@xzzpig/pi-subagents 0.19.0 → 0.21.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 (153) hide show
  1. package/CHANGELOG.md +214 -0
  2. package/README.md +1 -1
  3. package/agents/oracle.md +8 -19
  4. package/agents/researcher.md +0 -3
  5. package/agents/reviewer.md +17 -61
  6. package/agents/scout.md +1 -4
  7. package/agents/worker.md +8 -25
  8. package/docs/agents.md +86 -11
  9. package/docs/configuration.md +68 -7
  10. package/docs/extension-api.md +37 -12
  11. package/docs/fork-extensions.md +1 -0
  12. package/docs/missions.md +48 -17
  13. package/docs/models.md +7 -3
  14. package/docs/observability.md +18 -8
  15. package/docs/tool-reference.md +138 -80
  16. package/docs/watchdog.md +8 -6
  17. package/docs/workflows.md +18 -9
  18. package/index.ts +5 -0
  19. package/package.json +5 -3
  20. package/prompts/council.md +1 -1
  21. package/skills/pi-subagents/SKILL.md +1 -1
  22. package/skills/pi-subagents/references/constraints-and-recipes.md +1 -1
  23. package/skills/pi-subagents/references/execution-controls.md +16 -16
  24. package/skills/pi-subagents/references/management-authoring-rpc.md +16 -12
  25. package/skills/pi-subagents/references/prompting-and-roles.md +3 -3
  26. package/src/agents/advertised-agent-prompt.ts +9 -1
  27. package/src/agents/agent-management.ts +4 -0
  28. package/src/agents/agent-memory.ts +3 -3
  29. package/src/agents/agent-scope.ts +4 -0
  30. package/src/agents/agent-serializer.ts +8 -1
  31. package/src/agents/agents.ts +224 -122
  32. package/src/api/preflight.ts +50 -5
  33. package/src/extension/config.ts +24 -2
  34. package/src/extension/context-injection.ts +6 -1
  35. package/src/extension/control-notices.ts +1 -9
  36. package/src/extension/declaration-pinning.ts +164 -0
  37. package/src/extension/doctor.ts +7 -10
  38. package/src/extension/fanout-child.ts +7 -8
  39. package/src/extension/index.ts +134 -145
  40. package/src/extension/public-execution.ts +3 -0
  41. package/src/extension/reply-workflow-script.ts +21 -12
  42. package/src/extension/rpc.ts +12 -7
  43. package/src/extension/schemas.ts +39 -33
  44. package/src/extension/subagent-guide.ts +86 -6
  45. package/src/extension/subagent-options.ts +47 -0
  46. package/src/extension/tool-activation.ts +3 -2
  47. package/src/extension/tool-description.ts +51 -68
  48. package/src/inspectors/actions.ts +37 -11
  49. package/src/inspectors/plugins.ts +3 -2
  50. package/src/inspectors/tmux/actions.ts +204 -0
  51. package/src/inspectors/tmux/client.ts +85 -0
  52. package/src/inspectors/tmux/plugin.ts +21 -0
  53. package/src/integrations/herdr-status.ts +18 -49
  54. package/src/integrations/program-status.ts +215 -0
  55. package/src/intercom/native-supervisor-channel.ts +77 -4
  56. package/src/intercom/result-intercom.ts +3 -2
  57. package/src/intercom/supervisor-ui.ts +2 -174
  58. package/src/missions/goal-driver.ts +44 -31
  59. package/src/missions/store.ts +35 -6
  60. package/src/profiles/profiles.ts +29 -23
  61. package/src/runs/background/active-async-capacity.ts +58 -8
  62. package/src/runs/background/async-execution.ts +231 -44
  63. package/src/runs/background/async-job-tracker.ts +12 -4
  64. package/src/runs/background/async-resume.ts +5 -2
  65. package/src/runs/background/await-async-run.ts +18 -11
  66. package/src/runs/background/binary-bootstrap.ts +2 -1
  67. package/src/runs/background/calendar-schedule.ts +90 -0
  68. package/src/runs/background/chain-root-attachment.ts +9 -5
  69. package/src/runs/background/control-channel.ts +43 -0
  70. package/src/runs/background/fleet-view.ts +5 -5
  71. package/src/runs/background/notify.ts +185 -12
  72. package/src/runs/background/result-files.ts +116 -5
  73. package/src/runs/background/result-watcher.ts +99 -66
  74. package/src/runs/background/resume-guidance.ts +2 -2
  75. package/src/runs/background/run-child-session.ts +29 -8
  76. package/src/runs/background/run-id-resolver.ts +8 -5
  77. package/src/runs/background/run-status.ts +21 -16
  78. package/src/runs/background/runner-aliases.ts +7 -4
  79. package/src/runs/background/runner-child-launch.ts +1 -0
  80. package/src/runs/background/runner-http-dispatcher.ts +3 -0
  81. package/src/runs/background/scheduled-runs.ts +282 -72
  82. package/src/runs/background/stale-run-reconciler.ts +13 -2
  83. package/src/runs/background/subagent-runner-bootstrap.ts +4 -1
  84. package/src/runs/background/subagent-runner.ts +75 -16
  85. package/src/runs/background/subagent-wait.ts +38 -19
  86. package/src/runs/background/terminal-run-index.ts +46 -1
  87. package/src/runs/background/wait-completions.ts +1 -0
  88. package/src/runs/background/wait-tool.ts +33 -23
  89. package/src/runs/background/workflow-terminal-proof.ts +39 -22
  90. package/src/runs/foreground/async-stop-action.ts +48 -22
  91. package/src/runs/foreground/command-action.ts +41 -0
  92. package/src/runs/foreground/execution.ts +109 -58
  93. package/src/runs/foreground/foreground-history.ts +1 -0
  94. package/src/runs/foreground/subagent-executor.ts +270 -89
  95. package/src/runs/shared/child-commands.ts +229 -0
  96. package/src/runs/shared/child-hooks.ts +4 -3
  97. package/src/runs/shared/child-launch.ts +3 -0
  98. package/src/runs/shared/child-session.ts +131 -40
  99. package/src/runs/shared/child-tool-plan.ts +14 -27
  100. package/src/runs/shared/claude-code-adapter.ts +157 -2
  101. package/src/runs/shared/dynamic-fanout.ts +2 -2
  102. package/src/runs/shared/external-cli-preflight.ts +54 -6
  103. package/src/runs/shared/external-cli-runner.ts +5 -1
  104. package/src/runs/shared/fork-command-result.ts +10 -0
  105. package/src/runs/shared/herdr-placed-run.ts +5 -4
  106. package/src/runs/shared/mcp-direct-tool-allowlist.ts +8 -5
  107. package/src/runs/shared/model-resolution-diagnostic.ts +25 -0
  108. package/src/runs/shared/model-resolution.ts +39 -2
  109. package/src/runs/shared/nested-events.ts +5 -0
  110. package/src/runs/shared/parallel-handoff.ts +56 -8
  111. package/src/runs/shared/parallel-utils.ts +4 -0
  112. package/src/runs/shared/partial-output.ts +48 -0
  113. package/src/runs/shared/run-history.ts +87 -0
  114. package/src/runs/shared/runner-launcher.ts +25 -0
  115. package/src/runs/shared/single-output.ts +53 -0
  116. package/src/runs/shared/structured-output.ts +14 -7
  117. package/src/runs/shared/subagent-control.ts +33 -18
  118. package/src/runs/shared/subagent-prompt-runtime.ts +59 -30
  119. package/src/runs/shared/workflow-async-child-guidance.ts +1 -1
  120. package/src/runs/shared/worktree-cleanup-apply.ts +160 -0
  121. package/src/runs/shared/worktree-cleanup-plan.ts +41 -19
  122. package/src/runs/shared/worktree-lock.ts +29 -0
  123. package/src/runs/shared/worktree.ts +12 -1
  124. package/src/shared/atomic-json.ts +4 -2
  125. package/src/shared/edit-distance.ts +33 -0
  126. package/src/shared/file-lease.ts +74 -0
  127. package/src/shared/formatters.ts +1 -5
  128. package/src/shared/model-info.ts +22 -0
  129. package/src/shared/package-version.ts +17 -0
  130. package/src/shared/parent-wake.ts +79 -0
  131. package/src/shared/pruned-fork.ts +7 -1
  132. package/src/shared/required-child-extensions.ts +39 -5
  133. package/src/shared/runtime-module-path.ts +19 -0
  134. package/src/shared/settings-file-lease.ts +36 -0
  135. package/src/shared/types.ts +42 -3
  136. package/src/shared/utils.ts +8 -6
  137. package/src/slash/slash-commands.ts +3 -3
  138. package/src/slash/subagent-cost.ts +9 -5
  139. package/src/slash/subagents-admin.ts +2 -1
  140. package/src/tui/fleet-native-transcript.ts +2 -0
  141. package/src/tui/fleet-transcript.ts +12 -3
  142. package/src/tui/fleet.ts +11 -8
  143. package/src/tui/render.ts +28 -20
  144. package/src/tui/subagent-messages.ts +305 -0
  145. package/src/watchdog/diff-tool.ts +2 -2
  146. package/src/watchdog/register-main.ts +2 -22
  147. package/src/watchdog/render.ts +2 -24
  148. package/src/watchdog/runtime.ts +6 -4
  149. package/src/watchdog/settings.ts +18 -13
  150. package/src/watchdog/tool-actions.ts +2 -2
  151. package/src/workflows/scripted-workflow.ts +20 -6
  152. package/src/workflows/workflow-receipt.ts +2 -2
  153. package/src/workflows/workflow-resources.ts +18 -4
@@ -6,6 +6,7 @@ import { formatControlNoticeMessage } from "../shared/subagent-control.ts";
6
6
  import {
7
7
  type AsyncJobState,
8
8
  type AsyncStartedEvent,
9
+ type AsyncWidgetLayout,
9
10
  type ControlEvent,
10
11
  type SteeringNotice,
11
12
  type SubagentChildStatusEvent,
@@ -35,13 +36,18 @@ interface AsyncJobTrackerOptions {
35
36
  pollIntervalMs?: number;
36
37
  resultsDir?: string;
37
38
  widgetEnabled?: boolean;
39
+ widgetCollapsed?: boolean;
40
+ widgetLayout?: AsyncWidgetLayout;
38
41
  platform?: NodeJS.Platform;
39
- onJobTerminal?: () => void;
42
+ onJobTerminal?: (job: AsyncJobState) => void;
43
+ onJobCleanup?: (asyncId: string) => void;
40
44
  watch?: typeof fs.watch;
41
45
  kill?: (pid: number, signal?: NodeJS.Signals | 0) => boolean;
42
46
  now?: () => number;
43
47
  /** Resolve native supervisor requests without scanning supervisor mailboxes. */
44
48
  supervisorRequestState?: (event: ControlEvent) => "pending" | "resolved" | "unknown";
49
+ /** Called whenever the tracked jobs changed enough to re-render the widget. */
50
+ onJobsChanged?: () => void;
45
51
  }
46
52
 
47
53
  const CONTROL_EVENT_READ_CHUNK_BYTES = 64 * 1024;
@@ -103,8 +109,9 @@ export function createAsyncJobTracker(pi: Pick<ExtensionAPI, "events">, state: S
103
109
  }, run);
104
110
  };
105
111
  const rerenderWidget = (ctx: ExtensionContext, jobs = Array.from(state.asyncJobs.values())) => {
112
+ options.onJobsChanged?.();
106
113
  if (state.widgetsSuspended) return;
107
- renderWidget(ctx, options.widgetEnabled === false ? [] : jobs);
114
+ renderWidget(ctx, options.widgetEnabled === false ? [] : jobs, options.widgetCollapsed, options.widgetLayout);
108
115
  (ctx.ui as { requestRender?: () => void }).requestRender?.();
109
116
  };
110
117
  const rerenderLastWidget = (jobs = Array.from(state.asyncJobs.values())) => {
@@ -124,7 +131,7 @@ export function createAsyncJobTracker(pi: Pick<ExtensionAPI, "events">, state: S
124
131
  if (state.widgetsSuspended) return;
125
132
  const requestRender = (ctx.ui as { requestRender?: () => void }).requestRender;
126
133
  if (requestRender) requestRender.call(ctx.ui);
127
- else renderWidget(ctx, Array.from(state.asyncJobs.values()));
134
+ else renderWidget(ctx, Array.from(state.asyncJobs.values()), options.widgetCollapsed, options.widgetLayout);
128
135
  });
129
136
  };
130
137
  const refreshWidget = (ctx: ExtensionContext) => rerenderWidget(ctx);
@@ -219,6 +226,7 @@ export function createAsyncJobTracker(pi: Pick<ExtensionAPI, "events">, state: S
219
226
  const job = state.asyncJobs.get(asyncId);
220
227
  retainNestedLookupRoute(state, job?.nestedRoute, job?.sessionId);
221
228
  state.asyncJobs.delete(asyncId);
229
+ options.onJobCleanup?.(asyncId);
222
230
  rerenderLastWidget();
223
231
  }, completionRetentionMs);
224
232
  state.cleanupTimers.set(asyncId, timer);
@@ -559,7 +567,7 @@ export function createAsyncJobTracker(pi: Pick<ExtensionAPI, "events">, state: S
559
567
  } else cancelCleanup(job.asyncId);
560
568
  }
561
569
  // Scan on close too: publication may have raced the payload check.
562
- if (!isTerminalJobStatus(previousStatus) || (wasPending && !publication?.pending)) options.onJobTerminal?.();
570
+ if (!isTerminalJobStatus(previousStatus) || (wasPending && !publication?.pending)) options.onJobTerminal?.(job);
563
571
  rememberFleetJob(state, job);
564
572
  if (!publication?.pending && !nestedRefreshFailed && !hasLiveNestedDescendants(job.nestedChildren) && (previousStatus !== job.status || !state.cleanupTimers.has(job.asyncId))) {
565
573
  scheduleCleanup(job.asyncId);
@@ -1,6 +1,6 @@
1
1
  import * as fs from "node:fs";
2
2
  import * as path from "node:path";
3
- import { DIRS, type AcceptanceInput, type AsyncStatus, type SteeringRecoveryDescriptor, type SubagentRunMode } from "../../shared/types.ts";
3
+ import { DIRS, RUNNER_LAUNCHER_NAME_PATTERN, type AcceptanceInput, type AsyncStatus, type SteeringRecoveryDescriptor, type SubagentRunMode } from "../../shared/types.ts";
4
4
  import type { AgentConfig } from "../../agents/agents.ts";
5
5
  import { normalizeExtensionBindings } from "../shared/extension-bindings.ts";
6
6
  import { snapshotRequiredChildExtensions } from "../../shared/required-child-extensions.ts";
@@ -343,7 +343,7 @@ export function readAsyncRecoveryDescriptor(asyncDir: string | undefined): Steer
343
343
  "subagentOnlyExtensions", "mcpDirectTools", "excludeTools", "mutationTools", "systemPrompt", "systemPromptMode", "inheritProjectContext", "inheritGlobalContext", "inheritSkills", "skills",
344
344
  "skillPath", "agentFilePath", "memory", "outputPath", "outputMode", "structuredOutputSchema", "acceptance", "sessionDir", "artifactConfig",
345
345
  "artifactsDir", "maxOutput", "controlConfig", "context", "intercomBridge", "absoluteDeadlineAt", "initialTurnBudget", "initialToolBudget", "maxSubagentDepth", "share", "capabilityCeiling",
346
- "launchResolvedExtensions", "runFanoutBudget", "lane", "baseRef",
346
+ "launchResolvedExtensions", "runFanoutBudget", "lane", "baseRef", "launcher",
347
347
  "extensionBindings",
348
348
  "requiredExtensions",
349
349
  ]);
@@ -355,6 +355,7 @@ export function readAsyncRecoveryDescriptor(asyncDir: string | undefined): Steer
355
355
  if (typeof parsed[field] !== "string" || !(parsed[field] as string).trim()) throw new Error(`Invalid async recovery descriptor '${descriptorPath}': ${field} must be a non-empty string.`);
356
356
  }
357
357
  if (parsed.version !== 1) throw new Error(`Invalid async recovery descriptor '${descriptorPath}': version must be 1.`);
358
+ if (parsed.launcher !== undefined && (typeof parsed.launcher !== "string" || !RUNNER_LAUNCHER_NAME_PATTERN.test(parsed.launcher))) throw new Error(`Invalid async recovery descriptor '${descriptorPath}': launcher must be a launcher name.`);
358
359
  try {
359
360
  parsed.runFanoutBudget = validateRunFanoutBudgetDescriptor(parsed.runFanoutBudget);
360
361
  } catch (error) {
@@ -664,6 +665,8 @@ export function applySteeringRecoveryAgentConfig(agentConfig: AgentConfig, descr
664
665
  output: descriptor.outputPath,
665
666
  toolBudget: descriptor.initialToolBudget,
666
667
  maxSubagentDepth: descriptor.maxSubagentDepth,
668
+ // The recorded launcher wins over the current agent file, including recorded absence.
669
+ launcher: descriptor.launcher,
667
670
  };
668
671
  }
669
672
 
@@ -3,11 +3,11 @@ import { readStatus } from "../../shared/utils.ts";
3
3
  import { workflowAwaitedAsyncResultPath } from "./async-execution.ts";
4
4
  import { waitForImportedAsyncRoot, type ImportedAsyncRootResult } from "./chain-root-attachment.ts";
5
5
  import { currentPidNamespaceScope } from "./pid-namespace.ts";
6
- import { resultPayloadPathForSessionRun } from "./result-files.ts";
6
+ import { resultPayloadPathForSessionRun, resultSnapshotReplaced, withResultRunLease, type ResultSnapshot } from "./result-files.ts";
7
7
  import { checkPidLiveness } from "./stale-run-reconciler.ts";
8
8
 
9
9
  type ExistingAsyncRunOutcome =
10
- | { status: "settled"; result: ImportedAsyncRootResult }
10
+ | { status: "settled"; result: ImportedAsyncRootResult & { importedPublication: NonNullable<ImportedAsyncRootResult["importedPublication"]> } }
11
11
  | { status: "unavailable"; reason: string };
12
12
 
13
13
  function errorMessage(error: unknown): string {
@@ -18,8 +18,10 @@ function errorMessage(error: unknown): string {
18
18
  function runnerExitedWithoutResult(asyncDir: string, runId: string, resultPath: string): boolean {
19
19
  const status = readStatus(asyncDir);
20
20
  if (!status || (status.state !== "running" && status.state !== "queued") || typeof status.pid !== "number") return false;
21
- if (status.pidNamespaceScope !== undefined && status.pidNamespaceScope !== currentPidNamespaceScope()) return false;
22
- if (checkPidLiveness(status.pid) !== "dead") return false;
21
+ const observedScope = currentPidNamespaceScope();
22
+ if (status.pidNamespaceScope !== undefined && status.pidNamespaceScope !== observedScope) return false;
23
+ const pidScopeVerified = status.pidNamespaceScope !== undefined && status.pidNamespaceScope === observedScope;
24
+ if (checkPidLiveness(status.pid, undefined, pidScopeVerified) !== "dead") return false;
23
25
  return !fs.existsSync(resultPath) && !(status.sessionId && resultPayloadPathForSessionRun(asyncDir, status.sessionId, runId));
24
26
  }
25
27
 
@@ -58,18 +60,23 @@ export async function awaitExistingAsyncRun(asyncDir: string, runId: string, sig
58
60
  if (runnerExited) return { status: "unavailable", reason: `Async runner for run '${runId}' exited without publishing a result.` };
59
61
  // Only a parsed result file carries importedPublication; status-derived fallbacks do not.
60
62
  if (!completed.importedPublication) return { status: "unavailable", reason: `Async run '${runId}' ended without a result file at ${resultPath}.` };
61
- return { status: "settled", result: completed };
63
+ return { status: "settled", result: { ...completed, importedPublication: completed.importedPublication } };
62
64
  }
63
65
 
64
66
  /**
65
- * Renames the published result to a file owned by `claimant`. Only one of several
66
- * concurrent importers can win the rename; the others get undefined and launch fresh.
67
+ * Renames the published result to a file owned by `claimant`, if it is still the payload the
68
+ * claimant read. Only one of several concurrent importers can win the rename; the others, and a
69
+ * claimant whose payload a newer one replaced, get undefined and launch fresh.
67
70
  */
68
- export function claimWorkflowAwaitedResult(asyncDir: string, claimant: string): string | undefined {
69
- const claimedPath = `${workflowAwaitedAsyncResultPath(asyncDir)}.${claimant}.claimed`;
71
+ export function claimWorkflowAwaitedResult(asyncDir: string, claimant: string, read: ResultSnapshot): string | undefined {
72
+ const resultPath = workflowAwaitedAsyncResultPath(asyncDir);
73
+ const claimedPath = `${resultPath}.${claimant}.claimed`;
70
74
  try {
71
- fs.renameSync(workflowAwaitedAsyncResultPath(asyncDir), claimedPath);
72
- return claimedPath;
75
+ return withResultRunLease(asyncDir, read.runId, () => {
76
+ if (resultSnapshotReplaced(resultPath, read)) return undefined;
77
+ fs.renameSync(resultPath, claimedPath);
78
+ return claimedPath;
79
+ });
73
80
  } catch {
74
81
  return undefined;
75
82
  }
@@ -10,6 +10,7 @@ import * as typebox from "typebox";
10
10
  import * as typeboxCompile from "typebox/compile";
11
11
  import * as typeboxValue from "typebox/value";
12
12
  import { installRunnerHttpDispatcher } from "./runner-http-dispatcher.ts";
13
+ import { resolveRuntimeModuleExtension } from "../../shared/runtime-module-path.ts";
13
14
  import { runConfiguredSubagent, validateSubagentRunConfig } from "./subagent-runner-bootstrap.ts";
14
15
  import { getAgentDir } from "../../shared/utils.ts";
15
16
 
@@ -54,7 +55,7 @@ export default async function runBinaryBootstrap(): Promise<never> {
54
55
  "typebox/value": typeboxValue,
55
56
  },
56
57
  });
57
- const runner = `./subagent-runner${path.extname(fileURLToPath(import.meta.url))}`;
58
+ const runner = `./subagent-runner${resolveRuntimeModuleExtension(path.dirname(fileURLToPath(import.meta.url)), "subagent-runner")}`;
58
59
  return jiti.import<typeof import("./subagent-runner.ts")>(runner);
59
60
  },
60
61
  });
@@ -0,0 +1,90 @@
1
+ import { createRequire } from "node:module";
2
+ import type { Temporal } from "@js-temporal/polyfill";
3
+
4
+ const require = createRequire(import.meta.url);
5
+ let cachedTemporal: typeof Temporal | undefined;
6
+
7
+ function getTemporal(): typeof Temporal {
8
+ return cachedTemporal ??= (require("@js-temporal/polyfill") as typeof import("@js-temporal/polyfill")).Temporal;
9
+ }
10
+
11
+ export const CALENDAR_WEEKDAYS = ["mon", "tue", "wed", "thu", "fri", "sat", "sun"] as const;
12
+ export type CalendarWeekday = typeof CALENDAR_WEEKDAYS[number];
13
+ export type CalendarRule = { every: "day" | "week"; at: string; timezone: string; on?: CalendarWeekday[] };
14
+ export type CalendarOccurrence = { nextLocalDate: string; nextRunAt: string };
15
+ export type CalendarTrigger = CalendarRule & CalendarOccurrence & { kind: "calendar" };
16
+ const SEARCH_DAYS = 32;
17
+
18
+ export function normalizeCalendarRule(input: { every?: unknown; at?: unknown; timezone?: unknown; on?: unknown }): CalendarRule {
19
+ if (input.every !== "day" && input.every !== "week") throw new Error("Calendar every must be 'day' or 'week'.");
20
+ if (typeof input.at !== "string" || !/^(?:[01]\d|2[0-3]):[0-5]\d$/.test(input.at)) throw new Error("Calendar at must use HH:mm (00:00-23:59).");
21
+ if (typeof input.timezone !== "string" || !input.timezone.trim() || /^[+-]/.test(input.timezone.trim())) throw new Error("Calendar timezone requires an IANA name, such as 'Asia/Taipei', or 'UTC'.");
22
+ let timezone: string;
23
+ try { timezone = new Intl.DateTimeFormat("en", { timeZone: input.timezone.trim() }).resolvedOptions().timeZone; }
24
+ catch { throw new Error(`Invalid calendar timezone '${input.timezone}'. Use an IANA name or 'UTC'.`); }
25
+ if (input.every === "day") {
26
+ if (input.on !== undefined) throw new Error("Daily schedules do not accept on; use every:'week' with a weekday array.");
27
+ return { every: "day", at: input.at, timezone };
28
+ }
29
+ if (!Array.isArray(input.on) || input.on.length === 0 || input.on.some((day) => !CALENDAR_WEEKDAYS.includes(day))) throw new Error("Weekly on must be a non-empty array of mon/tue/wed/thu/fri/sat/sun.");
30
+ const selected = input.on;
31
+ return { every: "week", at: input.at, timezone, on: CALENDAR_WEEKDAYS.filter((day) => selected.includes(day)) };
32
+ }
33
+
34
+ function localDate(value: string): Temporal.PlainDate {
35
+ if (!/^\d{4}-\d{2}-\d{2}$/.test(value)) throw new Error("Calendar nextLocalDate must use YYYY-MM-DD.");
36
+ return getTemporal().PlainDate.from(value, { overflow: "reject" });
37
+ }
38
+
39
+ function referenceDate(rule: CalendarRule, reference: number): Temporal.PlainDate {
40
+ return getTemporal().Instant.fromEpochMilliseconds(reference).toZonedDateTimeISO(rule.timezone).toPlainDate();
41
+ }
42
+
43
+ function occurrence(rule: CalendarRule, date: Temporal.PlainDate): CalendarOccurrence | undefined {
44
+ if (rule.every === "week" && !rule.on!.includes(CALENDAR_WEEKDAYS[date.dayOfWeek - 1]!)) return undefined;
45
+ const requested = date.toPlainDateTime(rule.at);
46
+ const zoned = requested.toZonedDateTime(rule.timezone, { disambiguation: "earlier" });
47
+ // Skip nonexistent times/dates. A repeated time uses its first instant only.
48
+ if (!zoned.toPlainDateTime().equals(requested)) return undefined;
49
+ return { nextLocalDate: date.toString(), nextRunAt: new Date(zoned.epochMilliseconds).toISOString() };
50
+ }
51
+
52
+ export function nextCalendarOccurrence(rule: CalendarRule, after: number, minimumDate?: string): CalendarOccurrence {
53
+ let date = referenceDate(rule, after);
54
+ if (minimumDate && getTemporal().PlainDate.compare(date, localDate(minimumDate)) < 0) date = localDate(minimumDate);
55
+ for (let i = 0; i < SEARCH_DAYS; i++, date = date.add({ days: 1 })) {
56
+ const candidate = occurrence(rule, date);
57
+ if (candidate && Date.parse(candidate.nextRunAt) > after) return candidate;
58
+ }
59
+ throw new Error("No valid calendar occurrence within 32 local dates; check the timezone and rule.");
60
+ }
61
+
62
+ export function latestCalendarOccurrence(rule: CalendarRule, now: number, minimumDate: string): CalendarOccurrence | undefined {
63
+ const floor = localDate(minimumDate);
64
+ let date = referenceDate(rule, now);
65
+ for (let i = 0; i < SEARCH_DAYS; i++, date = date.subtract({ days: 1 })) {
66
+ if (getTemporal().PlainDate.compare(date, floor) < 0) return undefined;
67
+ const candidate = occurrence(rule, date);
68
+ if (candidate && Date.parse(candidate.nextRunAt) <= now) return candidate;
69
+ }
70
+ throw new Error("No valid calendar occurrence within 32 local dates; check the timezone and rule.");
71
+ }
72
+
73
+ export function calendarDateAfter(rule: CalendarRule, consumedAt: number, pendingDate: string): string {
74
+ const consumed = referenceDate(rule, consumedAt);
75
+ const pending = localDate(pendingDate);
76
+ return (getTemporal().PlainDate.compare(consumed, pending) > 0 ? consumed : pending).add({ days: 1 }).toString();
77
+ }
78
+
79
+ /** Re-resolve the pending date using current timezone data, without consulting its UTC cache. */
80
+ export function restoreCalendarTrigger(input: CalendarTrigger): CalendarTrigger {
81
+ const rule = normalizeCalendarRule(input);
82
+ let date = localDate(input.nextLocalDate);
83
+ if (rule.every === "week" && !rule.on!.includes(CALENDAR_WEEKDAYS[date.dayOfWeek - 1]!)) throw new Error("Calendar nextLocalDate is outside the selected weekdays.");
84
+ if (typeof input.nextRunAt !== "string" || !Number.isFinite(Date.parse(input.nextRunAt))) throw new Error("Calendar nextRunAt must be a valid timestamp.");
85
+ for (let i = 0; i < SEARCH_DAYS; i++, date = date.add({ days: 1 })) {
86
+ const candidate = occurrence(rule, date);
87
+ if (candidate) return { kind: "calendar", ...rule, ...candidate };
88
+ }
89
+ throw new Error("No valid pending calendar occurrence within 32 local dates.");
90
+ }
@@ -13,7 +13,8 @@ export interface ImportedAsyncRoot {
13
13
 
14
14
  export interface ImportedAsyncRootResult {
15
15
  agent: string;
16
- importedPublication?: { sessionId?: string; toolCallId?: string };
16
+ /** `snapshot` is the payload text this result was built from, so cleanup can tell it from a newer one. */
17
+ importedPublication?: { sessionId?: string; toolCallId?: string; snapshot: string };
17
18
  /** Human-readable display name for the child session, when derived at launch. */
18
19
  sessionName?: string;
19
20
  output: string;
@@ -83,18 +84,20 @@ interface AsyncResultFile {
83
84
  const TERMINAL_STATES = new Set(["complete", "failed", "partial", "paused", "stopped"]);
84
85
  const TERMINAL_STEP_STATUSES = new Set(["complete", "completed", "failed", "partial", "paused", "stopped"]);
85
86
 
86
- function readResultFile(resultPath: string): AsyncResultFile | undefined {
87
+ function readResultFile(resultPath: string): { data: AsyncResultFile; raw: string } | undefined {
88
+ let raw: string;
87
89
  try {
88
- return JSON.parse(fs.readFileSync(resultPath, "utf-8")) as AsyncResultFile;
90
+ raw = fs.readFileSync(resultPath, "utf-8");
89
91
  } catch (error) {
90
92
  if (typeof error === "object" && error !== null && "code" in error && (error as NodeJS.ErrnoException).code === "ENOENT") {
91
93
  return undefined;
92
94
  }
93
95
  throw error;
94
96
  }
97
+ return { data: JSON.parse(raw) as AsyncResultFile, raw };
95
98
  }
96
99
 
97
- function readImportedResultFile(root: ImportedAsyncRoot, status: AsyncStatus | null): AsyncResultFile | undefined {
100
+ function readImportedResultFile(root: ImportedAsyncRoot, status: AsyncStatus | null): { data: AsyncResultFile; raw: string } | undefined {
98
101
  const direct = readResultFile(root.resultPath);
99
102
  if (direct || !status?.sessionId) return direct;
100
103
  const indexedPath = resultPayloadPathForSessionRun(path.dirname(root.resultPath), status.sessionId, root.runId);
@@ -180,7 +183,7 @@ function outputFromTimeout(root: ImportedAsyncRoot, status: AsyncStatus | null,
180
183
  };
181
184
  }
182
185
 
183
- function buildImportedResult(root: ImportedAsyncRoot, status: AsyncStatus | null, result: AsyncResultFile): ImportedAsyncRootResult {
186
+ function buildImportedResult(root: ImportedAsyncRoot, status: AsyncStatus | null, { data: result, raw }: { data: AsyncResultFile; raw: string }): ImportedAsyncRootResult {
184
187
  const child = result.results?.[root.index];
185
188
  const step = selectedStatusStep(status, root.index);
186
189
  const state = resultState(result, child);
@@ -197,6 +200,7 @@ function buildImportedResult(root: ImportedAsyncRoot, status: AsyncStatus | null
197
200
  importedPublication: {
198
201
  ...(typeof result.sessionId === "string" ? { sessionId: result.sessionId } : {}),
199
202
  ...(typeof result.toolCallId === "string" ? { toolCallId: result.toolCallId } : {}),
203
+ snapshot: raw,
200
204
  },
201
205
  output: success ? output : (output || error || ""),
202
206
  success,
@@ -74,6 +74,44 @@ export interface SteerRequest {
74
74
  source?: string;
75
75
  }
76
76
 
77
+ export interface CommandRequest {
78
+ type: "command";
79
+ id: string;
80
+ ownerId: string;
81
+ operation: "status" | "yield" | "cancel";
82
+ toolCallId?: string;
83
+ deadlineAt: number;
84
+ }
85
+
86
+ function validCommandRequest(raw: unknown): raw is CommandRequest {
87
+ if (!raw || typeof raw !== "object") return false;
88
+ const value = raw as Partial<CommandRequest>;
89
+ return value.type === "command" && typeof value.id === "string" && /^[a-f0-9-]{36}$/.test(value.id)
90
+ && typeof value.ownerId === "string" && /^[a-f0-9-]{36}$/.test(value.ownerId)
91
+ && (value.operation === "status" || value.operation === "yield" || value.operation === "cancel")
92
+ && Number.isSafeInteger(value.deadlineAt) && value.deadlineAt! > 0
93
+ && (value.toolCallId === undefined ? value.operation === "status" : typeof value.toolCallId === "string" && value.toolCallId.length > 0 && value.toolCallId.length <= 256);
94
+ }
95
+
96
+ function commandRequestsDir(dir: string): string { return path.join(controlInboxDir(dir), "command-requests"); }
97
+ export function requestAsyncCommand(dir: string, request: CommandRequest): void {
98
+ if (!validCommandRequest(request)) throw new Error("Malformed command request.");
99
+ writeAtomicJson(path.join(commandRequestsDir(dir), `${request.id}.json`), request);
100
+ }
101
+ function consumeCommandRequests(dir: string, fsImpl: ControlChannelFs): CommandRequest[] {
102
+ const requests: CommandRequest[] = [];
103
+ for (const name of fsImpl.readdirSync(commandRequestsDir(dir)).filter((entry) => entry.endsWith(".json")).sort()) {
104
+ const file = path.join(commandRequestsDir(dir), name);
105
+ let value: unknown;
106
+ try { value = JSON.parse(fsImpl.readFileSync(file, "utf8")); }
107
+ catch (error) { if ((error as NodeJS.ErrnoException).code === "ENOENT") continue; }
108
+ try { fsImpl.rmSync(file); }
109
+ catch (error) { if ((error as NodeJS.ErrnoException).code === "ENOENT") continue; throw error; }
110
+ if (validCommandRequest(value)) requests.push(value);
111
+ }
112
+ return requests;
113
+ }
114
+
77
115
  const STEER_REQUESTS_DIR = "steer-requests";
78
116
  const STOP_REQUESTS_DIR = "stop-requests";
79
117
  const REVIVAL_BRIEFS_DIR = "revival-briefs";
@@ -519,6 +557,7 @@ export function watchAsyncControlInbox(
519
557
  onTimeout?: () => void;
520
558
  onStop?: (request: StopRequest) => void;
521
559
  onSteer?: (request: SteerRequest) => void;
560
+ onCommand?: (request: CommandRequest) => void;
522
561
  onError?: (error: unknown, phase: "install" | "scan" | "callback", request?: SteerRequest) => void;
523
562
  pollIntervalMs?: number;
524
563
  safetyPollIntervalMs?: number;
@@ -542,6 +581,7 @@ export function watchAsyncControlInbox(
542
581
  ...(opts.onInterrupt || opts.onTimeout || opts.onStop ? [dir] : []),
543
582
  ...(opts.onStop ? [stopRequestsDir(asyncDir)] : []),
544
583
  ...(opts.onSteer ? [steerRequestsDir(asyncDir)] : []),
584
+ ...(opts.onCommand ? [commandRequestsDir(asyncDir)] : []),
545
585
  ];
546
586
  if (dirs.length === 0) return () => {};
547
587
  try {
@@ -554,6 +594,9 @@ export function watchAsyncControlInbox(
554
594
  const check = (): void => {
555
595
  if (disposed) return;
556
596
  try {
597
+ if (opts.onCommand) for (const request of consumeCommandRequests(asyncDir, fsImpl)) {
598
+ try { opts.onCommand(request); } catch (error) { report(error, "callback"); }
599
+ }
557
600
  if (opts.onStop) for (const request of consumeStopRequestPayloads(asyncDir, fsImpl, (error) => report(error, "scan"))) {
558
601
  try { opts.onStop(request); } catch (error) { report(error, "callback"); }
559
602
  }
@@ -359,7 +359,7 @@ function formatAsyncFleetLines(runs: AsyncRunSummary[], now = Date.now()): strin
359
359
  const runContext = contextModeLabel(run.context);
360
360
  lines.push(`- ${run.id} | ${run.state}${activity ? ` | ${activity}` : ""} | ${run.mode}${runContext ? ` ${runContext}` : ""} | ${progress}${pending} | ${cwd}`);
361
361
  lines.push(` status: subagent({ action: "status", id: "${run.id}" })`);
362
- lines.push(` transcript: subagent({ action: "status", id: "${run.id}", view: "transcript" })`);
362
+ lines.push(` transcript: subagent({ action: "status", id: "${run.id}", options: { view: "transcript" } })`);
363
363
  for (const step of run.steps) {
364
364
  const display = fleetStepDisplayName(step);
365
365
  const stepContext = contextModeLabel(step.context);
@@ -372,7 +372,7 @@ function formatAsyncFleetLines(runs: AsyncRunSummary[], now = Date.now()): strin
372
372
  if (fs.existsSync(output)) lines.push(` output: ${shortenPath(output)}`);
373
373
  if (step.sessionFile) lines.push(` session: ${shortenPath(step.sessionFile)}`);
374
374
  if (step.status === "running" || step.recentOutput?.length || fs.existsSync(output)) {
375
- lines.push(` transcript: subagent({ action: "status", id: "${run.id}", index: ${step.index}, view: "transcript" })`);
375
+ lines.push(` transcript: subagent({ action: "status", id: "${run.id}", options: { index: ${step.index}, view: "transcript" } })`);
376
376
  }
377
377
  lines.push(...formatNestedRunStatusLines(step.children, { indent: " ", commandHints: true, maxLines: 12 }));
378
378
  }
@@ -432,9 +432,9 @@ export function inspectSubagentFleet(_params: FleetViewParams, deps: FleetViewDe
432
432
  const asyncLines = formatAsyncFleetLines(asyncRuns, deps.now?.() ?? Date.now());
433
433
  if (asyncLines.length) lines.push(...asyncLines, "");
434
434
  lines.push("Commands:");
435
- lines.push(" Refresh fleet: subagent({ action: \"status\", view: \"fleet\" })");
436
- lines.push(" Tail run transcript: subagent({ action: \"status\", id: \"<run-id>\", view: \"transcript\" })");
437
- lines.push(" Tail child transcript: subagent({ action: \"status\", id: \"<run-id>\", index: 0, view: \"transcript\" })");
435
+ lines.push(" Refresh fleet: subagent({ action: \"status\", options: { view: \"fleet\" } })");
436
+ lines.push(" Tail run transcript: subagent({ action: \"status\", id: \"<run-id>\", options: { view: \"transcript\" } })");
437
+ lines.push(" Tail child transcript: subagent({ action: \"status\", id: \"<run-id>\", options: { index: 0, view: \"transcript\" } })");
438
438
 
439
439
  return { content: [{ type: "text", text: lines.join("\n").trimEnd() }], details: { mode: "management", results: [] } };
440
440
  }