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
19 changes: 12 additions & 7 deletions packages/zcode-tui/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 });
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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) {
Expand Down Expand Up @@ -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;
Expand All @@ -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);
Expand Down Expand Up @@ -5784,7 +5789,7 @@ class ZCodeTui {
this.addNotice(detail, "warning");
}

private async stopBackgroundTask(taskId: string): Promise<void> {
private async stopBackgroundTask(taskId: string, selected?: RuntimeBackgroundJob): Promise<void> {
if (!taskId) {
this.addNotice("Usage: /tasks stop <task-id>", "muted");
return;
Expand All @@ -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;
Expand All @@ -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");
Expand Down
6 changes: 5 additions & 1 deletion packages/zcode-tui/src/runtime-projection.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";

Expand Down Expand Up @@ -39,6 +41,7 @@ export interface RuntimeActiveToolCall {

export interface RuntimeBackgroundJob {
taskId: string;
executionId?: string;
taskKind: RuntimeTaskKind;
toolCallId?: string;
toolName?: string;
Expand Down Expand Up @@ -136,7 +139,7 @@ const backgroundStatuses = new Set<RuntimeBackgroundStatus>([
"killed",
"stopped",
"spawn_error",
"lost"
"lost", "owner_unknown", "running_elsewhere"
]);
const todoStatuses = new Set<RuntimeTodo["status"]>(["pending", "in_progress", "completed"]);
const todoPriorities = new Set<RuntimeTodo["priority"]>(["high", "medium", "low"]);
Expand Down Expand Up @@ -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,
Expand Down
3 changes: 2 additions & 1 deletion packages/zcode-tui/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -109,12 +109,13 @@ export interface RuntimeAdapter {
readSessionUsage?: () => Promise<unknown>;
readSessionResumeTarget?: () => Promise<string | undefined>;
readSessionDatabasePath?: () => Promise<string | undefined>;
cancelBackgroundTask?: (taskId: string) => Promise<unknown>;
cancelBackgroundTask?: (taskId: string, executionId?: string) => Promise<unknown>;
sendBackgroundTaskMessage?: (options: {
taskId: string;
message: string;
summary: string;
restart?: boolean;
executionId?: string;
}) => Promise<unknown>;
previewFileRewind?: (targetMessageIds: string[]) => Promise<unknown>;
applyFileRewind?: (targetMessageIds: string[]) => Promise<unknown>;
Expand Down
3 changes: 2 additions & 1 deletion scripts/check-runtime.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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=>")
Expand Down
72 changes: 72 additions & 0 deletions scripts/runtime-subagent-execution.ts
Original file line number Diff line number Diff line change
@@ -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}`);
}
46 changes: 13 additions & 33 deletions scripts/sync-runtime.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -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(
Expand Down Expand Up @@ -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";
Expand Down Expand Up @@ -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")
Expand Down Expand Up @@ -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=>";
Expand All @@ -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)) {
Expand Down Expand Up @@ -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);
Expand All @@ -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}`);
Expand Down Expand Up @@ -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)")
},
{
Expand Down
Loading
Loading