diff --git a/packages/zcode-tui/src/index.ts b/packages/zcode-tui/src/index.ts index 4b8c1466..3bbd91dc 100644 --- a/packages/zcode-tui/src/index.ts +++ b/packages/zcode-tui/src/index.ts @@ -2284,7 +2284,7 @@ class ZCodeTui { const failed: Array<{ detail: string; taskId: string }> = []; for (const job of active) { try { - const result = await cancelBackgroundTask(job.taskId); + const result = await cancelBackgroundTask(job.taskId, job.executionId); const failure = backgroundCancellationFailure(result); if (failure) { failed.push({ detail: failure, taskId: job.taskId }); @@ -5518,7 +5518,8 @@ class ZCodeTui { return "back"; } const active = isActiveBackgroundJob(job); - const canMessage = job.taskKind === "local_agent" && Boolean(this.options.sendBackgroundTaskMessage); + const canMessage = job.taskKind === "local_agent" && job.status !== "running_elsewhere" + && job.status !== "owner_unknown" && Boolean(this.options.sendBackgroundTaskMessage); const canStop = active && job.cancellable !== false && Boolean(this.options.cancelBackgroundTask); const items: ChoiceItem[] = [ ...(canMessage @@ -5574,7 +5575,7 @@ class ZCodeTui { if (action.value === "close") return "close"; if (action.value === "refresh") continue; if (action.value === "stop") { - await this.stopBackgroundTask(job.taskId); + await this.stopBackgroundTask(job.taskId, job); continue; } if (action.value === "resume" && !active) { @@ -5724,6 +5725,10 @@ class ZCodeTui { this.addNotice(`${backgroundTaskKindLabel(job)} tasks cannot receive messages.`, "warning"); return; } + if (job.status === "running_elsewhere" || job.status === "owner_unknown") { + this.addNotice(`Cannot message this agent: ${job.status.replaceAll("_", " ")}.`, "warning"); + return; + } if (!this.options.sendBackgroundTaskMessage) { this.addNotice("Background agent messaging is unavailable in this runtime.", "warning"); return; @@ -5737,7 +5742,7 @@ class ZCodeTui { taskId: job.taskId, message, summary: message.replace(/\s+/gu, " ").trim().slice(0, 200), - restart + restart, executionId: job.executionId }); const record = isRecord(result) ? result : undefined; const status = asString(record?.status); @@ -5784,7 +5789,7 @@ class ZCodeTui { this.addNotice(detail, "warning"); } - private async stopBackgroundTask(taskId: string): Promise { + private async stopBackgroundTask(taskId: string, selected?: RuntimeBackgroundJob): Promise { if (!taskId) { this.addNotice("Usage: /tasks stop ", "muted"); return; @@ -5793,7 +5798,7 @@ class ZCodeTui { this.addNotice("Background task cancellation is unavailable in this runtime.", "warning"); return; } - const job = this.runtimeProjection?.backgroundJobs.find((candidate) => candidate.taskId === taskId); + const job = selected ?? this.runtimeProjection?.backgroundJobs.find((candidate) => candidate.taskId === taskId); if (job && !isActiveBackgroundJob(job)) { this.addNotice(`Background task ${taskId} is already ${job.status}.`, "muted"); return; @@ -5812,7 +5817,7 @@ class ZCodeTui { this.updateRuntimeActivity(); } try { - await this.options.cancelBackgroundTask(taskId); + await this.options.cancelBackgroundTask(taskId, job?.executionId); await this.refreshRuntimeState(); } catch (error) { this.addNotice(error instanceof Error ? error.message : String(error), "error"); diff --git a/packages/zcode-tui/src/runtime-projection.ts b/packages/zcode-tui/src/runtime-projection.ts index c77e7649..7e1287f9 100644 --- a/packages/zcode-tui/src/runtime-projection.ts +++ b/packages/zcode-tui/src/runtime-projection.ts @@ -11,6 +11,8 @@ export type RuntimeBackgroundStatus = | "killed" | "stopped" | "spawn_error" + | "owner_unknown" + | "running_elsewhere" | "lost"; export type RuntimeTaskKind = "local_agent" | "local_bash" | "local_workflow" | "monitor_mcp" | "unknown"; @@ -39,6 +41,7 @@ export interface RuntimeActiveToolCall { export interface RuntimeBackgroundJob { taskId: string; + executionId?: string; taskKind: RuntimeTaskKind; toolCallId?: string; toolName?: string; @@ -136,7 +139,7 @@ const backgroundStatuses = new Set([ "killed", "stopped", "spawn_error", - "lost" + "lost", "owner_unknown", "running_elsewhere" ]); const todoStatuses = new Set(["pending", "in_progress", "completed"]); const todoPriorities = new Set(["high", "medium", "low"]); @@ -255,6 +258,7 @@ function backgroundJobFrom(value: unknown): RuntimeBackgroundJob | undefined { const rawError = isRecord(value.error) ? value.error : undefined; return { taskId, + executionId: stringField(value, "executionId"), taskKind, toolCallId: stringField(value, "toolCallId", "toolCallID"), toolName, diff --git a/packages/zcode-tui/src/types.ts b/packages/zcode-tui/src/types.ts index 0edf1bab..466c2b0b 100644 --- a/packages/zcode-tui/src/types.ts +++ b/packages/zcode-tui/src/types.ts @@ -109,12 +109,13 @@ export interface RuntimeAdapter { readSessionUsage?: () => Promise; readSessionResumeTarget?: () => Promise; readSessionDatabasePath?: () => Promise; - cancelBackgroundTask?: (taskId: string) => Promise; + cancelBackgroundTask?: (taskId: string, executionId?: string) => Promise; sendBackgroundTaskMessage?: (options: { taskId: string; message: string; summary: string; restart?: boolean; + executionId?: string; }) => Promise; previewFileRewind?: (targetMessageIds: string[]) => Promise; applyFileRewind?: (targetMessageIds: string[]) => Promise; diff --git a/scripts/check-runtime.ts b/scripts/check-runtime.ts index 1c32d7ef..28681443 100755 --- a/scripts/check-runtime.ts +++ b/scripts/check-runtime.ts @@ -150,7 +150,8 @@ if (patchRuntimeLoginModelDefaults(runtimeSource) !== runtimeSource || !runtimeSource.includes(".subscribeSessionEvents=") || !runtimeSource.includes(".sendBackgroundTaskMessage=async") || !runtimeSource.includes(".restoreTuiBackgroundTasks(") - || !runtimeSource.includes("projectChildEvents:e=>new ") + || !runtimeSource.includes(".withSubagentExecution(") + || !runtimeSource.includes(".stopTuiBackgroundTask(") || !runtimeSource.includes(".readTuiRuntimeProjection(") || !runtimeSource.includes(".sendTuiBackgroundTaskMessage(") || !runtimeSource.includes(".$zRestorePersistedBackgroundTasks=async $zApp=>") diff --git a/scripts/runtime-subagent-execution.ts b/scripts/runtime-subagent-execution.ts new file mode 100644 index 00000000..e96c9eac --- /dev/null +++ b/scripts/runtime-subagent-execution.ts @@ -0,0 +1,72 @@ +import { parseExpressionAt } from "acorn"; + +const helper = 'require(require("node:path").join(__dirname,"cli-config.cjs"))'; + +function replaceOnce(source: string, pattern: RegExp, change: (...match: string[]) => string): string { + if ([...source.matchAll(new RegExp(pattern.source, "gu"))].length !== 1) { + throw new Error(`Incompatible subagent runtime anchor: ${pattern.source}`); + } + return source.replace(pattern, change); +} + +function patchFunction(source: string, label: string, edit: (body: string) => string): string { + const name = new RegExp(`\\(([\\w$]+),"${label}"\\)`, "u").exec(source)?.[1]; + const start = name && source.indexOf(`function ${name}(`); + if (typeof start !== "number" || start < 0) throw new Error(`Missing runtime function ${label}`); + const offset = source.slice(start - 6, start) === "async " ? start - 6 : start; + const fn = parseExpressionAt(source, offset, { ecmaVersion: "latest" }); + return source.slice(0, offset) + edit(source.slice(offset, fn.end)) + source.slice(fn.end); +} + +/** Wrap the complete launch, including detached child work tracked by the port. */ +function ownExecution(method: string, resume: boolean): string { + const wrapped = replaceOnce(method, /([\w$]+\.register\([\w$]+\(\{isBackgrounded:![01],lifecycle:([\w$]+),)/u, + (match, _registration, lifecycle) => `return ${helper}.withSubagentExecution(${lifecycle},${resume},async()=>{${match}`); + return wrapped.slice(0, -1) + "})}"; +} + +export function patchSubagentExecution(runtime: string): string { + if (runtime.includes(".withSubagentExecution(")) { + if (runtime.split(".withSubagentExecution(").length !== 4 || !runtime.includes(".trackSubagentExecution(") + || !runtime.includes("!==$zHistory&&") || !runtime.includes(".subagentExecutionState(")) { + throw new Error("Incomplete subagent execution patch. Sync from the original runtime."); + } + return runtime; + } + runtime = patchFunction(runtime, "createExploreSubagentPort", port => { + port = replaceOnce(port, /(\([\w$]+,[\w$]+=!1\)=>\()([\w$]+\.add\(([\w$]+)\))/u, + (_match, start, add, work) => `${start}${helper}.trackSubagentExecution(${work}),${add}`); + for (const [name, next] of [["run", "start"], ["start", "getTask"]]) { + const begin = port.indexOf(`,async ${name}(`); + const end = port.indexOf(`,async ${next}(`, begin + 1); + if (begin < 0 || end < 0) throw new Error(`Missing subagent ${name} method`); + port = port.slice(0, begin) + ownExecution(port.slice(begin, end), false) + port.slice(end); + } + return port; + }); + runtime = patchFunction(runtime, "resumeTerminalAgentInBackground", body => ownExecution(body, true)); + for (const writer of ["writeAgentMetadataFile", "writeStoppedAgentArtifacts"]) { + runtime = patchFunction(runtime, writer, body => replaceOnce(body, + /agentId:([\w$]+)\.agentId,childSessionId:\1\.childSessionId/u, + (match, task) => `${match},executionId:${task}.executionId`)); + } + runtime = patchFunction(runtime, "restoreLocalAgentTaskFromRunMetadata", body => { + const output = /([\w$]+)=[\w$]+\.findTranscriptAgentOutputFile\?\./u.exec(body)?.[1]; + if (!output) throw new Error("Missing transcript output file for subagent ownership"); + return replaceOnce(body, /([\w$]+)\(([\w$]+)\.status,([\w$]+)\);if\(!/u, + (_m, status, run, updated) => `${run}.status==="running"?(${helper}.subagentExecutionState(${output},${run}.childSessionId)==="released"?"failed":void 0):${status}(${run}.status,${updated});if(!`); + }); + runtime = patchFunction(runtime, "collectPreviousRuntimeAgentInterruptions", body => + replaceOnce(body, /(let\{agentId:[\w$]+,childSessionId:([\w$]+),outputFile:([\w$]+)\}=[\w$]+;)/u, + (match, _declaration, child, output) => `${match}if(${helper}.subagentExecutionState(${output},${child})!=="released")continue;`)); + // TaskOutput may read a historical result without granting TaskStop or + // SendMessage access through the live registry. + runtime = patchFunction(runtime, "getTaskOutputInputFailure", body => + replaceOnce(body, /!([\w$]+)\.get\(([\w$]+\.task_id)\)/u, + (match, registry, id) => `${match}&&!${helper}.historicalTaskOutput(${registry},${id})`)); + runtime = replaceOnce(runtime, /let ([\w$]+)=([\w$]+\(([\w$]+)\))\.get\(([\w$]+)\.task_id\);if\(!\1\)(return [^;]+);if\(!\4\.block\)/u, + (_m, task, registry, _context, input, fail) => + `let $zHistory=${helper}.historicalTaskOutput(${registry},${input}.task_id),${task}=${registry}.get(${input}.task_id)??$zHistory;if(!${task})${fail};if(!${input}.block||${task}===$zHistory)`); + return replaceOnce(runtime, /(if\(![\w$]+\.block\|\|([\w$]+)===\$zHistory\)\{[^}]+?\.abortSignal\),)([\w$]+\(\2,[\w$]+\))/u, + (_match, branch, task, notify) => `${branch}${task}!==$zHistory&&${notify}`); +} diff --git a/scripts/sync-runtime.ts b/scripts/sync-runtime.ts index 10e95555..3a67cf69 100755 --- a/scripts/sync-runtime.ts +++ b/scripts/sync-runtime.ts @@ -14,6 +14,7 @@ import { } from "../src/runtime-capabilities.ts"; import { parseReleaseVersion, syncedReleaseVersion } from "./release-version.ts"; import { markRuntimeModified } from "./runtime-attribution.ts"; +import { patchSubagentExecution } from "./runtime-subagent-execution.ts"; import { hasRuntimeHeadlessLifecycle, patchRuntimeHeadlessLifecycle } from "./runtime-headless-patches.ts"; export { hasRuntimeHeadlessLifecycle, patchRuntimeHeadlessLifecycle } from "./runtime-headless-patches.ts"; import { hasRuntimeKeychainRecovery, patchRuntimeKeychainRecovery } from "./runtime-keychain-patches.ts"; @@ -498,26 +499,8 @@ export function patchRuntimeGoalFailurePause(runtime: string): string { ); } -/** Bind the read model already shipped in the runtime; fail sync if its contract changes. */ -export function runtimeSubagentQueryBridge(runtime: string): string { - const bind = (name: string, classExport = false): { symbol: string; init: string } => { - const pattern = classExport - ? /([A-Za-z_$][\w$]*)=class(?: [A-Za-z_$][\w$]*)?\{static\{[A-Za-z_$][\w$]*\(this,"EventReducer"/u - : new RegExp(`[A-Za-z_$][\\w$]*\\(([A-Za-z_$][\\w$]*),"${name}"\\)`, "u"); - const match = pattern.exec(runtime); - const init = match && [...runtime.slice(0, match.index) - .matchAll(/([A-Za-z_$][\w$]*)=[A-Za-z_$][\w$]*\(\(\)=>\{/gu)].at(-1)?.[1]; - if (!match || !init) throw new Error(`ZCode runtime is incompatible with subagent restoration (${name} anchor missing).`); - return { symbol: match[1]!, init }; - }; - const collect = bind("collectSubagentChildSessionIds"); - const project = bind("projectSessionSubagents"); - const reducer = bind("EventReducer", true); - const initializers = [...new Set([collect.init, project.init, reducer.init])].map((name) => `${name}()`); - return `(${initializers.join(",")},{collectChildSessionIds:${collect.symbol},projectSubagents:${project.symbol},projectChildEvents:e=>new ${reducer.symbol}().reduce(e)})`; -} - export function patchRuntimeTuiBridge(runtime: string): string { + runtime = patchSubagentExecution(runtime); // Upstream's login gate only checks account subscriptions. API-key providers // imported into the registry must remain usable without a separate OAuth login. runtime = runtime.replace( @@ -550,7 +533,7 @@ export function patchRuntimeTuiBridge(runtime: string): string { const projectionHelperMarker = ".readTuiRuntimeProjection("; const backgroundRestoreMarker = ".$zRestorePersistedBackgroundTasks=async $zApp=>"; const backgroundRestoreHelperMarker = ".restoreTuiBackgroundTasks("; - const subagentQueryMarker = "projectChildEvents:e=>new "; + const nativeHistoryMarker = ".restoreTuiBackgroundTasks($zApp)"; const backgroundRestoreBeforeSendMarker = ".$zSendInputWithoutBackgroundRestore="; const interruptTurnMarker = ".interruptTurn=async e=>"; const interruptWaitForIdleMarker = "e?.waitForIdle===!0"; @@ -625,7 +608,7 @@ export function patchRuntimeTuiBridge(runtime: string): string { && runtime.includes(taskMessageHelperMarker) && runtime.includes(projectionBridgeMarker) && runtime.includes(backgroundRestoreHelperMarker) - && runtime.includes(subagentQueryMarker) + && runtime.includes(nativeHistoryMarker) && runtime.includes(".stopTuiBackgroundTask(") && runtime.includes(backgroundRestoreMarker) && runtime.includes(backgroundRestoreBeforeSendMarker) && runtime.includes(".loadSessionContextMessages=async()=>await(await") @@ -737,12 +720,6 @@ export function patchRuntimeTuiBridge(runtime: string): string { getApp = "$zTuiGetApp"; } const assignments: string[] = []; - // Persisted background-agent restore: after a CLI restart + session resume the - // in-memory runtimeTaskRegistry is empty, so /tasks lists nothing and - // sendBackgroundTaskMessage cannot find the task. The runtime already ships a - // resume-from-child-session path (sendMessage on a stopped local_agent task), - // so register tasks from the native session/subagent read model. Its candidate - // selection handles the active branch and its reducer owns lifecycle state. const helper = 'require(require("node:path").join(__dirname,"cli-config.cjs"))'; const managedWorktreeMarker = ".createManagedWorktree=async $zDirectory=>"; const listManagedWorktreesMarker = ".listManagedWorktrees=async $zDirectory=>"; @@ -756,8 +733,8 @@ export function patchRuntimeTuiBridge(runtime: string): string { if (!patched.includes(restartTuiMarker)) { assignments.push(`${bridge}${restartTuiMarker}${helper}.restartTuiAtDirectory($zDirectory)`); } - const queries = runtimeSubagentQueryBridge(runtime); - const guardedBackgroundRestoreAssignment = `${bridge}.$zRestorePersistedBackgroundTasks=async $zApp=>await ${helper}.restoreTuiBackgroundTasks($zApp,${queries})`; + if (!runtime.includes("async readSubagents(")) throw new Error("Missing native subagent history reader."); + const guardedBackgroundRestoreAssignment = `${bridge}.$zRestorePersistedBackgroundTasks=async $zApp=>await ${helper}.restoreTuiBackgroundTasks($zApp)`; const projectionAssignment = `${bridge}.readRuntimeProjection=async()=>{let $zRuntimeProjectionBridge=await ${getApp}();return await ${helper}.readTuiRuntimeProjection($zRuntimeProjectionBridge,${bridge})}`; const taskMessageAssignment = `${bridge}.sendBackgroundTaskMessage=async e=>await ${helper}.sendTuiBackgroundTaskMessage(await ${getApp}(),${bridge},e)`; if (!listSkillsBridgePattern.test(patched)) { @@ -807,7 +784,7 @@ export function patchRuntimeTuiBridge(runtime: string): string { assignments.push(projectionAssignment); } } - if (!patched.includes(backgroundRestoreHelperMarker) || !patched.includes(subagentQueryMarker)) { + if (!patched.includes(nativeHistoryMarker)) { const existingRestoreStart = patched.indexOf(`${bridge}.$zRestorePersistedBackgroundTasks=async $zApp=>`); if (existingRestoreStart >= 0) { const existingRestoreEnd = patched.indexOf(`,${bridge}.`, existingRestoreStart); @@ -822,8 +799,11 @@ export function patchRuntimeTuiBridge(runtime: string): string { if (!patched.includes(".readSessionUsage=async()=>await(await")) { assignments.push(`${bridge}.readSessionUsage=async()=>await(await ${getApp}()).readSessionUsage?.()??null`); } - if (!patched.includes(".cancelBackgroundTask=async")) { - assignments.push(`${bridge}.cancelBackgroundTask=async e=>await(await ${getApp}()).cancelBackgroundTask?.(e)??null`); + if (!patched.includes(".stopTuiBackgroundTask(")) { + const previous = `${bridge}.cancelBackgroundTask=async e=>await(await ${getApp}()).cancelBackgroundTask?.(e)??null`; + const stop = `${bridge}.cancelBackgroundTask=async(e,id)=>await ${helper}.stopTuiBackgroundTask(await ${getApp}(),e,id)`; + if (patched.includes(previous)) patched = patched.replace(previous, () => stop); + else assignments.push(stop); } if (!patched.includes(".previewFileRewind=async e=>")) { assignments.push(`${bridge}.previewFileRewind=async e=>{let t=await ${getApp}();return await t.runtime?.previewWorkspaceFileRewind?.({targetMessageIds:e})??null}`); @@ -1823,7 +1803,7 @@ export const runtimePatchPlan: readonly RuntimePatchDefinition[] = [ apply: patchRuntimeTuiBridge, verify: (runtime) => runtime.includes(".readRuntimeProjection=async()=>{let $zRuntimeProjectionBridge=await ") && runtime.includes(".loadSessionContextMessages=async()=>await(await") - && runtime.includes("projectChildEvents:e=>new ") + && runtime.includes(".withSubagentExecution(") && runtime.includes("readTuiShowReasoning(process.env)") }, { diff --git a/src/runtime-background-restore.ts b/src/runtime-background-restore.ts index 3c2fe6b4..c8f937d9 100644 --- a/src/runtime-background-restore.ts +++ b/src/runtime-background-restore.ts @@ -1,102 +1,73 @@ -import type { RuntimeSubagentQueries, RuntimeTask, RuntimeTuiApp } from "./runtime-tui-bridge.ts"; +import { readSubagentRun, subagentExecutionState } from "./subagent-execution.ts"; +import type { RuntimeTask, RuntimeTuiApp } from "./runtime-tui-bridge.ts"; -const maximumReminderTasks = 32; -const maximumReminderLength = 4_000; -const maximumRestoredTasks = 64; +const history = new WeakMap>(); +const reads = new WeakMap }>(); -async function restoreSessionChildren( - app: RuntimeTuiApp, sessionId: string, queries: RuntimeSubagentQueries -): Promise { - const store = app.runtime?.sessionStore; - const eventStore = app.runtime?.getSessionEventStore?.(); - if (!store || !eventStore) return []; - const parentSession = await store.getSession(sessionId); - if (!parentSession) return []; - const [messages, parentEvents, parentProjection] = await Promise.all([ - store.messages({ sessionID: sessionId }), eventStore.getEvents(sessionId), app.runtime?.getProjection?.() - ]); - // Use the same active-branch candidates and ownership checks as upstream's - // subagent observation API. Event storage alone is empty after a cold resume. - const ids = [...new Set(queries.collectChildSessionIds(parentSession, messages, parentEvents))]; - const children = await Promise.all(ids.map(async (id) => { - const session = await store.getSession(id); - if (!session || session.parentID !== sessionId || session.taskType !== "subagent_child") return null; - const [messages, events] = await Promise.all([ - store.messages({ sessionID: id }), eventStore.getEvents(id) - ]); - return { session, messages, projection: events.length ? queries.projectChildEvents(events) : undefined }; - })); - const valid = children.filter((child) => child !== null); - const projection = queries.projectSubagents({ - revision: 0, parentSession, messages, parentEvents, parentProjection, - childSessionsById: new Map(valid.map((child) => [child.session.id, child.session])), - childMessagesById: new Map(valid.map((child) => [child.session.id, child.messages])), - childProjectionsById: new Map(valid.flatMap((child) => - child.projection ? [[child.session.id, child.projection] as const] : [])) - }); - return [...projection.running, ...projection.ended].map((agent): RuntimeTask => ({ - taskId: agent.agentId ?? agent.toolCallId, - agentId: agent.agentId ?? agent.toolCallId, - agentType: agent.subagentType, - childSessionId: agent.childSessionId, - description: agent.title, - isBackgrounded: true, - parentSessionId: sessionId, - parentToolCallId: agent.toolCallId, - startedAt: agent.startedAt, - completedAt: agent.endedAt, - status: ["running", "waiting", "blocked"].includes(agent.status) ? "running" - : agent.status === "success" ? "completed" : agent.status === "failed" ? "failed" : "stopped", - error: agent.status === "failed" ? agent.summary : undefined, - output: agent.status === "success" && agent.summary - ? { status: "completed", content: [{ type: "text", text: agent.summary }] } : undefined, - taskType: "local_agent", - type: "local_agent" - })); +export function historicalTaskOutput(registry: object, id: string): RuntimeTask | undefined { + const task = history.get(registry)?.get(id); + return task && ["completed", "failed", "killed"].includes(task.status ?? "") ? task : undefined; +} + +export function historicalTasks(app: RuntimeTuiApp): RuntimeTask[] { + const registry = app.runtime?.runtimeTaskRegistry; + return registry ? [...(history.get(registry)?.values() ?? [])] : []; } -async function restore(app: RuntimeTuiApp, queries: RuntimeSubagentQueries): Promise { +async function readHistory(app: RuntimeTuiApp, session: string): Promise { const runtime = app.runtime; const registry = runtime?.runtimeTaskRegistry; - const sessionId = app.sessionId; - if (!registry?.register || typeof sessionId !== "string" || sessionId === app.$zRestoredBackgroundTasksSession) return; - app.$zRestoredBackgroundTasksLog = []; - try { - const tasks = await restoreSessionChildren(app, sessionId, queries); - // A restore may finish after navigation, or after a live task was registered. - if (app.sessionId !== sessionId || app.runtime !== runtime) return; - const restored: RuntimeTask[] = []; - for (const task of tasks) { - if (registry.get?.(task.taskId)) continue; - registry.register(task); - restored.push(task); + if (!app.readSubagents || !registry) return; + const tasks = new Map(); + let cursor: string | undefined; + do { + const page = await app.readSubagents({ endedCursor: cursor, endedLimit: 100 }); + for (const agent of [...page.running, ...page.ended.items]) { + const id = agent.agentId ?? agent.toolCallId; + const live = registry.get?.(id); + if (live?.status === "running") continue; + const output = runtime.transcriptAgentOutputFiles?.get(id) ?? + (typeof live?.outputFile === "string" ? live.outputFile : undefined); + const owner = subagentExecutionState(output, agent.childSessionId); + const run = readSubagentRun(output, agent.childSessionId, id); + const savedTerminal = run && { completed: "completed", failed: "failed", stopped: "killed" }[run.status]; + const projectedTerminal = { success: "completed", failed: "failed", cancelled: "killed" }[agent.status]; + let status = savedTerminal ?? projectedTerminal ?? "owner_unknown"; + if (owner === "held") status = "running_elsewhere"; + else if (run?.status === "running" || !savedTerminal && !projectedTerminal) { + status = owner === "released" ? "lost" : "owner_unknown"; + } + if (live && (live.status === status || live.executionId === run?.executionId && run?.executionId)) continue; + tasks.set(id, { + taskId: id, agentId: id, agentType: agent.subagentType, type: "local_agent", + childSessionId: agent.childSessionId, parentSessionId: session, parentToolCallId: agent.toolCallId, + description: agent.title, isBackgrounded: true, status, outputFile: output, + cancellable: false, startedAt: agent.startedAt, completedAt: agent.endedAt, + error: status === "failed" ? agent.summary : undefined, + output: status === "completed" && agent.summary + ? { status: "completed", content: [{ type: "text", text: agent.summary }] } : undefined + }); } - app.$zRestoredBackgroundTasksSession = sessionId; - if (restored.length === 0) return; - const taskIds = restored.slice(-maximumReminderTasks) - .map((task) => `- ${task.taskId} (${task.status})`).join("\n").slice(0, maximumReminderLength); - runtime?.messageHistory?.addAttachment?.("task_status", - "Background agent tasks from this resumed session have been restored and are available again.\n" - + 'Earlier TaskOutput errors saying "No task found" occurred before restoration and are stale.\n' - + "Use TaskOutput to collect results or SendMessage to continue a task. Do not assume these tasks were lost.\n" - + `Restored task IDs:\n${taskIds}`); - app.$zRestoredBackgroundTasksLog = [...(app.$zRestoredBackgroundTasksLog ?? []), ...restored].slice(-maximumRestoredTasks); - } catch { - // Restoration is supplementary. Let the next query retry a failed read. - if (app.sessionId === sessionId) app.$zRestoredBackgroundTasksSession = undefined; - } + cursor = page.ended.nextCursor; + } while (cursor); + if (app.sessionId === session && app.runtime === runtime) history.set(registry, tasks); } -const pendingRestores = new WeakMap>(); - -export async function restoreTuiBackgroundTasks(app: RuntimeTuiApp, queries: RuntimeSubagentQueries): Promise { - const pending = pendingRestores.get(app); - if (pending) { - await pending; - return restoreTuiBackgroundTasks(app, queries); +export async function restoreTuiBackgroundTasks(app: RuntimeTuiApp): Promise { + const session = app.sessionId; + const registry = app.runtime?.runtimeTaskRegistry; + if (!session || !registry) return; + const read = reads.get(registry); + if (read?.session === session && Date.now() - read.time < 2000) { + const releasedSinceRead = historicalTasks(app).some(task => task.status === "running_elsewhere" && + subagentExecutionState(task.outputFile as string, task.childSessionId as string) !== "held"); + if (read.time === Infinity || !releasedSinceRead) return read.pending; } - const operation = restore(app, queries); - pendingRestores.set(app, operation); - try { await operation; } - finally { pendingRestores.delete(app); } + if (read?.session !== session) history.delete(registry); + const entry = { session, time: Infinity, pending: Promise.resolve() }; + reads.set(registry, entry); + entry.pending = readHistory(app, session).then(() => { entry.time = Date.now(); }, () => { + if (reads.get(registry) === entry) reads.delete(registry); + }); + return entry.pending; } diff --git a/src/runtime-config-bridge.ts b/src/runtime-config-bridge.ts index 47986af1..c8066949 100644 --- a/src/runtime-config-bridge.ts +++ b/src/runtime-config-bridge.ts @@ -6,10 +6,11 @@ import { cliSettingsPath, desktopSettingsPath, legacyCliConfigPath, providerConf export { assertSessionModelReady, readSessionModelState } from "./session-model-recovery.ts"; export { assertResumableSession, ensureSessionForTitle, listSessionsForPicker, readSessionDatabasePath, readSessionResumeTarget } from "./runtime-session-lifecycle.ts"; -export { readTuiRuntimeProjection, sendTuiBackgroundTaskMessage } from "./runtime-tui-bridge.ts"; +export { readTuiRuntimeProjection, sendTuiBackgroundTaskMessage, stopTuiBackgroundTask } from "./runtime-tui-bridge.ts"; export { createManagedWorktree, listManagedWorktrees, restartTuiAtDirectory } from "./runtime-worktrees.ts"; export { createTuiWorkflowManagement, startTuiSavedWorkflow } from "./runtime-workflow-bridge.ts"; -export { restoreTuiBackgroundTasks } from "./runtime-background-restore.ts"; +export { restoreTuiBackgroundTasks, historicalTaskOutput } from "./runtime-background-restore.ts"; +export { subagentExecutionState, trackSubagentExecution, withSubagentExecution } from "./subagent-execution.ts"; export { withRecursiveWorkspacePathSuggestions } from "./runtime-workspace-paths.ts"; export { installSqliteWriteRecovery, pruneSqliteUsage, sqliteRecoveryStats } from "./runtime-sqlite-recovery.ts"; export { appServerRegistryOptions } from "./app-server-auth.ts"; diff --git a/src/runtime-tui-bridge.ts b/src/runtime-tui-bridge.ts index bb83e3f1..0746fddc 100644 --- a/src/runtime-tui-bridge.ts +++ b/src/runtime-tui-bridge.ts @@ -1,5 +1,6 @@ import { execFile } from "node:child_process"; import { promisify } from "node:util"; +import { historicalTasks } from "./runtime-background-restore.ts"; const execFileAsync = promisify(execFile); const workspaceSnapshots = new WeakMap { export interface RuntimeTuiApp { sessionId?: string; - $zRestoredBackgroundTasksSession?: string; - $zRestoredBackgroundTasksLog?: unknown[]; + readSubagents?(input: { endedCursor?: string; endedLimit: number }): Promise<{ + running: RuntimeSubagent[]; ended: { items: RuntimeSubagent[]; nextCursor?: string }; + }>; + cancelBackgroundTask?(id: string): Promise; loadSessionTranscript?(): Promise; readExecutionState(): Promise | unknown; runtime?: { - sessionStore?: RuntimeSessionStore; - getSessionEventStore?(): RuntimeSessionEventStore; + transcriptAgentOutputFiles?: Map; + stopBackgroundTask?(id: string, options: { strict: true; initiator: "user"; expectedExecutionId: string }): + Promise<{ ok: boolean; reason?: string }>; getProjection?(): Promise | undefined> | Record | undefined; getSessionId?(): string; runtimeTaskRegistry?: { all?(): Record; get?(taskId: string): RuntimeTask | undefined; - register?(task: RuntimeTask): unknown; }; - messageHistory?: { addAttachment?(source: string, text: string): unknown }; subagentPort?: { sendMessage?(input: Record): Promise; - stopTask?(taskId: string): Promise; }; workingDirectory?: string; rootTraceContext?: unknown; }; } -export interface RuntimeSessionInfo { - id: string; - parentID?: string; - taskType?: string; - title?: string; - time?: { created?: number; updated?: number }; -} - -export interface RuntimeSessionStore { - getSession(sessionId: string): Promise; - messages(input: { sessionID: string }): Promise; -} - -export interface RuntimeSessionEventStore { - getEvents(sessionId: string): Promise; -} - export interface RuntimeSubagent { agentId?: string; childSessionId: string; @@ -72,22 +56,6 @@ export interface RuntimeSubagent { summary?: string; } -/** Implemented by the extracted runtime's native session query and reducer. */ -export interface RuntimeSubagentQueries { - collectChildSessionIds(session: RuntimeSessionInfo, messages: unknown[], events: unknown[]): string[]; - projectChildEvents(events: unknown[]): unknown; - projectSubagents(input: { - revision: number; - parentSession: RuntimeSessionInfo; - messages: unknown[]; - parentEvents: unknown[]; - parentProjection?: Record; - childSessionsById: Map; - childMessagesById: Map; - childProjectionsById: Map; - }): { running: RuntimeSubagent[]; ended: RuntimeSubagent[] }; -} - export interface RuntimeTuiBridge { $zRestorePersistedBackgroundTasks?(app: RuntimeTuiApp): Promise; } @@ -100,6 +68,7 @@ function taskDetail(task: RuntimeTask): Record { const kind = task.taskType ?? task.type; return { taskId: task.taskId, + executionId: task.executionId, taskKind: kind, agentId: task.agentId, agentType: task.agentType, @@ -118,7 +87,7 @@ function taskDetail(task: RuntimeTask): Record { cancelRequestedAt: running ? null : task.cancelRequestedAt, blocked: running ? null : task.blocked, blockedReason: running ? null : task.blockedReason, - cancellable: kind === "local_agent" ? running : task.cancellable + cancellable: kind === "local_agent" ? running && typeof task.executionId === "string" : task.cancellable }; } @@ -152,10 +121,20 @@ export async function readTuiRuntimeProjection( await bridge.$zRestorePersistedBackgroundTasks?.(app); const projection = await app.runtime?.getProjection?.(); if (!projection) return null; - const details = Object.values(app.runtime?.runtimeTaskRegistry?.all?.() ?? {}) - .filter((task) => task.isBackgrounded === true).map(taskDetail); + const live = Object.values(app.runtime?.runtimeTaskRegistry?.all?.() ?? {}) + .filter(task => task.isBackgrounded === true); + const history = historicalTasks(app).filter(task => !live.some(current => + current.taskId === task.taskId && current.status === "running")); + const details = [...live, ...history].map(taskDetail); const tasks: Array> = Array.isArray(projection.backgroundTasks) - ? projection.backgroundTasks.slice() : []; + ? projection.backgroundTasks.map(task => { + const kind = task.taskKind ?? task.taskType ?? task.type; + if ((kind === "local_agent" || kind === "agent" || task.toolName === "Agent") && task.status === "running") { + // A projection can outlive its runner. Only a live detail below grants control. + return { ...task, status: "owner_unknown", cancellable: false, executionId: undefined }; + } + return task; + }) : []; for (const detail of details) { const index = tasks.findIndex((existing) => existing.taskId === detail.taskId); if (index < 0) tasks.push(detail); @@ -170,8 +149,7 @@ export async function readTuiRuntimeProjection( workspace: await readRuntimeWorkspace(app.runtime), backgroundTasks: tasks, backgroundTaskDetails: details, - restoredBackgroundTasks: Array.isArray(app.$zRestoredBackgroundTasksLog) - ? app.$zRestoredBackgroundTasksLog : [] + restoredBackgroundTasks: history.filter(task => ["completed", "failed", "lost"].includes(task.status ?? "")).map(taskDetail) }; } @@ -180,6 +158,20 @@ export interface BackgroundTaskMessage { message: string; summary?: string; restart?: boolean; + executionId?: string; +} + +export async function stopTuiBackgroundTask(app: RuntimeTuiApp, id: string, executionId?: string): Promise { + const task = app.runtime?.runtimeTaskRegistry?.get?.(id); + if (!executionId && task?.type !== "local_agent" && !historicalTasks(app).some(row => row.taskId === id)) { + return app.cancelBackgroundTask?.(id); + } + if (!executionId || task?.executionId !== executionId || !app.runtime?.stopBackgroundTask) { + throw new Error("This agent execution is no longer available to stop."); + } + const result = await app.runtime.stopBackgroundTask(id, { expectedExecutionId: executionId, initiator: "user", strict: true }); + if (!result.ok) throw new Error(`Agent stop rejected: ${result.reason}`); + return result; } export async function sendTuiBackgroundTaskMessage( @@ -189,24 +181,15 @@ export async function sendTuiBackgroundTaskMessage( ): Promise { await bridge.$zRestorePersistedBackgroundTasks?.(app); const runtime = app.runtime; - let task = runtime?.runtimeTaskRegistry?.get?.(input?.taskId); - if (!task && typeof app.sessionId === "string") { - app.$zRestoredBackgroundTasksSession = undefined; - await bridge.$zRestorePersistedBackgroundTasks?.(app); - task = runtime?.runtimeTaskRegistry?.get?.(input?.taskId); - } + const local = runtime?.runtimeTaskRegistry?.get?.(input?.taskId); + const task = local ?? historicalTasks(app).find(row => row.taskId === input?.taskId); if (!runtime?.subagentPort?.sendMessage) throw new Error("Background agent messaging is unavailable in this runtime."); if (!task || (task.type ?? task.taskType) !== "local_agent") throw new Error("The selected task is not a local agent."); if (typeof input?.message !== "string" || !input.message.trim()) throw new Error("Enter a message for the background agent."); const message = input.message.trim().slice(0, maximumTaskMessageLength); const summary = (typeof input.summary === "string" ? input.summary : message) .replace(/\s+/g, " ").trim().slice(0, maximumTaskSummaryLength); - if (input.restart === true && task.status === "running") { - if (!runtime.subagentPort.stopTask) throw new Error("Background agent restart is unavailable in this runtime."); - await runtime.subagentPort.stopTask(input.taskId); - task = runtime.runtimeTaskRegistry?.get?.(input.taskId); - if (!task) throw new Error("The background agent stopped but could not be restored."); - } + if (input.restart) await stopTuiBackgroundTask(app, input.taskId, input.executionId); return await runtime.subagentPort.sendMessage({ sessionId: task.parentSessionId ?? runtime.getSessionId?.(), turnId: task.turnId ?? "tui-task-message", diff --git a/src/subagent-execution.ts b/src/subagent-execution.ts new file mode 100644 index 00000000..2d39f7ae --- /dev/null +++ b/src/subagent-execution.ts @@ -0,0 +1,104 @@ +import { AsyncLocalStorage } from "node:async_hooks"; +import { createHash } from "node:crypto"; +import { existsSync, mkdirSync, readFileSync } from "node:fs"; +import { dirname, join } from "node:path"; +import type { DatabaseSync } from "node:sqlite"; + +interface Execution { + childSessionId: string; + outputFile: string; + agentId: string; + executionId: string; +} + +const active = new AsyncLocalStorage<{ retain(): () => void }>(); + +function lockPath(output: string, child: string): string { + const key = createHash("sha256").update(child).digest("hex"); + return join(dirname(output), `execution-${key}.sqlite`); +} + +function busy(error: unknown): boolean { + const code = (error as { errcode?: number })?.errcode; + return code === 5 || code === 6; +} + +function openDatabase(path: string, readOnly = false): DatabaseSync { + const sqlite: typeof import("node:sqlite") = require("node:sqlite"); + return new sqlite.DatabaseSync(path, { readOnly }); +} + +interface RunRecord { + agentId: string; + childSessionId: string; + executionId?: string; + status: string; +} + +export function readSubagentRun(output: string | undefined, child: string, agent?: string): RunRecord | undefined { + if (!output) return; + try { + const run = JSON.parse(readFileSync(join(dirname(output), "metadata.json"), "utf8")); + if (run?.childSessionId === child && (!agent || run.agentId === agent)) return run; + } catch { /* A legacy or partially written record cannot establish an owner. */ } +} + +function previousExecution(db: DatabaseSync): unknown { + if (!db.prepare("SELECT 1 FROM sqlite_master WHERE type='table' AND name='execution'").get()) return; + return db.prepare("SELECT id FROM execution WHERE singleton=1").get()?.id; +} + +export function subagentExecutionState(output?: string, child?: string): "held" | "released" | "unknown" { + if (!output || !child) return "unknown"; + const path = lockPath(output, child); + if (!existsSync(path)) return "unknown"; + let db: DatabaseSync | undefined; + try { + db = openDatabase(path, true); + const generation = previousExecution(db); + return generation && generation === readSubagentRun(output, child)?.executionId ? "released" : "unknown"; + } catch (error) { + return busy(error) ? "held" : "unknown"; + } finally { + db?.close(); + } +} + +export async function withSubagentExecution(task: Execution, resume: boolean, work: () => Promise): Promise { + mkdirSync(dirname(task.outputFile), { recursive: true }); + const db = openDatabase(lockPath(task.outputFile, task.childSessionId)); + let references = 1; + const release = () => { if (--references === 0) db.close(); }; + try { + // EXCLUSIVE locking mode retains the OS lock across COMMIT. The marker is + // durable before the model starts and a killed process drops its lock. + db.exec("PRAGMA locking_mode=EXCLUSIVE; BEGIN EXCLUSIVE"); + if (resume) { + const metadata = readSubagentRun(task.outputFile, task.childSessionId, task.agentId); + const generation = previousExecution(db); + if (!metadata || (!["completed", "failed", "stopped"].includes(metadata.status) && + !(metadata.status === "running" && generation && generation === metadata.executionId))) { + throw new Error("Cannot resume this agent because its previous execution owner is unknown."); + } + } + db.exec("CREATE TABLE IF NOT EXISTS execution (singleton INTEGER PRIMARY KEY, id TEXT NOT NULL)"); + db.prepare("INSERT OR REPLACE INTO execution VALUES (1, ?)").run(task.executionId); + db.exec("COMMIT"); + } catch (error) { + db.close(); + if (busy(error)) throw new Error("This agent execution is still owned by a runtime."); + throw error; + } + try { + return await active.run({ retain() { references++; return release; } }, work); + } finally { + release(); + } +} + +// The native port tracks both detached finalization and the underlying child +// promise (which can outlive cancellation). Keep the lock until both settle. +export function trackSubagentExecution(work: Promise): void { + const release = active.getStore()?.retain(); + if (release) void work.then(release, release); +} diff --git a/test/node/subagent-execution.test.cjs b/test/node/subagent-execution.test.cjs new file mode 100644 index 00000000..482c21aa --- /dev/null +++ b/test/node/subagent-execution.test.cjs @@ -0,0 +1,89 @@ +const assert = require("node:assert/strict"); +const { fork } = require("node:child_process"); +const { once } = require("node:events"); +const { mkdtemp, rm, writeFile } = require("node:fs/promises"); +const { tmpdir } = require("node:os"); +const { join } = require("node:path"); +const test = require("node:test"); +const bridge = require("../../vendor/cli-config.cjs"); + +const task = outputFile => ({ outputFile, agentId: "agent-306", childSessionId: "child-306", executionId: crypto.randomUUID() }); + +if (process.argv[2] === "contender") { + process.once("message", async output => { + try { + await bridge.withSubagentExecution(task(output), true, () => new Promise(resolve => { + process.send("acquired"); + process.once("message", resolve); + })); + } catch (error) { + process.send(error.message); + } finally { + process.disconnect(); + } + }); +} else { + test("simultaneous cold resumes have one owner and legacy running metadata cannot be claimed", async () => { + const directory = await mkdtemp(join(tmpdir(), "agent-ownership-")); + const output = join(directory, "output.txt"); + const metadata = join(directory, "metadata.json"); + const workers = []; + try { + await writeFile(metadata, JSON.stringify({ ...task(output), status: "running" })); + await assert.rejects(bridge.withSubagentExecution(task(output), true, () => assert.fail()), /owner is unknown/); + assert.equal(bridge.subagentExecutionState(output, task(output).childSessionId), "unknown"); + await writeFile(metadata, JSON.stringify({ ...task(output), status: "completed" })); + const results = await Promise.all([0, 1].map(async () => { + const worker = fork(__filename, ["contender"], { stdio: ["ignore", "ignore", "inherit", "ipc"] }); + workers.push(worker); + const response = once(worker, "message"); + worker.send(output); + return (await response)[0]; + })); + assert.equal(results.filter(result => result === "acquired").length, 1); + assert.match(results.find(result => result !== "acquired"), /still owned/); + } finally { + await Promise.all(workers.map(async worker => { + if (worker.exitCode !== null || worker.signalCode !== null) return; + const exited = once(worker, "exit"); + worker.kill(); + await exited; + })); + await rm(directory, { recursive: true, force: true }); + } + }); + + test("stale stop and restart requests never reach the current execution", async () => { + const calls = []; + const current = { taskId: "agent", type: "local_agent", status: "running", executionId: "second" }; + const app = { runtime: { runtimeTaskRegistry: { get: () => current }, + stopBackgroundTask: async (...args) => { calls.push(args); return { ok: true }; }, + subagentPort: { sendMessage: () => assert.fail() } } }; + await assert.rejects(bridge.stopTuiBackgroundTask(app, "agent", "first"), /no longer available/); + await assert.rejects(bridge.sendTuiBackgroundTaskMessage(app, {}, { + taskId: "agent", executionId: "first", restart: true, message: "continue" + }), /no longer available/); + assert.deepEqual(calls, []); + await bridge.stopTuiBackgroundTask(app, "agent", "second"); + assert.deepEqual(calls, [["agent", { expectedExecutionId: "second", initiator: "user", strict: true }]]); + }); + + test("cold history preserves terminal output and leaves unowned tasks out of the live registry", async () => { + const registry = { get: () => undefined, all: () => ({}), register: () => assert.fail() }; + const agent = status => ({ agentId: status, childSessionId: status, toolCallId: status, + subagentType: "general-purpose", title: "fixture", status, summary: "saved result", startedAt: 10 }); + const app = { sessionId: "parent", readExecutionState: () => ({}), + runtime: { runtimeTaskRegistry: registry, getProjection: () => ({}) }, + readSubagents: async ({ endedCursor }) => endedCursor + ? { running: [], ended: { items: [agent("failed"), agent("cancelled")] } } + : { running: [agent("running")], ended: { items: [agent("success"), agent("lost")], nextCursor: "more" } } }; + await bridge.restoreTuiBackgroundTasks(app); + const projection = await bridge.readTuiRuntimeProjection(app, {}); + assert.deepEqual(Object.fromEntries(projection.backgroundTasks.map(row => [row.agentId, row.status])), { + running: "owner_unknown", lost: "owner_unknown", success: "completed", failed: "failed", cancelled: "killed" + }); + assert.ok(projection.backgroundTasks.every(row => row.cancellable === false)); + assert.equal(bridge.historicalTaskOutput(registry, "success").output.content[0].text, "saved result"); + assert.equal(bridge.historicalTaskOutput(registry, "running"), undefined); + }); +} diff --git a/test/runtime/subagent-execution.test.ts b/test/runtime/subagent-execution.test.ts new file mode 100644 index 00000000..8bfc40df --- /dev/null +++ b/test/runtime/subagent-execution.test.ts @@ -0,0 +1,91 @@ +import { expect, test } from "bun:test"; +import { readFile, writeFile } from "node:fs/promises"; +import { join } from "node:path"; +import { cliSettingsPath, ensureCliSettings } from "../../src/model-access.ts"; +import { writeProviderFixture } from "../fixtures/provider-config.ts"; +import { runtimeTestEnv } from "../fixtures/runtime-env.ts"; +import { ScenarioWorkspace } from "../tui/harness/scenario-workspace.ts"; +import { TerminalSession } from "../tui/harness/terminal-session.ts"; + +test.skipIf(process.platform === "win32")("a second CLI cannot duplicate a live child and can resume it after SIGKILL", async () => { + await using workspace = await ScenarioWorkspace.create({ prefix: "zcode-agent-owner-" }); + const env = runtimeTestEnv(workspace.home); + await ensureCliSettings(env); + const settings = JSON.parse(await readFile(cliSettingsPath(env), "utf8")); + settings.plugins.enabled = false; + settings.ui.locale = "en-US"; + settings.memory = { use: false, write: false, autoConsolidate: false }; + await writeFile(cliSettingsPath(env), JSON.stringify(settings)); + const node = Bun.which("node")!; + // The launcher and kernel are separate processes. Target only this test's kernel. + const preload = join(workspace.root, "runtime-pid.cjs"); + await writeFile(preload, 'if (process.argv[1]?.endsWith("zcode.cjs")) require("node:fs").writeFileSync(process.env.RUNTIME_PID_FILE,String(process.pid))'); + let streams = 0; + let closed = 0; + let agentId: string; + const server = Bun.serve({ hostname: "127.0.0.1", port: 0, idleTimeout: 0, async fetch(request) { + const body = await request.json() as { stream?: boolean; messages: { role: string; content: unknown }[] }; + if (!body.stream) return Response.json({ choices: [{ message: { role: "assistant", content: "Agent fixture" }, finish_reason: "stop" }] }); + const hasPrompt = (marker: string) => body.messages.some(m => m.role === "user" && JSON.stringify(m.content).includes(marker)); + if (hasPrompt("CHILD_306")) { + streams++; + return new Response(new ReadableStream({ + start(controller) { controller.enqueue(new TextEncoder().encode(": waiting\n\n")); }, + cancel() { closed++; } + }), { headers: { "content-type": "text/event-stream" } }); + } + const launch = hasPrompt("LAUNCH_306") && !body.messages.some(m => m.role === "tool"); + const attempt = body.messages.findLastIndex(m => m.role === "user" && JSON.stringify(m.content).includes("NATIVE_SEND_306")); + const result = attempt >= 0 && body.messages.slice(attempt + 1).find(m => m.role === "tool"); + const send = attempt >= 0 && !result; + const tool = send + ? { name: "SendMessage", arguments: JSON.stringify({ to: agentId, message: "Continue", summary: "Continue" }) } + : { name: "Agent", arguments: JSON.stringify({ subagent_type: "general-purpose", + description: "Ownership fixture", prompt: "CHILD_306", run_in_background: true }) }; + const delta = launch || send ? { role: "assistant", tool_calls: [{ index: 0, id: send ? "call_send_306" : "call_launch_306", + type: "function", function: tool }] } + : result ? { role: "assistant", content: /not reachable|No agent named|still owned/i.test(JSON.stringify(result.content)) + ? "NATIVE_SEND_REFUSED" : "UNEXPECTED_SEND_RESULT " + JSON.stringify(result.content) } + : { role: "assistant", content: "PARENT_READY" }; + const chunk = (delta: unknown, finish_reason: string | null) => "data: " + JSON.stringify({ choices: [{ index: 0, delta, finish_reason }] }) + "\n\n"; + return new Response(chunk(delta, null) + chunk({}, launch || send ? "tool_calls" : "stop") + "data: [DONE]\n\n", + { headers: { "content-type": "text/event-stream" } }); + } }); + const wait = async (predicate: () => boolean, session: TerminalSession) => { + for (let i = 0; i < 500 && !predicate(); i++) await Bun.sleep(25); + if (!predicate()) throw new Error(`Unexpected streams: opened=${streams} closed=${closed}\n${session.screenText()}`); + }; + try { + await writeProviderFixture(env, { apiKey: "fixture", baseUrl: `${server.url.origin}/v1` }); + const start = (name: string, args: string[]) => TerminalSession.start({ workspace, + command: [node, join(import.meta.dir, "../../bin/zcode.js"), "--mode", "build", ...args], + env: { ...env, ZCODE_NODE: node, NODE_OPTIONS: `--require="${preload}"`, RUNTIME_PID_FILE: join(workspace.root, name) }, + timeoutMilliseconds: 60_000 }); + await using owner = start("owner", []); + await owner.waitForScreen("owner ready", /◉ build/u, 15_000); + owner.send("LAUNCH_306\r"); + await wait(() => streams === 1, owner); + const [file] = await Array.fromAsync(new Bun.Glob("**/agent_*/metadata.json").scan({ + cwd: workspace.home, dot: true, absolute: true + })); + const metadata = JSON.parse(await readFile(file, "utf8")); + agentId = metadata.agentId; + await owner.waitForHistory("persisted launch receipt", /PARENT_READY/u); + await using observer = start("observer", ["--resume", metadata.parentSessionId]); + await observer.waitForScreen("observer ready", /◉ build/u, 15_000); + observer.send(`/tasks resume ${metadata.agentId}\r`); + await observer.waitForHistory("live elsewhere", /running elsewhere/u); + observer.send("NATIVE_SEND_306\r"); + await observer.waitForScreen("model SendMessage refused while the other runtime is live", /NATIVE_SEND_REFUSED/u); + expect(streams).toBe(1); + process.kill(Number(await readFile(join(workspace.root, "owner"), "utf8")), "SIGKILL"); + await wait(() => closed === 1, observer); + observer.send(`/tasks resume ${metadata.agentId}\r`); + await wait(() => streams === 2, observer); + observer.send(`/tasks stop ${metadata.agentId}\r`); + await wait(() => closed === 2, observer); + expect(streams).toBe(2); + } finally { + server.stop(true); + } +}, 80_000);