@xzzpig/pi-subagents 0.1.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.
- package/CHANGELOG.md +1621 -0
- package/LICENSE +21 -0
- package/README.md +118 -0
- package/agents/delegate.md +14 -0
- package/agents/oracle.md +74 -0
- package/agents/researcher.md +52 -0
- package/agents/reviewer.md +79 -0
- package/agents/scout.md +50 -0
- package/agents/worker.md +58 -0
- package/index.ts +1 -0
- package/inspector-runner.mjs +11 -0
- package/install.mjs +93 -0
- package/package.json +105 -0
- package/prompts/gather-context-and-clarify.md +13 -0
- package/prompts/parallel-cleanup.md +59 -0
- package/prompts/parallel-research.md +50 -0
- package/prompts/parallel-review.md +54 -0
- package/prompts/review-loop.md +43 -0
- package/skills/pi-subagents/SKILL.md +41 -0
- package/skills/pi-subagents/references/constraints-and-recipes.md +251 -0
- package/skills/pi-subagents/references/execution-controls.md +428 -0
- package/skills/pi-subagents/references/management-authoring-rpc.md +161 -0
- package/skills/pi-subagents/references/prompting-and-roles.md +242 -0
- package/src/agents/agent-management.ts +1256 -0
- package/src/agents/agent-memory.ts +254 -0
- package/src/agents/agent-refinements.ts +624 -0
- package/src/agents/agent-scope.ts +6 -0
- package/src/agents/agent-selection.ts +25 -0
- package/src/agents/agent-serializer.ts +163 -0
- package/src/agents/agents.ts +1889 -0
- package/src/agents/chain-serializer.ts +280 -0
- package/src/agents/frontmatter.ts +149 -0
- package/src/agents/identity.ts +30 -0
- package/src/agents/proactive-skills.ts +194 -0
- package/src/agents/skills.ts +761 -0
- package/src/api/background-work.ts +197 -0
- package/src/api/capability-ceiling.ts +17 -0
- package/src/api/control-channel.ts +4 -0
- package/src/api/delegation.ts +119 -0
- package/src/api/external-runs.ts +129 -0
- package/src/api/intercom-bridge.ts +3 -0
- package/src/api/pi-args.ts +5 -0
- package/src/api/preflight.ts +403 -0
- package/src/api/shared-types.ts +19 -0
- package/src/extension/config.ts +76 -0
- package/src/extension/control-notices.ts +58 -0
- package/src/extension/doctor.ts +230 -0
- package/src/extension/fanout-child.ts +201 -0
- package/src/extension/index.ts +805 -0
- package/src/extension/public-execution.ts +71 -0
- package/src/extension/rpc.ts +653 -0
- package/src/extension/schemas.ts +375 -0
- package/src/extension/steering-notices.ts +35 -0
- package/src/extension/tool-description.ts +164 -0
- package/src/inspectors/herdr/actions.ts +229 -0
- package/src/inspectors/herdr/client.ts +130 -0
- package/src/inspectors/herdr/inspector-runner.ts +141 -0
- package/src/inspectors/herdr/project-panes.ts +154 -0
- package/src/integrations/herdr-status.ts +330 -0
- package/src/intercom/intercom-bridge.ts +187 -0
- package/src/intercom/native-supervisor-channel.ts +715 -0
- package/src/intercom/result-intercom.ts +421 -0
- package/src/missions/actions.ts +410 -0
- package/src/missions/goal-driver.ts +162 -0
- package/src/missions/lifecycle.ts +346 -0
- package/src/missions/store.ts +507 -0
- package/src/missions/types.ts +157 -0
- package/src/missions/workflow-state.ts +250 -0
- package/src/policy/authority.ts +46 -0
- package/src/profiles/profiles.ts +661 -0
- package/src/runs/background/async-execution.ts +1574 -0
- package/src/runs/background/async-job-tracker.ts +511 -0
- package/src/runs/background/async-resume.ts +539 -0
- package/src/runs/background/async-status.ts +542 -0
- package/src/runs/background/auto-drain.ts +67 -0
- package/src/runs/background/chain-append.ts +328 -0
- package/src/runs/background/chain-root-attachment.ts +199 -0
- package/src/runs/background/completion-batcher.ts +168 -0
- package/src/runs/background/completion-dedupe.ts +54 -0
- package/src/runs/background/control-channel.ts +692 -0
- package/src/runs/background/fleet-view.ts +540 -0
- package/src/runs/background/notify.ts +332 -0
- package/src/runs/background/parallel-groups.ts +45 -0
- package/src/runs/background/process-terminal.ts +280 -0
- package/src/runs/background/result-watcher.ts +414 -0
- package/src/runs/background/retained-children.ts +68 -0
- package/src/runs/background/run-id-resolver.ts +167 -0
- package/src/runs/background/run-status.ts +504 -0
- package/src/runs/background/scheduled-runs.ts +753 -0
- package/src/runs/background/stale-run-reconciler.ts +396 -0
- package/src/runs/background/steering.ts +239 -0
- package/src/runs/background/subagent-runner.ts +4718 -0
- package/src/runs/background/subagent-wait.ts +661 -0
- package/src/runs/background/top-level-async.ts +14 -0
- package/src/runs/background/wait-completions.ts +112 -0
- package/src/runs/background/wait-config.ts +36 -0
- package/src/runs/background/wait-subscriptions.ts +253 -0
- package/src/runs/background/wait-tool.ts +34 -0
- package/src/runs/foreground/async-steering-action.ts +256 -0
- package/src/runs/foreground/async-stop-action.ts +65 -0
- package/src/runs/foreground/chain-clarify.ts +1354 -0
- package/src/runs/foreground/chain-execution.ts +1527 -0
- package/src/runs/foreground/execution.ts +1868 -0
- package/src/runs/foreground/foreground-control.ts +132 -0
- package/src/runs/foreground/subagent-executor.ts +5532 -0
- package/src/runs/shared/acceptance.ts +1365 -0
- package/src/runs/shared/agent-contract.ts +38 -0
- package/src/runs/shared/capability-ceiling.ts +209 -0
- package/src/runs/shared/chain-outputs.ts +118 -0
- package/src/runs/shared/child-protocol.ts +401 -0
- package/src/runs/shared/completion-guard.ts +95 -0
- package/src/runs/shared/context-mode.ts +44 -0
- package/src/runs/shared/dynamic-fanout.ts +297 -0
- package/src/runs/shared/external-cli-runner.ts +130 -0
- package/src/runs/shared/long-running-guard.ts +220 -0
- package/src/runs/shared/mcp-direct-tool-allowlist.ts +406 -0
- package/src/runs/shared/model-fallback.ts +336 -0
- package/src/runs/shared/model-scope.ts +128 -0
- package/src/runs/shared/nested-events.ts +1076 -0
- package/src/runs/shared/nested-path.ts +52 -0
- package/src/runs/shared/nested-render.ts +123 -0
- package/src/runs/shared/parallel-handoff.ts +238 -0
- package/src/runs/shared/parallel-utils.ts +256 -0
- package/src/runs/shared/permissions.ts +95 -0
- package/src/runs/shared/pi-args.ts +808 -0
- package/src/runs/shared/pi-spawn.ts +163 -0
- package/src/runs/shared/process-signal.ts +19 -0
- package/src/runs/shared/run-history.ts +181 -0
- package/src/runs/shared/runtime-acknowledged-extensions.ts +71 -0
- package/src/runs/shared/session-lease.ts +299 -0
- package/src/runs/shared/single-output.ts +235 -0
- package/src/runs/shared/spawn-budget.ts +128 -0
- package/src/runs/shared/structured-output.ts +182 -0
- package/src/runs/shared/subagent-control.ts +231 -0
- package/src/runs/shared/subagent-prompt-runtime.ts +588 -0
- package/src/runs/shared/subagent-startup-retry.ts +104 -0
- package/src/runs/shared/task-intent.ts +181 -0
- package/src/runs/shared/tool-availability.ts +83 -0
- package/src/runs/shared/tool-budget.ts +80 -0
- package/src/runs/shared/turn-budget.ts +98 -0
- package/src/runs/shared/usage-budget.ts +65 -0
- package/src/runs/shared/workflow-graph.ts +231 -0
- package/src/runs/shared/worktree.ts +759 -0
- package/src/shared/accessible-dir.ts +47 -0
- package/src/shared/artifacts.ts +285 -0
- package/src/shared/atomic-json.ts +61 -0
- package/src/shared/child-transcript.ts +264 -0
- package/src/shared/file-coalescer.ts +40 -0
- package/src/shared/file-system-retry.ts +47 -0
- package/src/shared/fork-context.ts +213 -0
- package/src/shared/formatters.ts +133 -0
- package/src/shared/jsonl-writer.ts +81 -0
- package/src/shared/launch-contract.ts +124 -0
- package/src/shared/model-info.ts +81 -0
- package/src/shared/post-exit-stdio-guard.ts +85 -0
- package/src/shared/session-identity.ts +10 -0
- package/src/shared/session-tokens.ts +44 -0
- package/src/shared/settings.ts +501 -0
- package/src/shared/status-format.ts +55 -0
- package/src/shared/types.ts +2069 -0
- package/src/shared/utils.ts +613 -0
- package/src/slash/delegation-adapters.ts +434 -0
- package/src/slash/delegation-json.ts +108 -0
- package/src/slash/delegation-request.ts +166 -0
- package/src/slash/prompt-template-bridge.ts +383 -0
- package/src/slash/prompt-workflows.ts +300 -0
- package/src/slash/selector.ts +147 -0
- package/src/slash/slash-bridge.ts +192 -0
- package/src/slash/slash-commands.ts +994 -0
- package/src/slash/slash-live-state.ts +296 -0
- package/src/slash/subagents-admin.ts +432 -0
- package/src/tui/fleet-status.ts +564 -0
- package/src/tui/fleet-transcript.ts +577 -0
- package/src/tui/fleet.ts +879 -0
- package/src/tui/render-helpers.ts +80 -0
- package/src/tui/render.ts +2029 -0
- package/src/types/pi-runtime-compat.d.ts +8 -0
- package/src/watchdog/change-signature.ts +220 -0
- package/src/watchdog/child-status.ts +205 -0
- package/src/watchdog/emission-guard.ts +123 -0
- package/src/watchdog/lsp-diagnostics.ts +537 -0
- package/src/watchdog/model-selection.ts +167 -0
- package/src/watchdog/permission-arbiter.ts +145 -0
- package/src/watchdog/register-child.ts +117 -0
- package/src/watchdog/register-main.ts +440 -0
- package/src/watchdog/render.ts +54 -0
- package/src/watchdog/review.ts +302 -0
- package/src/watchdog/runtime.ts +868 -0
- package/src/watchdog/scope.ts +62 -0
- package/src/watchdog/settings.ts +568 -0
- package/src/watchdog/tool-actions.ts +155 -0
- package/src/watchdog/turn-delta.ts +161 -0
- package/src/watchdog/types.ts +198 -0
- package/src/watchdog/warning-format.ts +73 -0
- package/src/workflows/chat-progress.ts +140 -0
- package/src/workflows/scripted-workflow.ts +506 -0
|
@@ -0,0 +1,332 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Completion notification delivery.
|
|
3
|
+
*
|
|
4
|
+
* Async result files call this notifier directly and are deleted only after
|
|
5
|
+
* `sendMessage()` accepts the notification. The event bus remains an
|
|
6
|
+
* observation channel, not a delivery acknowledgement.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
|
|
10
|
+
import { buildCompletionKey, markSeenWithTtl } from "./completion-dedupe.ts";
|
|
11
|
+
import {
|
|
12
|
+
type CompletionBatchConfig,
|
|
13
|
+
type CompletionBatcher,
|
|
14
|
+
createCompletionBatcher,
|
|
15
|
+
resolveCompletionBatchConfig,
|
|
16
|
+
} from "./completion-batcher.ts";
|
|
17
|
+
import { SUBAGENT_ASYNC_COMPLETE_EVENT, SUBAGENT_FOREGROUND_COMPLETE_EVENT, type ParallelHandoffReference, type SubagentState } from "../../shared/types.ts";
|
|
18
|
+
import { isUnexplainedProcessSignal } from "../shared/process-signal.ts";
|
|
19
|
+
|
|
20
|
+
export interface SubagentNotifyDetails {
|
|
21
|
+
agent: string;
|
|
22
|
+
status: "completed" | "failed" | "paused" | "stopped";
|
|
23
|
+
source?: "async" | "foreground";
|
|
24
|
+
taskInfo?: string;
|
|
25
|
+
resultPreview: string;
|
|
26
|
+
durationMs?: number;
|
|
27
|
+
sessionLabel?: string;
|
|
28
|
+
sessionValue?: string;
|
|
29
|
+
handoffPath?: string;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export interface CompletionNotification {
|
|
33
|
+
[key: string]: unknown;
|
|
34
|
+
id?: string | null;
|
|
35
|
+
source?: "async" | "foreground";
|
|
36
|
+
agent?: string | null;
|
|
37
|
+
success?: boolean;
|
|
38
|
+
summary?: string;
|
|
39
|
+
exitCode?: number;
|
|
40
|
+
state?: string;
|
|
41
|
+
processSignal?: string | null;
|
|
42
|
+
interrupted?: boolean;
|
|
43
|
+
timedOut?: boolean;
|
|
44
|
+
stopped?: boolean;
|
|
45
|
+
turnBudgetExceeded?: boolean;
|
|
46
|
+
results?: Array<{
|
|
47
|
+
status?: string;
|
|
48
|
+
success?: boolean;
|
|
49
|
+
exitCode?: number | null;
|
|
50
|
+
processSignal?: string | null;
|
|
51
|
+
interrupted?: boolean;
|
|
52
|
+
timedOut?: boolean;
|
|
53
|
+
stopped?: boolean;
|
|
54
|
+
turnBudgetExceeded?: boolean;
|
|
55
|
+
}>;
|
|
56
|
+
timestamp?: number;
|
|
57
|
+
durationMs?: number;
|
|
58
|
+
cwd?: string;
|
|
59
|
+
sessionFile?: string;
|
|
60
|
+
shareUrl?: string;
|
|
61
|
+
gistUrl?: string;
|
|
62
|
+
shareError?: string;
|
|
63
|
+
taskIndex?: number;
|
|
64
|
+
totalTasks?: number;
|
|
65
|
+
sessionId?: string | null;
|
|
66
|
+
triggerTurn?: boolean;
|
|
67
|
+
/** True when an acknowledged grouped intercom relay already delivered this run. */
|
|
68
|
+
intercomDelivered?: boolean;
|
|
69
|
+
parallelHandoff?: ParallelHandoffReference;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
interface NotifyTimerApi {
|
|
73
|
+
setTimeout(handler: () => void, delayMs: number): unknown;
|
|
74
|
+
clearTimeout(handle: unknown): void;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
export interface RegisterSubagentNotifyOptions {
|
|
78
|
+
batchConfig?: CompletionBatchConfig;
|
|
79
|
+
timers?: NotifyTimerApi;
|
|
80
|
+
now?: () => number;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
export interface CompletionNotifier {
|
|
84
|
+
deliver(result: CompletionNotification): Promise<boolean>;
|
|
85
|
+
dispose(): void;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
function formatSessionLine(details: SubagentNotifyDetails): string | undefined {
|
|
89
|
+
if (!details.sessionValue) return undefined;
|
|
90
|
+
return details.sessionLabel ? `${details.sessionLabel}: ${details.sessionValue}` : details.sessionValue;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
export function formatSingleCompletion(details: SubagentNotifyDetails): string {
|
|
94
|
+
const sessionLine = formatSessionLine(details);
|
|
95
|
+
const taskKind = details.source === "foreground" ? "Detached foreground task" : "Background task";
|
|
96
|
+
return [
|
|
97
|
+
`${taskKind} ${details.status}: **${details.agent}**${details.taskInfo ?? ""}`,
|
|
98
|
+
"",
|
|
99
|
+
details.resultPreview.trim() ? details.resultPreview : "(no output)",
|
|
100
|
+
details.handoffPath ? "" : undefined,
|
|
101
|
+
details.handoffPath ? `Parallel handoff: ${details.handoffPath}` : undefined,
|
|
102
|
+
sessionLine ? "" : undefined,
|
|
103
|
+
sessionLine,
|
|
104
|
+
]
|
|
105
|
+
.filter((line) => line !== undefined)
|
|
106
|
+
.join("\n");
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
export function parseSubagentNotifyContent(content: string): SubagentNotifyDetails | undefined {
|
|
110
|
+
const lines = content.split("\n");
|
|
111
|
+
const match = (lines[0] ?? "").match(/^(Background task|Detached foreground task) (completed|failed|paused|stopped): \*\*(.+?)\*\*(?:\s+(\([^)]*\)))?$/);
|
|
112
|
+
if (!match) return undefined;
|
|
113
|
+
const body = lines.slice(2);
|
|
114
|
+
let sessionIndex = -1;
|
|
115
|
+
for (let i = body.length - 1; i >= 1; i--) {
|
|
116
|
+
if (body[i - 1]?.trim() === "" && /^(Session|Session file|Session share error):\s+/.test(body[i]!)) {
|
|
117
|
+
sessionIndex = i;
|
|
118
|
+
break;
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
const sessionLine = sessionIndex >= 0 ? body[sessionIndex] : undefined;
|
|
122
|
+
const handoffIndex = body.findIndex((line) => line.startsWith("Parallel handoff: "));
|
|
123
|
+
const metadataIndexes = [sessionIndex, handoffIndex].filter((index) => index >= 0);
|
|
124
|
+
const firstMetadataIndex = metadataIndexes.length ? Math.min(...metadataIndexes) : body.length;
|
|
125
|
+
const resultEnd = firstMetadataIndex > 0 && body[firstMetadataIndex - 1]?.trim() === "" ? firstMetadataIndex - 1 : firstMetadataIndex;
|
|
126
|
+
const resultPreview = body.slice(0, resultEnd).join("\n").trim() || "(no output)";
|
|
127
|
+
const handoffPath = handoffIndex >= 0 ? body[handoffIndex]!.slice("Parallel handoff: ".length).trim() : undefined;
|
|
128
|
+
let sessionLabel: string | undefined;
|
|
129
|
+
let sessionValue: string | undefined;
|
|
130
|
+
if (sessionLine) {
|
|
131
|
+
const separator = sessionLine.indexOf(":");
|
|
132
|
+
sessionLabel = sessionLine.slice(0, separator).toLowerCase();
|
|
133
|
+
sessionValue = sessionLine.slice(separator + 1).trim();
|
|
134
|
+
}
|
|
135
|
+
return {
|
|
136
|
+
agent: match[3]!,
|
|
137
|
+
status: match[2] as SubagentNotifyDetails["status"],
|
|
138
|
+
...(match[1] === "Detached foreground task" ? { source: "foreground" as const } : {}),
|
|
139
|
+
...(match[4] ? { taskInfo: match[4] } : {}),
|
|
140
|
+
resultPreview,
|
|
141
|
+
...(handoffPath ? { handoffPath } : {}),
|
|
142
|
+
...(sessionLabel && sessionValue ? { sessionLabel, sessionValue } : {}),
|
|
143
|
+
};
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
export function formatGroupedCompletion(details: SubagentNotifyDetails[]): string {
|
|
147
|
+
const header = `Background tasks completed (${details.length}): ${details.map((d) => `**${d.agent}**${d.taskInfo ?? ""}`).join(", ")}`;
|
|
148
|
+
const blocks: string[] = [header, ""];
|
|
149
|
+
for (let index = 0; index < details.length; index++) {
|
|
150
|
+
const detail = details[index];
|
|
151
|
+
if (!detail) continue;
|
|
152
|
+
const sessionLine = formatSessionLine(detail);
|
|
153
|
+
blocks.push(`${index + 1}. ${detail.agent}${detail.taskInfo ?? ""}`);
|
|
154
|
+
blocks.push(detail.resultPreview.trim() ? detail.resultPreview : "(no output)");
|
|
155
|
+
if (detail.handoffPath) blocks.push(`Parallel handoff: ${detail.handoffPath}`);
|
|
156
|
+
if (sessionLine) blocks.push(sessionLine);
|
|
157
|
+
blocks.push("");
|
|
158
|
+
}
|
|
159
|
+
return blocks.join("\n").trimEnd();
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
interface PendingCompletion {
|
|
163
|
+
key: string;
|
|
164
|
+
details: SubagentNotifyDetails;
|
|
165
|
+
triggerTurn: boolean;
|
|
166
|
+
resolve(accepted: boolean): void;
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
function sendCompletion(pi: Pick<ExtensionAPI, "sendMessage">, items: PendingCompletion[]): boolean {
|
|
170
|
+
if (items.length === 0) return true;
|
|
171
|
+
const details = items.map((item) => item.details);
|
|
172
|
+
const content = details.length === 1 ? formatSingleCompletion(details[0]!) : formatGroupedCompletion(details);
|
|
173
|
+
const display = details.some((detail) => detail.source === "foreground" || detail.status !== "completed");
|
|
174
|
+
try {
|
|
175
|
+
pi.sendMessage(
|
|
176
|
+
{
|
|
177
|
+
customType: "subagent-notify",
|
|
178
|
+
content,
|
|
179
|
+
display,
|
|
180
|
+
},
|
|
181
|
+
{ triggerTurn: items.some((item) => item.triggerTurn) },
|
|
182
|
+
);
|
|
183
|
+
return true;
|
|
184
|
+
} catch {
|
|
185
|
+
return false;
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
function completionBatchKey(result: CompletionNotification): string {
|
|
190
|
+
const sessionId = typeof result.sessionId === "string" ? result.sessionId.trim() : "";
|
|
191
|
+
if (sessionId) return `session:${sessionId}`;
|
|
192
|
+
const cwd = typeof result.cwd === "string" ? result.cwd.trim() : "";
|
|
193
|
+
return cwd ? `cwd:${cwd}` : "unknown";
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
export function buildCompletionDetails(result: CompletionNotification): SubagentNotifyDetails {
|
|
197
|
+
const agent = result.agent ?? "unknown";
|
|
198
|
+
const summary = typeof result.summary === "string" ? result.summary : "";
|
|
199
|
+
const stopped = result.stopped === true
|
|
200
|
+
|| result.state === "stopped"
|
|
201
|
+
|| (result.success !== true && result.exitCode !== 0 && isUnexplainedProcessSignal(result))
|
|
202
|
+
|| result.results?.some((child) => child.stopped === true
|
|
203
|
+
|| child.status === "stopped"
|
|
204
|
+
|| (child.success !== true && child.exitCode !== 0 && isUnexplainedProcessSignal(child))) === true;
|
|
205
|
+
const paused = !stopped && !result.success && (
|
|
206
|
+
result.exitCode === 0
|
|
207
|
+
|| result.state === "paused"
|
|
208
|
+
|| summary.startsWith("Paused after interrupt.")
|
|
209
|
+
);
|
|
210
|
+
const status = stopped ? "stopped" : paused ? "paused" : result.success ? "completed" : "failed";
|
|
211
|
+
const taskInfo =
|
|
212
|
+
result.taskIndex !== undefined && result.totalTasks !== undefined
|
|
213
|
+
? ` (${result.taskIndex + 1}/${result.totalTasks})`
|
|
214
|
+
: undefined;
|
|
215
|
+
|
|
216
|
+
const parallelHandoff = result.parallelHandoff && typeof result.parallelHandoff === "object"
|
|
217
|
+
? result.parallelHandoff as { path?: unknown }
|
|
218
|
+
: undefined;
|
|
219
|
+
const handoffPath = typeof parallelHandoff?.path === "string" ? parallelHandoff.path : undefined;
|
|
220
|
+
const session =
|
|
221
|
+
result.shareUrl
|
|
222
|
+
? { label: "Session", value: result.shareUrl }
|
|
223
|
+
: result.shareError
|
|
224
|
+
? { label: "Session share error", value: result.shareError }
|
|
225
|
+
: result.sessionFile
|
|
226
|
+
? { label: "Session file", value: result.sessionFile }
|
|
227
|
+
: undefined;
|
|
228
|
+
return {
|
|
229
|
+
agent,
|
|
230
|
+
status,
|
|
231
|
+
...(result.source ? { source: result.source } : {}),
|
|
232
|
+
...(taskInfo ? { taskInfo } : {}),
|
|
233
|
+
resultPreview: summary,
|
|
234
|
+
...(typeof result.durationMs === "number" ? { durationMs: result.durationMs } : {}),
|
|
235
|
+
...(handoffPath ? { handoffPath } : {}),
|
|
236
|
+
...(session ? { sessionLabel: session.label, sessionValue: session.value } : {}),
|
|
237
|
+
};
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
export default function registerSubagentNotify(
|
|
241
|
+
pi: ExtensionAPI,
|
|
242
|
+
state: Pick<SubagentState, "currentSessionId">,
|
|
243
|
+
options: RegisterSubagentNotifyOptions = {},
|
|
244
|
+
): CompletionNotifier {
|
|
245
|
+
const seen = new Map<string, number>();
|
|
246
|
+
const pending = new Map<string, Promise<boolean>>();
|
|
247
|
+
const ttlMs = 10 * 60 * 1000;
|
|
248
|
+
const now = options.now ?? Date.now;
|
|
249
|
+
const batchConfig = resolveCompletionBatchConfig(options.batchConfig);
|
|
250
|
+
const batchers = new Map<string, CompletionBatcher<PendingCompletion>>();
|
|
251
|
+
let disposed = false;
|
|
252
|
+
|
|
253
|
+
const settle = (items: PendingCompletion[], accepted: boolean) => {
|
|
254
|
+
for (const item of items) {
|
|
255
|
+
pending.delete(item.key);
|
|
256
|
+
if (accepted) markSeenWithTtl(seen, item.key, now(), ttlMs);
|
|
257
|
+
item.resolve(accepted);
|
|
258
|
+
}
|
|
259
|
+
};
|
|
260
|
+
const emit = (items: PendingCompletion[]) => settle(items, sendCompletion(pi, items));
|
|
261
|
+
const getBatcher = (result: CompletionNotification) => {
|
|
262
|
+
const key = completionBatchKey(result);
|
|
263
|
+
let batcher = batchers.get(key);
|
|
264
|
+
if (!batcher) {
|
|
265
|
+
batcher = createCompletionBatcher<PendingCompletion>({
|
|
266
|
+
config: batchConfig,
|
|
267
|
+
emit,
|
|
268
|
+
...(options.timers ? { timers: options.timers } : {}),
|
|
269
|
+
now,
|
|
270
|
+
});
|
|
271
|
+
batchers.set(key, batcher);
|
|
272
|
+
}
|
|
273
|
+
return batcher;
|
|
274
|
+
};
|
|
275
|
+
|
|
276
|
+
const deliver = (result: CompletionNotification): Promise<boolean> => {
|
|
277
|
+
if (disposed || typeof result.sessionId !== "string" || result.sessionId !== state.currentSessionId) return Promise.resolve(false);
|
|
278
|
+
if (result.intercomDelivered === true) return Promise.resolve(true);
|
|
279
|
+
const key = buildCompletionKey(result, "notify");
|
|
280
|
+
const seenAt = seen.get(key);
|
|
281
|
+
if (seenAt !== undefined && now() - seenAt <= ttlMs) return Promise.resolve(true);
|
|
282
|
+
if (seenAt !== undefined) seen.delete(key);
|
|
283
|
+
const inFlight = pending.get(key);
|
|
284
|
+
if (inFlight) return inFlight;
|
|
285
|
+
const details = buildCompletionDetails(result);
|
|
286
|
+
let resolve!: (accepted: boolean) => void;
|
|
287
|
+
const completion = new Promise<boolean>((settleCompletion) => { resolve = settleCompletion; });
|
|
288
|
+
pending.set(key, completion);
|
|
289
|
+
const item: PendingCompletion = {
|
|
290
|
+
key,
|
|
291
|
+
details,
|
|
292
|
+
triggerTurn: result.triggerTurn !== false,
|
|
293
|
+
resolve,
|
|
294
|
+
};
|
|
295
|
+
if (details.source === "foreground") {
|
|
296
|
+
emit([item]);
|
|
297
|
+
return completion;
|
|
298
|
+
}
|
|
299
|
+
const batcher = getBatcher(result);
|
|
300
|
+
if (details.status !== "completed") {
|
|
301
|
+
batcher.flush();
|
|
302
|
+
emit([item]);
|
|
303
|
+
return completion;
|
|
304
|
+
}
|
|
305
|
+
batcher.push(item);
|
|
306
|
+
return completion;
|
|
307
|
+
};
|
|
308
|
+
|
|
309
|
+
const unsubscribeAsync = pi.events.on(SUBAGENT_ASYNC_COMPLETE_EVENT, (data) => {
|
|
310
|
+
void deliver(data as CompletionNotification);
|
|
311
|
+
});
|
|
312
|
+
const unsubscribeForeground = pi.events.on(SUBAGENT_FOREGROUND_COMPLETE_EVENT, (data) => {
|
|
313
|
+
void deliver(data as CompletionNotification);
|
|
314
|
+
});
|
|
315
|
+
|
|
316
|
+
return {
|
|
317
|
+
deliver,
|
|
318
|
+
dispose() {
|
|
319
|
+
if (disposed) return;
|
|
320
|
+
disposed = true;
|
|
321
|
+
for (const batcher of batchers.values()) settle(batcher.dispose(), false);
|
|
322
|
+
batchers.clear();
|
|
323
|
+
for (const unsubscribe of [unsubscribeAsync, unsubscribeForeground]) {
|
|
324
|
+
try {
|
|
325
|
+
unsubscribe?.();
|
|
326
|
+
} catch {
|
|
327
|
+
// The runtime is already shutting down; pending records stay on disk.
|
|
328
|
+
}
|
|
329
|
+
}
|
|
330
|
+
},
|
|
331
|
+
};
|
|
332
|
+
}
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import type { AsyncParallelGroupStatus } from "../../shared/types.ts";
|
|
2
|
+
|
|
3
|
+
function isValidParallelGroup(group: unknown, stepCount: number, chainStepCount: number): group is AsyncParallelGroupStatus {
|
|
4
|
+
if (typeof group !== "object" || group === null) return false;
|
|
5
|
+
const { start, count, stepIndex } = group as Partial<AsyncParallelGroupStatus>;
|
|
6
|
+
return typeof start === "number"
|
|
7
|
+
&& typeof count === "number"
|
|
8
|
+
&& typeof stepIndex === "number"
|
|
9
|
+
&& Number.isInteger(start)
|
|
10
|
+
&& Number.isInteger(count)
|
|
11
|
+
&& Number.isInteger(stepIndex)
|
|
12
|
+
&& start >= 0
|
|
13
|
+
&& count > 0
|
|
14
|
+
&& stepIndex >= 0
|
|
15
|
+
&& stepIndex < chainStepCount
|
|
16
|
+
&& start + count <= stepCount;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export function normalizeParallelGroups(groups: unknown, stepCount: number, chainStepCount: number): AsyncParallelGroupStatus[] {
|
|
20
|
+
if (!Array.isArray(groups)) return [];
|
|
21
|
+
return groups
|
|
22
|
+
.filter((group): group is AsyncParallelGroupStatus => isValidParallelGroup(group, stepCount, chainStepCount))
|
|
23
|
+
.sort((left, right) => left.stepIndex - right.stepIndex || left.start - right.start);
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export function flatToLogicalStepIndex(flatIndex: number, chainStepCount: number, groups: AsyncParallelGroupStatus[]): number {
|
|
27
|
+
let logicalIndex = 0;
|
|
28
|
+
let cursor = 0;
|
|
29
|
+
for (const group of groups) {
|
|
30
|
+
while (cursor < group.start && logicalIndex < chainStepCount) {
|
|
31
|
+
if (cursor === flatIndex) return logicalIndex;
|
|
32
|
+
cursor++;
|
|
33
|
+
logicalIndex++;
|
|
34
|
+
}
|
|
35
|
+
if (flatIndex >= group.start && flatIndex < group.start + group.count) return group.stepIndex;
|
|
36
|
+
cursor = group.start + group.count;
|
|
37
|
+
logicalIndex = group.stepIndex + 1;
|
|
38
|
+
}
|
|
39
|
+
while (cursor <= flatIndex && logicalIndex < chainStepCount) {
|
|
40
|
+
if (cursor === flatIndex) return logicalIndex;
|
|
41
|
+
cursor++;
|
|
42
|
+
logicalIndex++;
|
|
43
|
+
}
|
|
44
|
+
return Math.max(0, chainStepCount - 1);
|
|
45
|
+
}
|
|
@@ -0,0 +1,280 @@
|
|
|
1
|
+
import * as fs from "node:fs";
|
|
2
|
+
import * as path from "node:path";
|
|
3
|
+
import { writeAtomicJson, writePrivateAtomicJson } from "../../shared/atomic-json.ts";
|
|
4
|
+
import {
|
|
5
|
+
SUBAGENT_LIFECYCLE_ARTIFACT_VERSION,
|
|
6
|
+
type AsyncStatus,
|
|
7
|
+
type CanonicalSessionTerminalV1,
|
|
8
|
+
type ProcessInstanceExitV1,
|
|
9
|
+
type ProcessTerminalReason,
|
|
10
|
+
type ProcessTerminalV1,
|
|
11
|
+
} from "../../shared/types.ts";
|
|
12
|
+
import { canonicalSessionId, inspectSessionLease } from "../shared/session-lease.ts";
|
|
13
|
+
|
|
14
|
+
export interface ProcessTerminalCandidate {
|
|
15
|
+
version: 1;
|
|
16
|
+
runId: string;
|
|
17
|
+
runnerProcessInstanceId: string;
|
|
18
|
+
writers: Record<string, ProcessInstanceExitV1[]>;
|
|
19
|
+
expectedWriters?: Record<string, number>;
|
|
20
|
+
sessionFile?: string;
|
|
21
|
+
revivalLeaseToken?: string;
|
|
22
|
+
revivalLeaseReleaseAcknowledged?: boolean;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export interface RunnerCloseObservation {
|
|
26
|
+
processInstanceId: string;
|
|
27
|
+
closeObservedAt: number;
|
|
28
|
+
exitCode: number | null;
|
|
29
|
+
signal: string | null;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
function isRecord(value: unknown): value is Record<string, unknown> {
|
|
33
|
+
return Boolean(value) && typeof value === "object" && !Array.isArray(value);
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
function validProcessInstance(value: unknown, kind?: "runner" | "pi-writer"): value is ProcessInstanceExitV1 {
|
|
37
|
+
if (!isRecord(value)) return false;
|
|
38
|
+
if (typeof value.processInstanceId !== "string" || value.processInstanceId.length === 0) return false;
|
|
39
|
+
if (kind ? value.kind !== kind : (value.kind !== "runner" && value.kind !== "pi-writer")) return false;
|
|
40
|
+
if (typeof value.closeObservedAt !== "number" || !Number.isFinite(value.closeObservedAt)) return false;
|
|
41
|
+
if (typeof value.exitCode !== "number" && value.exitCode !== null) return false;
|
|
42
|
+
if (typeof value.signal !== "string" && value.signal !== null) return false;
|
|
43
|
+
return value.kind === "runner"
|
|
44
|
+
? value.attempt === undefined
|
|
45
|
+
: typeof value.attempt === "number" && Number.isInteger(value.attempt) && value.attempt >= 0;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
function validInstance(value: unknown): value is ProcessInstanceExitV1 {
|
|
49
|
+
return validProcessInstance(value, "pi-writer");
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
export function processTerminalCandidatePath(asyncDir: string): string {
|
|
53
|
+
return path.join(asyncDir, "process-terminal-candidate.json");
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
export function processTerminalPath(asyncDir: string): string {
|
|
57
|
+
return path.join(asyncDir, "process-terminal.json");
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
function errorMessage(error: unknown): string {
|
|
61
|
+
return error instanceof Error ? error.message : String(error);
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
export function readProcessTerminalCandidate(asyncDir: string): ProcessTerminalCandidate | undefined {
|
|
65
|
+
try {
|
|
66
|
+
const raw = JSON.parse(fs.readFileSync(processTerminalCandidatePath(asyncDir), "utf-8")) as unknown;
|
|
67
|
+
if (!isRecord(raw) || raw.version !== 1 || typeof raw.runId !== "string" || typeof raw.runnerProcessInstanceId !== "string" || !isRecord(raw.writers)) {
|
|
68
|
+
throw new Error(`Invalid process-terminal candidate in '${asyncDir}'.`);
|
|
69
|
+
}
|
|
70
|
+
const writers: Record<string, ProcessInstanceExitV1[]> = {};
|
|
71
|
+
for (const [index, entries] of Object.entries(raw.writers)) {
|
|
72
|
+
if (!Array.isArray(entries) || !entries.every(validInstance)) throw new Error(`Invalid writer process records for child '${index}'.`);
|
|
73
|
+
writers[index] = entries;
|
|
74
|
+
}
|
|
75
|
+
let expectedWriters: Record<string, number> | undefined;
|
|
76
|
+
if (raw.expectedWriters !== undefined) {
|
|
77
|
+
if (!isRecord(raw.expectedWriters)) throw new Error("Invalid expected writer process records.");
|
|
78
|
+
expectedWriters = {};
|
|
79
|
+
for (const [index, count] of Object.entries(raw.expectedWriters)) {
|
|
80
|
+
if (typeof count !== "number" || !Number.isInteger(count) || count < 0) throw new Error(`Invalid expected writer count for child '${index}'.`);
|
|
81
|
+
expectedWriters[index] = count;
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
if (raw.sessionFile !== undefined && typeof raw.sessionFile !== "string") throw new Error("Invalid process-terminal candidate sessionFile.");
|
|
85
|
+
if (raw.revivalLeaseToken !== undefined && typeof raw.revivalLeaseToken !== "string") throw new Error("Invalid process-terminal candidate lease token.");
|
|
86
|
+
if (raw.revivalLeaseReleaseAcknowledged !== undefined && typeof raw.revivalLeaseReleaseAcknowledged !== "boolean") throw new Error("Invalid process-terminal lease release acknowledgement.");
|
|
87
|
+
return {
|
|
88
|
+
version: 1,
|
|
89
|
+
runId: raw.runId,
|
|
90
|
+
runnerProcessInstanceId: raw.runnerProcessInstanceId,
|
|
91
|
+
writers,
|
|
92
|
+
...(expectedWriters ? { expectedWriters } : {}),
|
|
93
|
+
...(typeof raw.sessionFile === "string" && raw.sessionFile ? { sessionFile: raw.sessionFile } : {}),
|
|
94
|
+
...(typeof raw.revivalLeaseToken === "string" && raw.revivalLeaseToken ? { revivalLeaseToken: raw.revivalLeaseToken } : {}),
|
|
95
|
+
...(typeof raw.revivalLeaseReleaseAcknowledged === "boolean" ? { revivalLeaseReleaseAcknowledged: raw.revivalLeaseReleaseAcknowledged } : {}),
|
|
96
|
+
};
|
|
97
|
+
} catch (error) {
|
|
98
|
+
if ((error as NodeJS.ErrnoException).code === "ENOENT") return undefined;
|
|
99
|
+
throw error;
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
export function writeProcessTerminalCandidate(asyncDir: string, candidate: ProcessTerminalCandidate): void {
|
|
104
|
+
writePrivateAtomicJson(processTerminalCandidatePath(asyncDir), candidate);
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
export function markProcessTerminalCandidateLeaseRelease(asyncDir: string, token: string, acknowledged: boolean): void {
|
|
108
|
+
const candidate = readProcessTerminalCandidate(asyncDir);
|
|
109
|
+
if (!candidate || candidate.revivalLeaseToken !== token) return;
|
|
110
|
+
writeProcessTerminalCandidate(asyncDir, { ...candidate, revivalLeaseReleaseAcknowledged: acknowledged });
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
function unknownProof(runId: string, runnerProcessInstanceId: string, reason: ProcessTerminalReason, diagnostic?: string): ProcessTerminalV1 {
|
|
114
|
+
return { version: 1, state: "unknown", runId, runnerProcessInstanceId, reason, ...(diagnostic ? { diagnostic } : {}) };
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
function resumeDisposition(state: string | undefined, sessionFile: string | undefined): "resumable" | "non-resumable" | "unavailable" {
|
|
118
|
+
if (state === "stopped") return "non-resumable";
|
|
119
|
+
if (state !== "complete" && state !== "completed" && state !== "failed" && state !== "paused") return "unavailable";
|
|
120
|
+
return sessionFile && fs.existsSync(sessionFile) ? "resumable" : "unavailable";
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
function sessionProjection(candidate: ProcessTerminalCandidate, lease: ReturnType<typeof inspectSessionLease>): CanonicalSessionTerminalV1 | undefined {
|
|
124
|
+
if (!candidate.sessionFile || lease.state !== "free") return undefined;
|
|
125
|
+
if (candidate.revivalLeaseToken && candidate.revivalLeaseReleaseAcknowledged !== true) return undefined;
|
|
126
|
+
return {
|
|
127
|
+
canonicalSessionId: canonicalSessionId(candidate.sessionFile),
|
|
128
|
+
leaseDisposition: candidate.revivalLeaseToken ? "released" : "not-held",
|
|
129
|
+
freeAtObservation: true,
|
|
130
|
+
...(candidate.revivalLeaseToken ? { canonicalSessionLeaseReleased: true } : {}),
|
|
131
|
+
};
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
function validateProof(raw: unknown, asyncDir: string, fallback?: { runId?: string; runnerProcessInstanceId?: string }): raw is ProcessTerminalV1 {
|
|
135
|
+
if (!isRecord(raw) || raw.version !== 1 || !["pending", "observed", "unknown", "not-started"].includes(String(raw.state)) || typeof raw.runId !== "string" || !raw.runId || typeof raw.runnerProcessInstanceId !== "string" || !raw.runnerProcessInstanceId) {
|
|
136
|
+
throw new Error(`Invalid process-terminal proof in '${asyncDir}'.`);
|
|
137
|
+
}
|
|
138
|
+
if (fallback?.runId && raw.runId !== fallback.runId) throw new Error(`Process-terminal proof in '${asyncDir}' belongs to run '${raw.runId}', expected '${fallback.runId}'.`);
|
|
139
|
+
if (fallback?.runnerProcessInstanceId && raw.runnerProcessInstanceId !== fallback.runnerProcessInstanceId) throw new Error(`Process-terminal proof in '${asyncDir}' belongs to runner '${raw.runnerProcessInstanceId}', expected '${fallback.runnerProcessInstanceId}'.`);
|
|
140
|
+
if (raw.instances !== undefined && (!Array.isArray(raw.instances) || !raw.instances.every((entry) => validProcessInstance(entry)))) {
|
|
141
|
+
throw new Error(`Invalid process-terminal instances in '${asyncDir}'.`);
|
|
142
|
+
}
|
|
143
|
+
if (raw.state === "observed") {
|
|
144
|
+
if (typeof raw.observedAt !== "number" || !Number.isFinite(raw.observedAt)) throw new Error(`Observed process-terminal proof in '${asyncDir}' is missing observedAt.`);
|
|
145
|
+
if (!Array.isArray(raw.instances)) throw new Error(`Observed process-terminal proof in '${asyncDir}' is missing instances.`);
|
|
146
|
+
const runner = raw.instances.find((entry) => isRecord(entry) && entry.kind === "runner");
|
|
147
|
+
if (!validProcessInstance(runner, "runner") || runner.processInstanceId !== raw.runnerProcessInstanceId) throw new Error(`Observed process-terminal proof in '${asyncDir}' has no matching runner instance.`);
|
|
148
|
+
}
|
|
149
|
+
if (raw.resumeDisposition !== undefined && !["resumable", "non-resumable", "unavailable"].includes(String(raw.resumeDisposition))) throw new Error(`Invalid process-terminal resume disposition in '${asyncDir}'.`);
|
|
150
|
+
return true;
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
export function sanitizeProcessTerminal(value: unknown, fallback: { runId?: string; runnerProcessInstanceId?: string }, label = "status"): ProcessTerminalV1 | undefined {
|
|
154
|
+
if (value === undefined) return undefined;
|
|
155
|
+
try {
|
|
156
|
+
validateProof(value, label, fallback);
|
|
157
|
+
return value as ProcessTerminalV1;
|
|
158
|
+
} catch (error) {
|
|
159
|
+
return unknownProof(fallback.runId ?? label, fallback.runnerProcessInstanceId ?? "unknown", "proof-write-failed", errorMessage(error));
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
export function readProcessTerminal(asyncDir: string, fallback?: { runId?: string; runnerProcessInstanceId?: string }): ProcessTerminalV1 | undefined {
|
|
164
|
+
try {
|
|
165
|
+
const raw = JSON.parse(fs.readFileSync(processTerminalPath(asyncDir), "utf-8")) as unknown;
|
|
166
|
+
validateProof(raw, asyncDir, fallback);
|
|
167
|
+
return raw as ProcessTerminalV1;
|
|
168
|
+
} catch (error) {
|
|
169
|
+
if ((error as NodeJS.ErrnoException).code === "ENOENT") return undefined;
|
|
170
|
+
return unknownProof(fallback?.runId ?? path.basename(asyncDir), fallback?.runnerProcessInstanceId ?? "unknown", "proof-write-failed", errorMessage(error));
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
function stepProcessTerminalProof(
|
|
175
|
+
proof: ProcessTerminalV1,
|
|
176
|
+
childIndex: number,
|
|
177
|
+
state: ProcessTerminalV1["state"],
|
|
178
|
+
records: ProcessInstanceExitV1[],
|
|
179
|
+
resumeDispositionValue: ProcessTerminalV1["resumeDisposition"],
|
|
180
|
+
): ProcessTerminalV1 {
|
|
181
|
+
const base = {
|
|
182
|
+
version: 1 as const,
|
|
183
|
+
runId: proof.runId,
|
|
184
|
+
childIndex,
|
|
185
|
+
runnerProcessInstanceId: proof.runnerProcessInstanceId,
|
|
186
|
+
...(resumeDispositionValue ? { resumeDisposition: resumeDispositionValue } : {}),
|
|
187
|
+
};
|
|
188
|
+
if (state === "observed") {
|
|
189
|
+
return { ...base, state, observedAt: proof.state === "observed" ? proof.observedAt : Date.now(), instances: records };
|
|
190
|
+
}
|
|
191
|
+
if (state === "unknown") {
|
|
192
|
+
return { ...base, state, reason: proof.state === "unknown" ? proof.reason : "writer-close-unverified" };
|
|
193
|
+
}
|
|
194
|
+
return { ...base, state };
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
function overlayStatus(asyncDir: string, proof: ProcessTerminalV1, candidate?: ProcessTerminalCandidate): void {
|
|
198
|
+
const statusPath = path.join(asyncDir, "status.json");
|
|
199
|
+
try {
|
|
200
|
+
const status = JSON.parse(fs.readFileSync(statusPath, "utf-8")) as AsyncStatus;
|
|
201
|
+
status.processTerminal = proof;
|
|
202
|
+
if (status.steps) {
|
|
203
|
+
for (const [index, step] of status.steps.entries()) {
|
|
204
|
+
const records = candidate?.writers[String(index)] ?? [];
|
|
205
|
+
const expected = candidate?.expectedWriters?.[String(index)] ?? (records.length > 0 ? records.length : 0);
|
|
206
|
+
const stepState = expected === 0 ? "not-started" : proof.state === "observed" && records.length === expected ? "observed" : proof.state === "pending" ? "pending" : "unknown";
|
|
207
|
+
step.processTerminal = stepProcessTerminalProof(proof, index, stepState, records, resumeDisposition(step.status, step.sessionFile ?? candidate?.sessionFile));
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
writeAtomicJson(statusPath, status);
|
|
211
|
+
} catch {
|
|
212
|
+
// The proof sidecar remains authoritative when terminal status is unavailable.
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
export function finalizeProcessTerminal(
|
|
217
|
+
asyncDir: string,
|
|
218
|
+
runId: string,
|
|
219
|
+
runnerClose: RunnerCloseObservation,
|
|
220
|
+
): ProcessTerminalV1 {
|
|
221
|
+
const existing = readProcessTerminal(asyncDir, { runId, runnerProcessInstanceId: runnerClose.processInstanceId });
|
|
222
|
+
if (existing && fs.existsSync(processTerminalPath(asyncDir))) {
|
|
223
|
+
if (existing.state === "observed" && existing.runId === runId && existing.runnerProcessInstanceId === runnerClose.processInstanceId) return existing;
|
|
224
|
+
if (existing.state === "unknown") return existing;
|
|
225
|
+
}
|
|
226
|
+
let proof: ProcessTerminalV1;
|
|
227
|
+
let candidateForOverlay: ProcessTerminalCandidate | undefined;
|
|
228
|
+
try {
|
|
229
|
+
const candidate = readProcessTerminalCandidate(asyncDir);
|
|
230
|
+
candidateForOverlay = candidate;
|
|
231
|
+
if (!candidate) proof = unknownProof(runId, runnerClose.processInstanceId, "runner-candidate-missing");
|
|
232
|
+
else if (candidate.runId !== runId || candidate.runnerProcessInstanceId !== runnerClose.processInstanceId) proof = unknownProof(runId, runnerClose.processInstanceId, "runner-instance-mismatch");
|
|
233
|
+
else {
|
|
234
|
+
const allWriters = Object.values(candidate.writers).flat();
|
|
235
|
+
const status = (() => {
|
|
236
|
+
try { return JSON.parse(fs.readFileSync(path.join(asyncDir, "status.json"), "utf-8")) as AsyncStatus; } catch { return undefined; }
|
|
237
|
+
})();
|
|
238
|
+
const session = candidate.sessionFile ? inspectSessionLease(candidate.sessionFile) : undefined;
|
|
239
|
+
const writerEntries = Object.entries(candidate.writers);
|
|
240
|
+
const expectedWriters = candidate.expectedWriters ?? Object.fromEntries(writerEntries.map(([index, records]) => [index, records.length]));
|
|
241
|
+
const expectedEntries = Object.entries(expectedWriters);
|
|
242
|
+
const expectedIndexes = new Set(expectedEntries.map(([index]) => index));
|
|
243
|
+
const writerIndexes = new Set(writerEntries.map(([index]) => index));
|
|
244
|
+
const inconsistentWriters = writerEntries.some(([index, records]) => !expectedIndexes.has(index) || records.length !== expectedWriters[index])
|
|
245
|
+
|| expectedEntries.some(([index, expected]) => !writerIndexes.has(index) && expected !== 0);
|
|
246
|
+
if (session && session.state !== "free") {
|
|
247
|
+
proof = unknownProof(runId, runnerClose.processInstanceId, session.state === "owned" ? "canonical-session-lease-active" : "canonical-session-unavailable");
|
|
248
|
+
} else if (candidate.revivalLeaseToken && candidate.revivalLeaseReleaseAcknowledged !== true) {
|
|
249
|
+
proof = unknownProof(runId, runnerClose.processInstanceId, "canonical-session-release-unverified");
|
|
250
|
+
} else if (inconsistentWriters || (allWriters.length === 0 && expectedEntries.length === 0)) {
|
|
251
|
+
proof = unknownProof(runId, runnerClose.processInstanceId, "writer-close-unverified");
|
|
252
|
+
} else {
|
|
253
|
+
const runner: ProcessInstanceExitV1 = { kind: "runner", ...runnerClose };
|
|
254
|
+
const canonicalSession = session && sessionProjection(candidate, session);
|
|
255
|
+
proof = {
|
|
256
|
+
version: 1,
|
|
257
|
+
state: "observed",
|
|
258
|
+
runId,
|
|
259
|
+
runnerProcessInstanceId: runnerClose.processInstanceId,
|
|
260
|
+
observedAt: runnerClose.closeObservedAt,
|
|
261
|
+
instances: [runner, ...allWriters],
|
|
262
|
+
resumeDisposition: resumeDisposition(status?.state, candidate.sessionFile ?? status?.sessionFile),
|
|
263
|
+
...(canonicalSession ? { canonicalSession } : {}),
|
|
264
|
+
};
|
|
265
|
+
}
|
|
266
|
+
}
|
|
267
|
+
} catch (error) {
|
|
268
|
+
proof = unknownProof(runId, runnerClose.processInstanceId, "proof-write-failed", errorMessage(error));
|
|
269
|
+
}
|
|
270
|
+
let durable = false;
|
|
271
|
+
try {
|
|
272
|
+
writeAtomicJson(processTerminalPath(asyncDir), proof);
|
|
273
|
+
durable = true;
|
|
274
|
+
overlayStatus(asyncDir, proof, candidateForOverlay);
|
|
275
|
+
fs.appendFileSync(path.join(asyncDir, "events.jsonl"), `${JSON.stringify({ type: "subagent.run.process_terminal", lifecycleArtifactVersion: SUBAGENT_LIFECYCLE_ARTIFACT_VERSION, ts: Date.now(), runId, processTerminal: proof })}\n`, "utf-8");
|
|
276
|
+
} catch {
|
|
277
|
+
// Do not emit a process-terminal event when the proof sidecar was not durable.
|
|
278
|
+
}
|
|
279
|
+
return durable ? proof : unknownProof(runId, runnerClose.processInstanceId, "proof-write-failed", "Failed to persist process-terminal proof.");
|
|
280
|
+
}
|