Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions packages/coding-agent/src/core/agent-session-services.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import {
import { type CreateAgentSessionOptions, type CreateAgentSessionResult, createAgentSession } from "./sdk.ts";
import type { SessionManager } from "./session-manager.ts";
import { SettingsManager } from "./settings-manager.ts";
import { registerSubagentRuntimeDiagnosticSink } from "./subagents/runtime-diagnostics.ts";

/**
* Non-fatal issues collected while creating services or sessions.
Expand Down Expand Up @@ -227,6 +228,7 @@ export async function createAgentSessionServices(
export async function createAgentSessionFromServices(
options: CreateAgentSessionFromServicesOptions,
): Promise<CreateAgentSessionResult> {
registerSubagentRuntimeDiagnosticSink(options.sessionManager, options.services.diagnostics);
return createAgentSession({
cwd: options.services.cwd,
agentDir: options.services.agentDir,
Expand Down
3 changes: 2 additions & 1 deletion packages/coding-agent/src/core/agent-session.ts
Original file line number Diff line number Diff line change
Expand Up @@ -122,6 +122,7 @@ import {
import type { SlashCommandInfo } from "./slash-commands.ts";
import { createSyntheticSourceInfo, type SourceInfo } from "./source-info.ts";
import type { SubagentController } from "./subagents/controller.ts";
import { hasFixedHarnessSubagentSession } from "./subagents/session-runtime.ts";
import type { SubagentBatchResult, SubagentDeliveryBatch, SubagentSummary } from "./subagents/types.ts";
import { type BuildSystemPromptOptions, buildSystemPrompt } from "./system-prompt.ts";
import { type CodingAgentTelemetrySpan, startCodingAgentSpan } from "./telemetry.ts";
Expand Down Expand Up @@ -1260,7 +1261,7 @@ export class AgentSession {
}

private async _refreshSelectedHarnessAtPromptBoundary(): Promise<void> {
if (!this._harnessStateStore) return;
if (!this._harnessStateStore || hasFixedHarnessSubagentSession(this.sessionManager)) return;

const selected = await this._harnessStateStore.loadCurrent();
if (selected.manifest.version === this.activeHarnessVersion) return;
Expand Down
129 changes: 120 additions & 9 deletions packages/coding-agent/src/core/sdk.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,9 +25,22 @@ import type { ResourceLoader } from "./resource-loader.ts";
import { DefaultResourceLoader } from "./resource-loader.ts";
import { getDefaultSessionDir, persistSessionState, SessionManager } from "./session-manager.ts";
import { SettingsManager } from "./settings-manager.ts";
import { SubagentController } from "./subagents/controller.ts";
import { encodeSubagentRosterSnapshot, SUBAGENT_ROSTER_CUSTOM_TYPE } from "./subagents/persistence.ts";
import { captureSubagentSessionConfig, createSubagentSession } from "./subagents/services.ts";
import { type PreparedSubagentWake, SubagentController } from "./subagents/controller.ts";
import {
type ChildSnapshotV1,
encodeSubagentRosterSnapshot,
ParentOwnedSubagentSessionStore,
readSelectedBranchSubagentRoster,
SUBAGENT_ROSTER_CUSTOM_TYPE,
} from "./subagents/persistence.ts";
import { reportSubagentRuntimeWarning } from "./subagents/runtime-diagnostics.ts";
import {
capturePersistedSubagentConfig,
captureSubagentSessionConfig,
createSubagentSession,
type ResolvedRestoredSubagentConfig,
resolveRestoredSubagentConfig,
} from "./subagents/services.ts";
import { RootLocalEphemeralSubagentSessionManagerFactory } from "./subagents/session-manager-factory.ts";
import { time } from "./timings.ts";
import {
Expand Down Expand Up @@ -218,12 +231,7 @@ function createRootSubagentController(
);
return Object.freeze({
sessionManager,
config: Object.freeze({
model: Object.freeze({ provider: config.model.provider, id: config.model.id }),
thinkingLevel: config.thinkingLevel,
tools: config.tools,
harnessRevision: config.harnessVersionBundle?.manifest.version ?? null,
}),
config: capturePersistedSubagentConfig(config),
createSession: (signal: AbortSignal) =>
createSubagentSession(config, {
signal,
Expand Down Expand Up @@ -252,6 +260,108 @@ function createRootSubagentController(
});
}

function createPreparedSubagentWake(
childName: string,
sessionManager: SessionManager,
resolved: ResolvedRestoredSubagentConfig,
): PreparedSubagentWake {
return Object.freeze({
sessionManager,
config: resolved.persistedConfig,
...(resolved.warning === undefined ? {} : { warning: resolved.warning }),
createSession: (signal: AbortSignal) =>
createSubagentSession(resolved.sessionConfig, { signal, childName, sessionManager }),
});
}

async function createReplacementSubagentWake(
parent: AgentSession,
agentDir: string,
store: ParentOwnedSubagentSessionStore,
childName: string,
): Promise<PreparedSubagentWake> {
const sessionConfig = captureSubagentSessionConfig(parent, agentDir);
const sessionManager = store.createChild(childName);
return createPreparedSubagentWake(childName, sessionManager, {
sessionConfig,
persistedConfig: capturePersistedSubagentConfig(sessionConfig),
});
}

async function prepareRestoredSubagentWake(
parent: AgentSession,
agentDir: string,
store: ParentOwnedSubagentSessionStore,
snapshot: ChildSnapshotV1,
): Promise<PreparedSubagentWake> {
const resolved = await resolveRestoredSubagentConfig(parent, agentDir, snapshot.config, snapshot.name);
if (resolved.warning) reportSubagentRuntimeWarning(parent.sessionManager, resolved.warning);
try {
return createPreparedSubagentWake(
snapshot.name,
store.openChild(snapshot.name, snapshot.childSessionId, snapshot.childLeafId),
resolved,
);
} catch (error) {
const message = `Persisted subagent ${snapshot.name} history became unavailable: ${error instanceof Error ? error.message : String(error)}; creating a replacement child session`;
reportSubagentRuntimeWarning(parent.sessionManager, message);
const replacement = await createReplacementSubagentWake(parent, agentDir, store, snapshot.name);
return Object.freeze({ ...replacement, warning: message });
}
}

function restoreRootSubagents(
controller: SubagentController,
parent: AgentSession,
agentDir: string,
parentSessionManager: SessionManager,
): void {
if (!parentSessionManager.isPersisted()) return;
const roster = readSelectedBranchSubagentRoster(parentSessionManager);
for (const warning of roster.warnings) reportSubagentRuntimeWarning(parentSessionManager, warning);
if (!roster.found || roster.children.length === 0) return;

let store: ParentOwnedSubagentSessionStore;
try {
store = new ParentOwnedSubagentSessionStore(parentSessionManager);
} catch (error) {
const message = `Persisted subagent storage is unavailable: ${error instanceof Error ? error.message : String(error)}`;
reportSubagentRuntimeWarning(parentSessionManager, message);
for (const child of roster.children) {
const name = child.kind === "restorable" ? child.snapshot.name : child.name;
controller.restoreIsolated(name, child.kind === "isolated" ? child.error : message, () =>
Promise.reject(new Error(message)),
);
}
return;
}

for (const child of roster.children) {
if (child.kind === "isolated") {
controller.restoreIsolated(child.name, child.error, () =>
createReplacementSubagentWake(parent, agentDir, store, child.name),
);
continue;
}

const snapshot = child.snapshot;
let historyError: string | undefined;
try {
store.validateChild(snapshot.name, snapshot.childSessionId, snapshot.childLeafId);
} catch (error) {
historyError = `Persisted subagent ${snapshot.name} history is unavailable: ${error instanceof Error ? error.message : String(error)}`;
reportSubagentRuntimeWarning(parentSessionManager, historyError);
}
controller.restore(
snapshot,
historyError
? () => createReplacementSubagentWake(parent, agentDir, store, snapshot.name)
: () => prepareRestoredSubagentWake(parent, agentDir, store, snapshot),
historyError,
);
}
}

/**
* Create an AgentSession with the specified options.
*
Expand Down Expand Up @@ -534,6 +644,7 @@ export async function createAgentSession(options: CreateAgentSessionOptions = {}
}
}
subagentController?.bindParent(session);
if (subagentController) restoreRootSubagents(subagentController, session, agentDir, sessionManager);
const extensionsResult = resourceLoader.getExtensions();

return {
Expand Down
135 changes: 105 additions & 30 deletions packages/coding-agent/src/core/subagents/controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -107,9 +107,20 @@ interface SubagentRecord {
sessionManager?: CapturedSubagentSession["sessionManager"];
persistenceConfig?: CapturedSubagentSession["config"];
persistenceError?: string;
runtimeWarning?: string;
persistedChildSessionId?: string;
persistedChildLeafId?: string | null;
persistable?: boolean;
prepareWake?: PrepareSubagentWake;
leafUnsubscribe?: () => void;
}

export interface PreparedSubagentWake extends CapturedSubagentSession {
readonly warning?: string;
}

export type PrepareSubagentWake = () => Promise<PreparedSubagentWake>;

function isTerminalStatus(status: SubagentStatus): status is SubagentTerminalStatus {
return status === "idle" || status === "failed" || status === "interrupted";
}
Expand Down Expand Up @@ -248,6 +259,51 @@ export class SubagentController {
}));
}

restore(snapshot: ChildSnapshotV1, prepareWake: PrepareSubagentWake, isolationError?: string): void {
this.#assertReservable(snapshot.name);
const interrupted = snapshot.status === "queued" || snapshot.status === "running";
const isolated = isolationError !== undefined;
const timestamp = interrupted || isolated ? Date.now() : snapshot.updatedAt;
this.#records.set(snapshot.name, {
id: uuidv7(),
name: snapshot.name,
task: snapshot.task,
status: isolated ? "failed" : interrupted ? "interrupted" : snapshot.status,
createdAt: snapshot.createdAt,
updatedAt: timestamp,
...(snapshot.startedAt === undefined ? {} : { startedAt: snapshot.startedAt }),
...(interrupted || isolated
? { completedAt: timestamp }
: snapshot.completedAt === undefined
? {}
: { completedAt: snapshot.completedAt }),
...(snapshot.result === undefined ? {} : { finalText: snapshot.result }),
...((isolationError ?? snapshot.error) === undefined ? {} : { error: isolationError ?? snapshot.error }),
persistenceConfig: snapshot.config,
persistedChildSessionId: snapshot.childSessionId,
persistedChildLeafId: snapshot.childLeafId,
persistable: true,
prepareWake,
});
}

restoreIsolated(name: string, error: string, prepareWake: PrepareSubagentWake): void {
this.#assertReservable(name);
const timestamp = Date.now();
this.#records.set(name, {
id: uuidv7(),
name,
task: "Persisted subagent restoration failed",
status: "failed",
createdAt: timestamp,
updatedAt: timestamp,
completedAt: timestamp,
error,
persistable: false,
prepareWake,
});
}

spawn(
name: string,
task: string,
Expand Down Expand Up @@ -832,9 +888,9 @@ export class SubagentController {
status: agent.status,
...(record.coordinatedRun === undefined ? {} : { runId: record.coordinatedRun.id }),
...(record.finalText === undefined ? {} : { result: record.finalText }),
...((record.error ?? record.persistenceError) === undefined
...((record.error ?? record.persistenceError ?? record.runtimeWarning) === undefined
? {}
: { error: record.error ?? record.persistenceError }),
: { error: record.error ?? record.persistenceError ?? record.runtimeWarning }),
}),
];
});
Expand Down Expand Up @@ -869,50 +925,57 @@ export class SubagentController {
attempt: run.attempt,
retryAvailable,
...(record.finalText === undefined ? {} : { result: record.finalText }),
...((record.error ?? record.persistenceError) === undefined
...((record.error ?? record.persistenceError ?? record.runtimeWarning) === undefined
? {}
: { error: record.error ?? record.persistenceError }),
: { error: record.error ?? record.persistenceError ?? record.runtimeWarning }),
});
}

#createPersistenceSnapshot(interruptActive = false): ChildSnapshotV1[] {
const interruptionTimestamp = interruptActive ? Date.now() : undefined;
return [...this.#records.values()]
.sort((left, right) => left.name.localeCompare(right.name))
.map((record) => {
.flatMap((record) => {
if (record.persistable === false) return [];
const config = record.persistenceConfig;
const sessionManager = record.sessionManager;
if (!config || !sessionManager) {
const childSessionId = sessionManager ? sessionManager.getSessionId() : record.persistedChildSessionId;
const childLeafId = sessionManager ? sessionManager.getLeafId() : record.persistedChildLeafId;
if (!config || !childSessionId || childLeafId === undefined) {
throw new Error(`Persistent subagent state is unavailable: ${record.name}`);
}
const interrupted = interruptActive && (record.status === "queued" || record.status === "running");
const snapshotTimestamp = interruptionTimestamp ?? record.updatedAt;
const error = record.error ?? record.persistenceError;
return {
name: record.name,
task: record.task,
status: interrupted ? "interrupted" : record.status,
createdAt: record.createdAt,
updatedAt: interrupted ? snapshotTimestamp : record.updatedAt,
...(record.startedAt === undefined ? {} : { startedAt: record.startedAt }),
...(interrupted
? { completedAt: snapshotTimestamp }
: record.completedAt === undefined
? {}
: { completedAt: record.completedAt }),
...(record.finalText === undefined ? {} : { result: record.finalText }),
...(error === undefined ? {} : { error }),
childSessionId: sessionManager.getSessionId(),
childLeafId: sessionManager.getLeafId(),
config,
};
return [
{
name: record.name,
task: record.task,
status: interrupted ? "interrupted" : record.status,
createdAt: record.createdAt,
updatedAt: interrupted ? snapshotTimestamp : record.updatedAt,
...(record.startedAt === undefined ? {} : { startedAt: record.startedAt }),
...(interrupted
? { completedAt: snapshotTimestamp }
: record.completedAt === undefined
? {}
: { completedAt: record.completedAt }),
...(record.finalText === undefined ? {} : { result: record.finalText }),
...(error === undefined ? {} : { error }),
childSessionId,
childLeafId,
config,
},
];
});
}

#persistRosterBestEffort(changedName?: string, interruptActive = false): void {
if (!this.#persistRoster || this.#records.size === 0) return;
try {
this.#persistRoster(this.#createPersistenceSnapshot(interruptActive), false);
const snapshot = this.#createPersistenceSnapshot(interruptActive);
if (snapshot.length === 0) return;
this.#persistRoster(snapshot, false);
} catch (error) {
const message = `Subagent roster persistence failed: ${normalizeError(error)}`;
if (changedName) {
Expand Down Expand Up @@ -1082,6 +1145,18 @@ export class SubagentController {
if (record.status === "queued") {
throw new Error(`Cannot message queued subagent: ${name}`);
}
if (!record.session && record.prepareWake) {
if (!wake) throw new Error(`Cannot message restored subagent without wake: ${name}`);
const prepared = await record.prepareWake();
record.createSession = prepared.createSession;
record.sessionManager = prepared.sessionManager;
record.persistenceConfig = prepared.config;
record.persistedChildSessionId = prepared.sessionManager.getSessionId();
record.persistedChildLeafId = prepared.sessionManager.getLeafId();
record.persistable = true;
record.runtimeWarning = prepared.warning;
record.prepareWake = undefined;
}
if (record.status === "failed" || record.status === "interrupted") {
if (!wake) {
throw new Error(`Cannot message ${record.status} subagent without wake: ${name}`);
Expand All @@ -1098,17 +1173,17 @@ export class SubagentController {
this.#scheduleRun(record, message);
return { target: name, action: "message", status: "queued", delivery: "prompt" };
}
if (record.status === "idle" && wake) {
record.coordinatedRun = undefined;
this.#scheduleRun(record, message);
return { target: name, action: "message", status: "queued", delivery: "prompt" };
}

const session = record.session;
if (!session) {
throw new Error(`Subagent session is unavailable: ${name}`);
}
if (record.status === "idle") {
if (wake) {
record.coordinatedRun = undefined;
this.#scheduleRun(record, message);
return { target: name, action: "message", status: "queued", delivery: "prompt" };
}
await session.followUp(message);
return { target: name, action: "message", status: "idle", delivery: "follow_up" };
}
Expand Down
Loading
Loading