@xzzpig/pi-subagents 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (81) hide show
  1. package/CHANGELOG.md +79 -0
  2. package/README.md +2 -0
  3. package/agents/reviewer.md +3 -4
  4. package/docs/agents.md +342 -0
  5. package/docs/configuration.md +328 -0
  6. package/docs/extension-api.md +308 -0
  7. package/docs/missions.md +119 -0
  8. package/docs/models.md +192 -0
  9. package/docs/observability.md +174 -0
  10. package/docs/tool-reference.md +343 -0
  11. package/docs/watchdog.md +176 -0
  12. package/docs/workflows.md +163 -0
  13. package/package.json +13 -11
  14. package/skills/pi-subagents/references/constraints-and-recipes.md +1 -1
  15. package/skills/pi-subagents/references/execution-controls.md +7 -7
  16. package/skills/pi-subagents/references/management-authoring-rpc.md +1 -1
  17. package/skills/pi-subagents/references/prompting-and-roles.md +1 -1
  18. package/src/agents/agents.ts +17 -8
  19. package/src/agents/frontmatter.ts +7 -3
  20. package/src/agents/skills.ts +2 -9
  21. package/src/api/project-panes.ts +30 -0
  22. package/src/extension/config.ts +28 -1
  23. package/src/extension/fanout-child.ts +5 -4
  24. package/src/extension/index.ts +75 -30
  25. package/src/extension/rpc.ts +7 -6
  26. package/src/extension/schemas.ts +29 -8
  27. package/src/extension/subagent-guide.ts +39 -0
  28. package/src/extension/tool-description.ts +30 -12
  29. package/src/inspectors/herdr/project-panes.ts +459 -63
  30. package/src/intercom/native-supervisor-channel.ts +102 -4
  31. package/src/missions/actions.ts +25 -2
  32. package/src/missions/lifecycle.ts +21 -2
  33. package/src/missions/store.ts +79 -2
  34. package/src/missions/types.ts +33 -0
  35. package/src/missions/workflow-state.ts +19 -13
  36. package/src/runs/background/active-run-index.ts +42 -0
  37. package/src/runs/background/async-execution.ts +17 -6
  38. package/src/runs/background/async-job-tracker.ts +293 -133
  39. package/src/runs/background/async-resume.ts +19 -3
  40. package/src/runs/background/async-status.ts +33 -5
  41. package/src/runs/background/completion-replay.ts +267 -0
  42. package/src/runs/background/control-channel.ts +95 -54
  43. package/src/runs/background/result-watcher.ts +113 -10
  44. package/src/runs/background/resume-guidance.ts +33 -0
  45. package/src/runs/background/run-status.ts +18 -0
  46. package/src/runs/background/scheduled-runs.ts +25 -1
  47. package/src/runs/background/stale-run-reconciler.ts +12 -24
  48. package/src/runs/background/subagent-runner.ts +69 -11
  49. package/src/runs/background/subagent-wait.ts +5 -2
  50. package/src/runs/background/wait-completions.ts +39 -5
  51. package/src/runs/background/wait-subscriptions.ts +21 -5
  52. package/src/runs/foreground/async-dismiss-action.ts +85 -0
  53. package/src/runs/foreground/async-steering-action.ts +7 -8
  54. package/src/runs/foreground/chain-execution.ts +3 -0
  55. package/src/runs/foreground/execution.ts +7 -0
  56. package/src/runs/foreground/foreground-history.ts +137 -0
  57. package/src/runs/foreground/subagent-executor.ts +466 -61
  58. package/src/runs/foreground/workflow-foreground-steering.ts +187 -0
  59. package/src/runs/shared/dynamic-fanout.ts +1 -1
  60. package/src/runs/shared/model-fallback.ts +8 -4
  61. package/src/runs/shared/model-scope.ts +12 -2
  62. package/src/runs/shared/parallel-utils.ts +1 -0
  63. package/src/runs/shared/subagent-prompt-runtime.ts +94 -9
  64. package/src/runs/shared/worktree.ts +3 -2
  65. package/src/shared/artifacts.ts +15 -15
  66. package/src/shared/display-text.ts +100 -0
  67. package/src/shared/file-coalescer.ts +9 -0
  68. package/src/shared/fork-context.ts +13 -0
  69. package/src/shared/formatters.ts +4 -6
  70. package/src/shared/prompt-resources.ts +51 -0
  71. package/src/shared/settings.ts +15 -2
  72. package/src/shared/types.ts +45 -2
  73. package/src/shared/utf8.ts +11 -0
  74. package/src/shared/utils.ts +43 -33
  75. package/src/slash/prompt-workflows.ts +2 -15
  76. package/src/slash/slash-commands.ts +22 -2
  77. package/src/tui/fleet-status.ts +22 -12
  78. package/src/tui/fleet.ts +135 -25
  79. package/src/tui/render.ts +150 -33
  80. package/src/watchdog/change-signature.ts +4 -3
  81. package/src/workflows/scripted-workflow.ts +210 -13
@@ -62,6 +62,7 @@ import {
62
62
  } from "../../shared/types.ts";
63
63
  import { formatDuration, shortenPath } from "../../shared/formatters.ts";
64
64
  import { collectWaitCompletions } from "./wait-completions.ts";
65
+ import { formatResumeFirstFailedRunsNote } from "./resume-guidance.ts";
65
66
  export { WAIT_TOOL_ENABLED_ENV, resolveWaitToolConfig, type ResolvedWaitToolConfig } from "./wait-config.ts";
66
67
 
67
68
  /** States that mean a run is still in flight (not yet resolved). */
@@ -604,6 +605,7 @@ export async function waitForSubagents(
604
605
  let finishedAsyncCount: number;
605
606
  let failedAsyncCount: number;
606
607
  let completions: WaitCompletion[] | undefined;
608
+ let resumeGuidance = "";
607
609
  const activeProviderIds = new Set(providerActive.map(backgroundWorkIdentity));
608
610
  const providerFinishedCount = [...initialProviderIds].filter((id) => !activeProviderIds.has(id)).length;
609
611
  try {
@@ -612,6 +614,7 @@ export async function waitForSubagents(
612
614
  finishedAsyncCount = terminal.length;
613
615
  failedAsyncCount = terminal.filter((run) => run.state === "failed").length;
614
616
  terminalSummary = summarizeTerminalRuns(terminal, providerFinishedCount);
617
+ resumeGuidance = formatResumeFirstFailedRunsNote(terminal);
615
618
  completions = collectWaitCompletions(terminal, deps.state, deps.resultsDir ?? DIRS.results);
616
619
  } catch (error) {
617
620
  return result(error instanceof Error ? error.message : String(error), true);
@@ -637,7 +640,7 @@ export async function waitForSubagents(
637
640
  : `${initialAsyncIds.size} async run(s) and ${initialProviderIds.size} provider item(s)`;
638
641
  const status = relevantAttention.length > 0 ? "attention required" : "done";
639
642
  return result(
640
- `Waited ${elapsed} for ${scope}; ${status}.${outcome}${attentionNote} Completion/control events have been observed; inspect status if a notification is not visible yet.`,
643
+ `Waited ${elapsed} for ${scope}; ${status}.${outcome}${resumeGuidance}${attentionNote} Completion/control events have been observed; inspect status if a notification is not visible yet.`,
641
644
  deps.failOnFailedRuns === true && failedAsyncCount > 0,
642
645
  completions,
643
646
  );
@@ -654,7 +657,7 @@ export async function waitForSubagents(
654
657
  ? `${relevantAttention.length} of ${initialCount} ${subject} need attention`
655
658
  : `${finishedCount} of ${initialCount} ${subject} finished`;
656
659
  return result(
657
- `Waited ${elapsed}; ${progress}.${outcome}${attentionNote}${remainder} Relevant completion/control events have been observed; inspect status if a notification is not visible yet.`,
660
+ `Waited ${elapsed}; ${progress}.${outcome}${resumeGuidance}${attentionNote}${remainder} Relevant completion/control events have been observed; inspect status if a notification is not visible yet.`,
658
661
  deps.failOnFailedRuns === true && failedAsyncCount > 0,
659
662
  completions,
660
663
  );
@@ -2,6 +2,7 @@ import * as fs from "node:fs";
2
2
  import * as path from "node:path";
3
3
  import type { ArtifactPaths, SubagentState, WaitCompletion, WaitCompletionChild } from "../../shared/types.ts";
4
4
  import type { AsyncRunSummary } from "./async-status.ts";
5
+ import { readCompletionReplay, writeCompletionReplay } from "./completion-replay.ts";
5
6
 
6
7
  function asNonEmptyString(value: unknown): string | undefined {
7
8
  return typeof value === "string" && value ? value : undefined;
@@ -68,12 +69,34 @@ export function toWaitCompletion(data: Record<string, unknown>, runId: string):
68
69
  * file is deleted after delivery, so this record is the only in-process source once
69
70
  * the watcher has consumed it.
70
71
  */
71
- export function recordWaitCompletion(state: SubagentState, runId: string, data: Record<string, unknown>, now: number, ttlMs: number): void {
72
+ export function recordWaitCompletion(
73
+ state: SubagentState,
74
+ runId: string,
75
+ data: Record<string, unknown>,
76
+ now: number,
77
+ ttlMs: number,
78
+ persistence?: { resultsDir: string; sessionId: string },
79
+ ): void {
72
80
  const store = state.completedResults ??= new Map();
73
81
  for (const [key, entry] of store) {
74
82
  if (now - entry.seenAt > ttlMs) store.delete(key);
75
83
  }
76
- store.set(runId, { seenAt: now, completion: toWaitCompletion(data, runId) });
84
+ let completion = toWaitCompletion(data, runId);
85
+ if (persistence) {
86
+ try {
87
+ completion = writeCompletionReplay({
88
+ ...persistence,
89
+ runId,
90
+ completion,
91
+ data,
92
+ now,
93
+ ttlMs,
94
+ }).completion;
95
+ } catch (error) {
96
+ console.error(`Failed to persist completion replay for '${runId}':`, error);
97
+ }
98
+ }
99
+ store.set(runId, { seenAt: now, completion });
77
100
  }
78
101
 
79
102
  /**
@@ -102,10 +125,21 @@ export function collectWaitCompletions(terminal: AsyncRunSummary[], state: Subag
102
125
  });
103
126
  }
104
127
  // The watcher may have consumed the file between the store check and the
105
- // read; its record is authoritative when present, otherwise the payload
106
- // is gone and the text summary remains the only surface for this run.
128
+ // read. Prefer its in-memory record, then the durable replay written before
129
+ // result cleanup so watcher reloads do not lose completion details.
107
130
  const late = state.completedResults?.get(run.id);
108
- if (late) completions.push(late.completion);
131
+ if (late) {
132
+ completions.push(late.completion);
133
+ continue;
134
+ }
135
+ try {
136
+ const replay = readCompletionReplay(resultsDir, run.id, { sessionId: run.sessionId });
137
+ if (replay) completions.push(replay.completion);
138
+ } catch (replayError) {
139
+ throw new Error(`Failed to read completion replay for '${run.id}': ${errorMessage(replayError)}`, {
140
+ cause: replayError instanceof Error ? replayError : undefined,
141
+ });
142
+ }
109
143
  }
110
144
  }
111
145
  return completions.length > 0 ? completions : undefined;
@@ -2,7 +2,9 @@ import * as fs from "node:fs";
2
2
  import * as path from "node:path";
3
3
  import { randomUUID } from "node:crypto";
4
4
  import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
5
- import { listAsyncRuns } from "./async-status.ts";
5
+ import { listAsyncRuns, type AsyncRunSummary } from "./async-status.ts";
6
+ import { formatResumeFirstFailedRunDetail } from "./resume-guidance.ts";
7
+ import { readCompletionReplay } from "./completion-replay.ts";
6
8
  import { writeAtomicJson } from "../../shared/atomic-json.ts";
7
9
  import {
8
10
  DIRS,
@@ -13,6 +15,7 @@ import {
13
15
  SUBAGENT_FOREGROUND_COMPLETE_EVENT,
14
16
  SUBAGENT_RESULT_INTERCOM_EVENT,
15
17
  type SubagentState,
18
+ type WaitCompletion,
16
19
  type WaitSubscriptionRecord,
17
20
  } from "../../shared/types.ts";
18
21
 
@@ -61,7 +64,7 @@ function parseRecord(value: unknown): WaitSubscriptionRecord | undefined {
61
64
  return record as WaitSubscriptionRecord;
62
65
  }
63
66
 
64
- function needsAttention(run: ReturnType<typeof listAsyncRuns>[number]): boolean {
67
+ function needsAttention(run: AsyncRunSummary): boolean {
65
68
  return run.activityState === "needs_attention" || run.steps.some((step) => step.activityState === "needs_attention");
66
69
  }
67
70
 
@@ -103,7 +106,7 @@ export function createWaitSubscriptionManager(
103
106
  unresolvedRestoredForegroundTokens.delete(record.token);
104
107
  };
105
108
 
106
- const settle = (record: WaitSubscriptionRecord, outcome: string, detail: string) => {
109
+ const settle = (record: WaitSubscriptionRecord, outcome: string, detail: string, completion?: WaitCompletion) => {
107
110
  if (disposed || state.currentSessionId !== record.sessionId) return;
108
111
  try {
109
112
  remove(record);
@@ -116,7 +119,12 @@ export function createWaitSubscriptionManager(
116
119
  customType: "subagent-wait-subscription",
117
120
  content: `Wait subscription ${record.token} fired for run ${record.runId}: ${outcome}. ${detail}`,
118
121
  display: true,
119
- details: { token: record.token, runId: record.runId, outcome },
122
+ details: {
123
+ token: record.token,
124
+ runId: record.runId,
125
+ outcome,
126
+ ...(completion ? { completions: [completion] } : {}),
127
+ },
120
128
  }, { triggerTurn: true });
121
129
  } catch (error) {
122
130
  console.error(`Failed to deliver wait subscription '${record.token}' after clearing it:`, error);
@@ -166,7 +174,15 @@ export function createWaitSubscriptionManager(
166
174
  return;
167
175
  }
168
176
  if (run.state !== "queued" && run.state !== "running") {
169
- settle(record, run.state === "complete" ? "completed" : run.state, "Inspect the run status for its final output.");
177
+ let completion: WaitCompletion | undefined;
178
+ try {
179
+ completion = readCompletionReplay(resultsDir, record.runId, { sessionId: record.sessionId, now: now() })?.completion;
180
+ } catch (error) {
181
+ console.error(`Failed to read completion replay for wait subscription '${record.token}':`, error);
182
+ }
183
+ const detail = formatResumeFirstFailedRunDetail(run) ?? "Inspect the run status for its final output.";
184
+ const archiveDetail = completion?.archivePath ? ` Completion archive: ${completion.archivePath}.` : "";
185
+ settle(record, run.state === "complete" ? "completed" : run.state, `${detail}${archiveDetail}`, completion);
170
186
  }
171
187
  };
172
188
 
@@ -0,0 +1,85 @@
1
+ import * as fs from "node:fs";
2
+ import * as path from "node:path";
3
+ import type { AgentToolResult } from "@earendil-works/pi-agent-core";
4
+ import { writeAtomicJson } from "../../shared/atomic-json.ts";
5
+ import { DIRS, type Details, type SubagentState } from "../../shared/types.ts";
6
+ import { readStatus } from "../../shared/utils.ts";
7
+ import { updateActiveRunIndex } from "../background/active-run-index.ts";
8
+ import { reconcileAsyncRun } from "../background/stale-run-reconciler.ts";
9
+
10
+ export function dismissRecoveredWorkflow(
11
+ state: SubagentState,
12
+ location: { asyncDir: string | null; resolvedId?: string },
13
+ ): AgentToolResult<Details> {
14
+ const asyncDir = location.asyncDir;
15
+ const runId = location.resolvedId ?? (asyncDir ? path.basename(asyncDir) : "requested");
16
+ if (!asyncDir) {
17
+ return {
18
+ content: [{ type: "text", text: `Recovered workflow '${runId}' has no disk status to dismiss.` }],
19
+ isError: true,
20
+ details: { mode: "management", results: [] },
21
+ };
22
+ }
23
+ const status = readStatus(asyncDir);
24
+ if (!status || status.mode !== "workflow") {
25
+ return {
26
+ content: [{ type: "text", text: `Run '${runId}' is not a recovered workflow.` }],
27
+ isError: true,
28
+ details: { mode: "management", results: [] },
29
+ };
30
+ }
31
+ if (!state.currentSessionId || status.sessionId !== state.currentSessionId) {
32
+ return {
33
+ content: [{ type: "text", text: `Recovered workflow '${runId}' was not found in the active session.` }],
34
+ isError: true,
35
+ details: { mode: "management", results: [] },
36
+ };
37
+ }
38
+ if (state.workflowControllers?.has(status.runId) || state.workflowControllers?.has(runId)) {
39
+ return {
40
+ content: [{ type: "text", text: `Workflow '${runId}' still has a live controller and cannot be dismissed.` }],
41
+ isError: true,
42
+ details: { mode: "management", results: [] },
43
+ };
44
+ }
45
+ if (status.state !== "running") {
46
+ return {
47
+ content: [{ type: "text", text: `Recovered workflow '${runId}' is ${status.state}, not running.` }],
48
+ isError: true,
49
+ details: { mode: "management", results: [] },
50
+ };
51
+ }
52
+ let latestStatus = status;
53
+ const resultPath = path.join(DIRS.results, `${status.runId}.json`);
54
+ if (fs.existsSync(resultPath)) {
55
+ const reconciled = reconcileAsyncRun(asyncDir).status;
56
+ if (reconciled && reconciled.state !== "running") {
57
+ return {
58
+ content: [{ type: "text", text: `Recovered workflow '${runId}' is ${reconciled.state}, not running.` }],
59
+ isError: true,
60
+ details: { mode: "management", results: [] },
61
+ };
62
+ }
63
+ if (reconciled) latestStatus = reconciled;
64
+ }
65
+
66
+ const dismissed = { ...latestStatus, displayDismissedAt: Date.now() };
67
+ writeAtomicJson(path.join(asyncDir, "status.json"), dismissed);
68
+ const repaired = reconcileAsyncRun(asyncDir).status;
69
+ if (repaired && repaired.state !== "running") {
70
+ return {
71
+ content: [{ type: "text", text: `Recovered workflow '${runId}' is ${repaired.state}, not running.` }],
72
+ isError: true,
73
+ details: { mode: "management", results: [] },
74
+ };
75
+ }
76
+ updateActiveRunIndex(asyncDir, "complete");
77
+ state.asyncJobs.delete(status.runId);
78
+ state.asyncJobs.delete(runId);
79
+ state.fleetJobs?.delete(status.runId);
80
+ state.fleetJobs?.delete(runId);
81
+ return {
82
+ content: [{ type: "text", text: `Dismissed recovered workflow ${status.runId} from the display. No running work was terminated.` }],
83
+ details: { mode: "management", results: [] },
84
+ };
85
+ }
@@ -173,7 +173,7 @@ export async function steerAsyncRun(input: {
173
173
  return { content: [{ type: "text", text: `Steering delivered for async run ${status.runId} (request ${requestId}).` }], details: { mode: "management", results: [], steering: preCommitResult } };
174
174
  }
175
175
  try {
176
- deliverInterruptRequest({ asyncDir, pid: latest?.pid ?? status.pid, kill: input.kill, source: "steering-recovery" });
176
+ deliverInterruptRequest({ asyncDir, source: "steering-recovery" });
177
177
  } catch (error) {
178
178
  fs.rmSync(markerPath, { force: true });
179
179
  fs.rmSync(claimPath, { force: true });
@@ -219,15 +219,14 @@ export async function steerAsyncRun(input: {
219
219
  const limits = remainingSteeringRecoveryLimits(recoveryTarget.recoveryDescriptor, paused);
220
220
  const revived = await input.recover(limits);
221
221
  if (revived.isError || !revived.details.asyncId) throw new Error(revived.content[0]?.type === "text" ? revived.content[0].text : "Replacement launch failed; source run remains paused.");
222
- const sourceStatus = readStatus(asyncDir);
223
- const targetIndex = input.index ?? status.steps?.findIndex((step) => step.status === "running") ?? -1;
224
- if (sourceStatus?.state === "paused" && sourceStatus.steering && targetIndex >= 0) {
225
- updateSteeringTarget(sourceStatus.steering, requestId, targetIndex, "recovered", Date.now(), { replacementRunId: revived.details.asyncId });
226
- const stepSteering = sourceStatus.steps?.[targetIndex]?.steering;
222
+ const targetIndex = input.index ?? paused.steering?.recent.find((request) => request.id === requestId)?.targets[0]?.index ?? status.steps?.findIndex((step) => step.status === "running") ?? -1;
223
+ if (paused.steering && targetIndex >= 0) {
224
+ updateSteeringTarget(paused.steering, requestId, targetIndex, "recovered", Date.now(), { replacementRunId: revived.details.asyncId });
225
+ const stepSteering = paused.steps?.[targetIndex]?.steering;
227
226
  if (stepSteering) updateSteeringTarget(stepSteering, requestId, targetIndex, "recovered", Date.now(), { replacementRunId: revived.details.asyncId });
228
- writeAtomicJson(path.join(asyncDir, "status.json"), sourceStatus);
227
+ writeAtomicJson(path.join(asyncDir, "status.json"), paused);
229
228
  }
230
- const recovered = sourceStatus?.steering ? actionResultFromSteeringStatus(sourceStatus.steering, status.runId, requestId, revived.details.asyncId) : undefined;
229
+ const recovered = paused.steering ? actionResultFromSteeringStatus(paused.steering, status.runId, requestId, revived.details.asyncId) : undefined;
231
230
  appendSteeringNotice("recovered", `Steering recovered for run ${status.runId}; replacement ${revived.details.asyncId} launched.`);
232
231
  return { content: [{ type: "text", text: `Steering recovered for async run ${status.runId}; replacement ${revived.details.asyncId} launched after the source paused.` }], details: { mode: "management", results: [], steering: recovered ?? { requestId, state: "recovered", sourceRunId: status.runId, replacementRunId: revived.details.asyncId, deliveryStatus: "delivered", targets: [{ index: input.index ?? 0, state: "recovered" }] } } };
233
232
  } catch (error) {
@@ -34,6 +34,7 @@ import {
34
34
  import { discoverAvailableSkills, normalizeSkillInput } from "../../agents/skills.ts";
35
35
  import { INTERCOM_BRIDGE_MARKER } from "../../intercom/intercom-bridge.ts";
36
36
  import { runSync } from "./execution.ts";
37
+ import { workflowForegroundSteeringLaunchOptions } from "./workflow-foreground-steering.ts";
37
38
  import {
38
39
  beginForegroundChild,
39
40
  finishForegroundChild,
@@ -387,6 +388,7 @@ async function runParallelChainTasks(input: ParallelChainRunInput): Promise<Sing
387
388
  result = await runSync(input.ctx.cwd, input.agents, task.agent, taskStr, {
388
389
  permissions: input.permissions,
389
390
  parentSessionId: input.ctx.sessionManager.getSessionId() ?? undefined,
391
+ ...workflowForegroundSteeringLaunchOptions(input.foregroundControl, childIndex),
390
392
  capabilityCeiling: input.capabilityCeiling,
391
393
  context: input.contextForAgent?.(task.agent),
392
394
  cwd: taskCwd,
@@ -1367,6 +1369,7 @@ ${step.message}` : ""}` }],
1367
1369
  r = await runSync(ctx.cwd, agents, seqStep.agent, stepTask, {
1368
1370
  permissions: params.permissions,
1369
1371
  parentSessionId: ctx.sessionManager.getSessionId() ?? undefined,
1372
+ ...workflowForegroundSteeringLaunchOptions(params.foregroundControl, childIndex),
1370
1373
  capabilityCeiling: params.capabilityCeiling,
1371
1374
  context: params.contextForAgent?.(seqStep.agent),
1372
1375
  cwd: resolveChildCwd(cwd ?? ctx.cwd, seqStep.cwd),
@@ -8,6 +8,7 @@ import * as path from "node:path";
8
8
  import type { Message } from "@earendil-works/pi-ai";
9
9
  import type { AgentConfig } from "../../agents/agents.ts";
10
10
  import { appendAgentRefinementOverlay } from "../../agents/agent-refinements.ts";
11
+ import { alignForkedSessionCwd } from "../../shared/fork-context.ts";
11
12
  import {
12
13
  ensureArtifactsDir,
13
14
  formatOutputArtifactContent,
@@ -337,6 +338,9 @@ async function runSingleAttempt(
337
338
  parentRootRunId: options.nestedRoute?.rootRunId,
338
339
  parentCapabilityToken: options.nestedRoute?.capabilityToken,
339
340
  parentSessionId: options.parentSessionId,
341
+ steerInboxDir: options.steerInboxDir,
342
+ steerCapabilityPath: options.steerCapabilityPath,
343
+ steerAckDir: options.steerAckDir,
340
344
  structuredOutput: options.structuredOutput,
341
345
  toolBudget: options.toolBudget,
342
346
  allowZeroToolBudget: options.allowZeroToolBudget,
@@ -1416,6 +1420,9 @@ async function runSyncCompletion(
1416
1420
  const acceptancePrompt = formatAcceptancePrompt(effectiveAcceptance, { reportOptional: isAgentContractV1(options.agentContract) });
1417
1421
  const taskWithAcceptance = acceptancePrompt ? `${task}\n${acceptancePrompt}` : task;
1418
1422
  const sessionEnabled = Boolean(options.sessionFile || options.sessionDir) || shareEnabled;
1423
+ if (options.context === "fork" && options.sessionFile && existsSync(options.sessionFile)) {
1424
+ alignForkedSessionCwd(options.sessionFile, options.cwd ?? runtimeCwd);
1425
+ }
1419
1426
  const skillNames = options.skills ?? agent.skills ?? [];
1420
1427
  const skillCwd = options.cwd ?? runtimeCwd;
1421
1428
  const { resolved: resolvedSkills, missing: missingSkills } = resolveSkillsWithFallback(
@@ -0,0 +1,137 @@
1
+ import * as fs from "node:fs";
2
+ import * as path from "node:path";
3
+ import type { ForegroundResumeChild, ForegroundResumeRun, SubagentState } from "../../shared/types.ts";
4
+ import { DIRS } from "../../shared/types.ts";
5
+ import { writeAtomicJson } from "../../shared/atomic-json.ts";
6
+ import { utf8Tail } from "../../shared/utf8.ts";
7
+
8
+ export const MAX_REMEMBERED_FOREGROUND_RUNS = 50;
9
+ const HISTORY_VERSION = 1;
10
+ const MAX_INLINE_OUTPUT_BYTES = 64 * 1024;
11
+
12
+ interface ForegroundHistoryIndex {
13
+ version: 1;
14
+ runs: ForegroundResumeRun[];
15
+ }
16
+
17
+ function historyPath(resultsDir: string): string {
18
+ return path.join(resultsDir, "foreground-history.json");
19
+ }
20
+
21
+ function boundedTail(value: string): string {
22
+ return utf8Tail(value, MAX_INLINE_OUTPUT_BYTES).text;
23
+ }
24
+
25
+ function compactChild(child: ForegroundResumeChild): ForegroundResumeChild {
26
+ const outputPath = child.artifactPaths?.outputPath ?? child.savedOutputPath;
27
+ return {
28
+ agent: child.agent,
29
+ index: child.index,
30
+ ...(child.context ? { context: child.context } : {}),
31
+ ...(child.sessionFile ? { sessionFile: child.sessionFile } : {}),
32
+ ...(child.model ? { model: child.model } : {}),
33
+ ...(child.thinking ? { thinking: child.thinking } : {}),
34
+ status: child.status,
35
+ ...(child.activityState ? { activityState: child.activityState } : {}),
36
+ ...(child.lastActivityAt !== undefined ? { lastActivityAt: child.lastActivityAt } : {}),
37
+ ...(child.currentTool ? { currentTool: child.currentTool } : {}),
38
+ ...(child.currentToolStartedAt !== undefined ? { currentToolStartedAt: child.currentToolStartedAt } : {}),
39
+ ...(child.currentPath ? { currentPath: child.currentPath } : {}),
40
+ ...(child.turnCount !== undefined ? { turnCount: child.turnCount } : {}),
41
+ ...(child.tokens !== undefined ? { tokens: child.tokens } : {}),
42
+ ...(child.toolCount !== undefined ? { toolCount: child.toolCount } : {}),
43
+ ...(child.exitCode !== undefined ? { exitCode: child.exitCode } : {}),
44
+ ...(child.error ? { error: child.error } : {}),
45
+ ...(!outputPath && child.finalOutput ? { finalOutput: boundedTail(child.finalOutput) } : {}),
46
+ ...(child.outputState ? { outputState: child.outputState } : {}),
47
+ ...(child.outputMode ? { outputMode: child.outputMode } : {}),
48
+ ...(child.savedOutputPath ? { savedOutputPath: child.savedOutputPath } : {}),
49
+ ...(child.outputSaveError ? { outputSaveError: child.outputSaveError } : {}),
50
+ ...(child.artifactPaths ? { artifactPaths: child.artifactPaths } : {}),
51
+ ...(child.transcriptPath ? { transcriptPath: child.transcriptPath } : {}),
52
+ ...(child.transcriptError ? { transcriptError: child.transcriptError } : {}),
53
+ ...(child.acceptance ? { acceptance: child.acceptance } : {}),
54
+ ...(child.launchContractDigest ? { launchContractDigest: child.launchContractDigest } : {}),
55
+ ...(child.capabilityCeiling ? { capabilityCeiling: child.capabilityCeiling } : {}),
56
+ ...(child.updatedAt !== undefined ? { updatedAt: child.updatedAt } : {}),
57
+ };
58
+ }
59
+
60
+ function isRestorableForegroundStatus(status: unknown): status is ForegroundResumeChild["status"] {
61
+ return status === "completed" || status === "failed" || status === "paused" || status === "stopped";
62
+ }
63
+
64
+ function compactRun(run: ForegroundResumeRun): ForegroundResumeRun | undefined {
65
+ if (!run.sessionId) return undefined;
66
+ if (run.children.length === 0 || !run.children.every((child) => isRestorableForegroundStatus(child.status))) return undefined;
67
+ return {
68
+ runId: run.runId,
69
+ mode: run.mode,
70
+ cwd: run.cwd,
71
+ sessionId: run.sessionId,
72
+ updatedAt: run.updatedAt,
73
+ children: run.children.map(compactChild),
74
+ };
75
+ }
76
+
77
+ function readIndex(resultsDir: string): ForegroundHistoryIndex {
78
+ const filePath = historyPath(resultsDir);
79
+ if (!fs.existsSync(filePath)) return { version: HISTORY_VERSION, runs: [] };
80
+ try {
81
+ const parsed = JSON.parse(fs.readFileSync(filePath, "utf-8")) as unknown;
82
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return { version: HISTORY_VERSION, runs: [] };
83
+ const record = parsed as Partial<ForegroundHistoryIndex>;
84
+ if (record.version !== HISTORY_VERSION || !Array.isArray(record.runs)) return { version: HISTORY_VERSION, runs: [] };
85
+ return { version: HISTORY_VERSION, runs: record.runs.filter(isRestorableRun) };
86
+ } catch {
87
+ return { version: HISTORY_VERSION, runs: [] };
88
+ }
89
+ }
90
+
91
+ function isRestorableRun(value: unknown): value is ForegroundResumeRun {
92
+ if (!value || typeof value !== "object" || Array.isArray(value)) return false;
93
+ const run = value as Partial<ForegroundResumeRun>;
94
+ return typeof run.runId === "string" && Boolean(run.runId)
95
+ && (run.mode === "single" || run.mode === "parallel" || run.mode === "chain")
96
+ && typeof run.cwd === "string" && Boolean(run.cwd)
97
+ && typeof run.sessionId === "string" && Boolean(run.sessionId)
98
+ && typeof run.updatedAt === "number" && Number.isFinite(run.updatedAt)
99
+ && Array.isArray(run.children)
100
+ && run.children.length > 0
101
+ && run.children.every((child) => Boolean(child && typeof child === "object" && !Array.isArray(child)
102
+ && typeof (child as Partial<ForegroundResumeChild>).agent === "string"
103
+ && typeof (child as Partial<ForegroundResumeChild>).index === "number"
104
+ && isRestorableForegroundStatus((child as Partial<ForegroundResumeChild>).status)));
105
+ }
106
+
107
+ function sortAndBound(runs: ForegroundResumeRun[], limit: number): ForegroundResumeRun[] {
108
+ return [...runs].sort((left, right) => right.updatedAt - left.updatedAt).slice(0, limit);
109
+ }
110
+
111
+ export function persistForegroundRunHistory(state: SubagentState, options: { resultsDir?: string; limit?: number } = {}): void {
112
+ const resultsDir = options.resultsDir ?? DIRS.results;
113
+ const limit = options.limit ?? MAX_REMEMBERED_FOREGROUND_RUNS;
114
+ const existing = readIndex(resultsDir);
115
+ const merged = new Map(existing.runs.map((run) => [run.runId, run]));
116
+ for (const run of state.foregroundRuns?.values() ?? []) {
117
+ const compact = compactRun(run);
118
+ if (compact) merged.set(compact.runId, compact);
119
+ }
120
+ const runs = sortAndBound([...merged.values()], limit);
121
+ writeAtomicJson(historyPath(resultsDir), { version: HISTORY_VERSION, runs });
122
+ }
123
+
124
+ export function restoreForegroundRunHistory(state: SubagentState, options: { resultsDir?: string; sessionId?: string | null; limit?: number } = {}): number {
125
+ const sessionId = options.sessionId ?? state.currentSessionId;
126
+ if (!sessionId) return 0;
127
+ const index = readIndex(options.resultsDir ?? DIRS.results);
128
+ const runs = sortAndBound(index.runs.filter((run) => run.sessionId === sessionId), options.limit ?? MAX_REMEMBERED_FOREGROUND_RUNS);
129
+ state.foregroundRuns ??= new Map();
130
+ let restored = 0;
131
+ for (const run of runs) {
132
+ if (state.foregroundRuns.has(run.runId)) continue;
133
+ state.foregroundRuns.set(run.runId, run);
134
+ restored += 1;
135
+ }
136
+ return restored;
137
+ }