@xzzpig/pi-subagents 0.13.0 → 0.15.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 +243 -0
- package/README.md +6 -5
- package/agents/evidence-auditor.md +34 -0
- package/agents/researcher.md +23 -13
- package/agents/reviewer.md +3 -2
- package/docs/agents.md +56 -15
- package/docs/configuration.md +93 -15
- package/docs/extension-api.md +132 -19
- package/docs/missions.md +10 -2
- package/docs/models.md +11 -22
- package/docs/observability.md +67 -11
- package/docs/standalone-background.md +59 -0
- package/docs/tool-reference.md +42 -23
- package/docs/watchdog.md +39 -10
- package/docs/workflows.md +58 -19
- package/index.ts +5 -2
- package/inspector-runner.mjs +2 -2
- package/node_modules/@xzzpig/pi-components/CHANGELOG.md +19 -0
- package/node_modules/@xzzpig/pi-components/README.md +28 -0
- package/node_modules/@xzzpig/pi-components/dist/src/transcript.d.ts +46 -4
- package/node_modules/@xzzpig/pi-components/dist/src/transcript.js +65 -17
- package/node_modules/@xzzpig/pi-components/package.json +1 -1
- package/node_modules/@xzzpig/pi-components/src/transcript.ts +107 -14
- package/package.json +10 -5
- package/prompts/parallel-review.md +1 -1
- package/runner-peer-loader.mjs +24 -0
- package/runner-peer-preload.mjs +36 -0
- package/skills/pi-subagents/SKILL.md +34 -22
- package/skills/pi-subagents/references/constraints-and-recipes.md +3 -2
- package/skills/pi-subagents/references/execution-controls.md +27 -8
- package/skills/pi-subagents/references/management-authoring-rpc.md +2 -2
- package/skills/pi-subagents/references/multi-lane-orchestration.md +3 -1
- package/skills/pi-subagents/references/prompting-and-roles.md +17 -13
- package/skills/pi-subagents/references/review-and-validation.md +3 -3
- package/src/agents/advertised-agent-prompt.ts +94 -0
- package/src/agents/agent-management.ts +71 -59
- package/src/agents/agent-serializer.ts +6 -3
- package/src/agents/agents.ts +198 -72
- package/src/agents/builtin-names.ts +1 -0
- package/src/agents/chain-serializer.ts +5 -0
- package/src/agents/runtime-agent-registry.ts +7 -6
- package/src/api/delegation.ts +4 -0
- package/src/api/preflight.ts +110 -71
- package/src/api/required-child-extensions.ts +6 -0
- package/src/api/shared-types.ts +3 -1
- package/src/api/workflow-resources.ts +6 -0
- package/src/extension/config.ts +14 -37
- package/src/extension/fanout-child.ts +68 -5
- package/src/extension/herdr-pi-bridge.ts +164 -0
- package/src/extension/index.ts +141 -51
- package/src/extension/public-execution.ts +7 -6
- package/src/extension/rpc.ts +8 -21
- package/src/extension/schemas.ts +86 -84
- package/src/extension/tool-description.ts +32 -79
- package/src/inspectors/actions.ts +148 -0
- package/src/inspectors/ghostty/actions.ts +74 -0
- package/src/inspectors/ghostty/plugin.ts +17 -0
- package/src/inspectors/herdr/actions.ts +99 -179
- package/src/inspectors/herdr/plugin.ts +20 -0
- package/src/inspectors/herdr/project-panes.ts +4 -1
- package/src/inspectors/{herdr/inspector-runner.ts → inspector-runner.ts} +12 -12
- package/src/inspectors/plugins.ts +8 -0
- package/src/inspectors/{herdr/session-roots-codec.ts → session-roots-codec.ts} +3 -14
- package/src/inspectors/types.ts +51 -0
- package/src/integrations/pi-web-session-liveness.ts +73 -0
- package/src/intercom/intercom-bridge.ts +50 -8
- package/src/intercom/native-supervisor-channel.ts +142 -115
- package/src/intercom/supervisor-ui.ts +3 -2
- package/src/missions/workflow-state.ts +37 -16
- package/src/policy/authority.ts +4 -0
- package/src/profiles/profiles.ts +12 -6
- package/src/runs/background/active-async-capacity.ts +22 -18
- package/src/runs/background/active-run-index.ts +17 -1
- package/src/runs/background/async-execution.ts +359 -176
- package/src/runs/background/async-job-tracker.ts +41 -7
- package/src/runs/background/async-resume.ts +19 -12
- package/src/runs/background/async-retention.ts +20 -0
- package/src/runs/background/async-status-snapshot.ts +10 -12
- package/src/runs/background/async-status.ts +32 -13
- package/src/runs/background/auto-drain.ts +59 -35
- package/src/runs/background/binary-bootstrap.ts +38 -0
- package/src/runs/background/chain-append.ts +1 -1
- package/src/runs/background/chain-root-attachment.ts +22 -33
- package/src/runs/background/control-channel.ts +78 -44
- package/src/runs/background/fleet-view.ts +30 -2
- package/src/runs/background/notify.ts +193 -19
- package/src/runs/background/owned-process-tree.ts +35 -8
- package/src/runs/background/process-terminal.ts +23 -23
- package/src/runs/background/result-files.ts +8 -4
- package/src/runs/background/result-watcher.ts +19 -2
- package/src/runs/background/retained-nested-route-tracker.ts +96 -0
- package/src/runs/background/run-child-session.ts +118 -41
- package/src/runs/background/run-status.ts +78 -5
- package/src/runs/background/runner-aliases.ts +22 -5
- package/src/runs/background/runner-child-launch.ts +93 -0
- package/src/runs/background/runner-child-sessions.ts +5 -4
- package/src/runs/background/runner-http-dispatcher.ts +119 -0
- package/src/runs/background/scheduled-runs.ts +51 -18
- package/src/runs/background/stale-run-reconciler.ts +38 -12
- package/src/runs/background/steering.ts +20 -2
- package/src/runs/background/subagent-runner.ts +766 -432
- package/src/runs/background/subagent-wait.ts +179 -28
- package/src/runs/background/wait-completions.ts +79 -27
- package/src/runs/background/wait-subscriptions.ts +9 -3
- package/src/runs/background/wait-tool.ts +5 -3
- package/src/runs/foreground/async-steering-action.ts +37 -7
- package/src/runs/foreground/async-stop-action.ts +93 -3
- package/src/runs/foreground/execution.ts +174 -194
- package/src/runs/foreground/foreground-history.ts +5 -2
- package/src/runs/foreground/prompt-audit.ts +12 -6
- package/src/runs/foreground/subagent-executor.ts +896 -397
- package/src/runs/foreground/workflow-detach-reconcile.ts +10 -5
- package/src/runs/foreground/workflow-foreground-steering.ts +57 -2
- package/src/runs/shared/acceptance.ts +54 -14
- package/src/runs/shared/agent-contract.ts +1 -1
- package/src/runs/shared/async-status-projection.ts +172 -78
- package/src/runs/shared/capability-ceiling.ts +2 -0
- package/src/runs/shared/child-hooks.ts +167 -3
- package/src/runs/shared/child-launch-plan.ts +15 -3
- package/src/runs/shared/child-launch.ts +44 -16
- package/src/runs/shared/child-lifecycle.ts +6 -3
- package/src/runs/shared/child-runtime-config.ts +8 -1
- package/src/runs/shared/child-session.ts +130 -24
- package/src/runs/shared/child-tool-plan.ts +145 -14
- package/src/runs/shared/completion-evidence.ts +2 -2
- package/src/runs/shared/completion-guard.ts +6 -3
- package/src/runs/shared/dynamic-fanout.ts +2 -2
- package/src/runs/shared/effective-system-prompt.ts +33 -0
- package/src/runs/shared/external-cli-contract.ts +11 -1
- package/src/runs/shared/external-cli-preflight.ts +6 -2
- package/src/runs/shared/external-cli-runner.ts +9 -7
- package/src/runs/shared/herdr-connection.ts +134 -0
- package/src/runs/shared/herdr-external-adapters.ts +169 -0
- package/src/runs/shared/herdr-machine.ts +279 -0
- package/src/runs/shared/herdr-pi-protocol.ts +59 -0
- package/src/runs/shared/herdr-placed-run.ts +263 -0
- package/src/runs/shared/host-step-status.ts +11 -11
- package/src/runs/shared/llm-intent-arbiter.ts +40 -21
- package/src/runs/shared/model-resolution-diagnostic.ts +76 -0
- package/src/runs/shared/{model-fallback.ts → model-resolution.ts} +34 -218
- package/src/runs/shared/model-scope.ts +1 -1
- package/src/runs/shared/nested-events.ts +19 -10
- package/src/runs/shared/orca-progress-tabs.ts +7 -1
- package/src/runs/shared/parallel-handoff.ts +57 -12
- package/src/runs/shared/parallel-utils.ts +10 -4
- package/src/runs/shared/pi-spawn.ts +10 -0
- package/src/runs/shared/readonly-drain-observation.ts +42 -0
- package/src/runs/shared/run-fanout-budget.ts +8 -8
- package/src/runs/shared/runtime-acknowledged-extensions.ts +3 -3
- package/src/runs/shared/subagent-prompt-runtime.ts +23 -5
- package/src/runs/shared/task-intent.ts +46 -13
- package/src/runs/shared/workflow-async-child-guidance.ts +18 -0
- package/src/runs/shared/worktree-cleanup-plan.ts +6 -3
- package/src/runs/shared/worktree-setup-command.ts +213 -0
- package/src/runs/shared/worktree.ts +437 -214
- package/src/shared/child-cache-retention.ts +43 -0
- package/src/shared/fork-context.ts +15 -72
- package/src/shared/launch-contract.ts +70 -8
- package/src/shared/model-response-aliases.ts +13 -0
- package/src/shared/opencode-session-headers.ts +30 -0
- package/src/shared/pruned-fork.ts +1 -1
- package/src/shared/required-child-extensions.ts +81 -0
- package/src/shared/settings.ts +5 -2
- package/src/shared/shortcuts.ts +0 -4
- package/src/shared/types.ts +164 -90
- package/src/shared/utils.ts +10 -2
- package/src/shared/watch-strategy.ts +2 -0
- package/src/shared/workflow-child-permit.ts +18 -13
- package/src/slash/delegation-adapters.ts +3 -1
- package/src/slash/delegation-request.ts +14 -0
- package/src/slash/slash-commands.ts +2 -7
- package/src/slash/subagents-admin.ts +31 -14
- package/src/tui/fleet-native-transcript.ts +50 -6
- package/src/tui/fleet-status.ts +165 -20
- package/src/tui/fleet.ts +52 -21
- package/src/tui/render.ts +210 -50
- package/src/watchdog/child-status.ts +28 -28
- package/src/watchdog/lsp-diagnostics.ts +1 -1
- package/src/watchdog/model-selection.ts +21 -1
- package/src/watchdog/permission-arbiter.ts +5 -2
- package/src/watchdog/register-child.ts +10 -2
- package/src/watchdog/register-main.ts +39 -35
- package/src/watchdog/render.ts +1 -1
- package/src/watchdog/review.ts +122 -74
- package/src/watchdog/rules.ts +1 -1
- package/src/watchdog/runtime.ts +100 -27
- package/src/watchdog/scope.ts +1 -1
- package/src/watchdog/settings.ts +3 -0
- package/src/watchdog/tool-actions.ts +13 -12
- package/src/watchdog/turn-delta.ts +23 -0
- package/src/watchdog/types.ts +5 -3
- package/src/watchdog/warning-format.ts +1 -1
- package/src/workflows/chat-progress.ts +3 -3
- package/src/workflows/scripted-workflow.ts +349 -26
- package/src/workflows/workflow-checklist.ts +17 -20
- package/src/workflows/workflow-child-summary.ts +57 -8
- package/src/workflows/workflow-preflight.ts +19 -19
- package/src/workflows/workflow-receipt.ts +24 -6
- package/src/workflows/workflow-resources.ts +108 -22
- package/src/workflows/workflow-settlement.ts +3 -0
- package/src/runs/shared/model-exclusions.ts +0 -373
- /package/src/inspectors/{herdr/shell-command.ts → shell-command.ts} +0 -0
|
@@ -2,7 +2,7 @@ import { randomUUID } from "node:crypto";
|
|
|
2
2
|
import * as fs from "node:fs";
|
|
3
3
|
import * as path from "node:path";
|
|
4
4
|
import type { AgentToolResult } from "@earendil-works/pi-agent-core";
|
|
5
|
-
import type { ExtensionAPI,
|
|
5
|
+
import type { ExtensionAPI, ToolDefinition } from "@earendil-works/pi-coding-agent";
|
|
6
6
|
import { Type } from "typebox";
|
|
7
7
|
import type { ChildSupervisorMetadata } from "../runs/shared/child-runtime-config.ts";
|
|
8
8
|
import { INTERCOM_DETACH_REQUEST_EVENT, POLL_INTERVAL_MS, TEMP_ROOT_DIR, type ControlEvent, type IntercomEventBus, type SubagentState } from "../shared/types.ts";
|
|
@@ -74,7 +74,7 @@ interface ContactSupervisorParams {
|
|
|
74
74
|
}
|
|
75
75
|
|
|
76
76
|
interface IntercomParams {
|
|
77
|
-
action: "list" | "
|
|
77
|
+
action: "list" | "pending" | "status" | "reply";
|
|
78
78
|
to?: string;
|
|
79
79
|
message?: string;
|
|
80
80
|
replyTo?: string;
|
|
@@ -83,6 +83,10 @@ interface IntercomParams {
|
|
|
83
83
|
type SupervisorWatch = (filename: fs.PathLike, listener: fs.WatchListener<string>) => fs.FSWatcher;
|
|
84
84
|
|
|
85
85
|
interface NativeSupervisorChannelDeps {
|
|
86
|
+
/** Owned live/final-drain mailboxes. Only a completed poll retires the snapshot, never a demand probe. */
|
|
87
|
+
getChannelDirs?: () => { dirs: string[]; retire?: () => void };
|
|
88
|
+
/** Retained scheduled states for the current runtime owner, never foreign owners. */
|
|
89
|
+
getCurrentOwnerStates?: () => Iterable<SubagentState>;
|
|
86
90
|
platform?: NodeJS.Platform;
|
|
87
91
|
watch?: SupervisorWatch;
|
|
88
92
|
timers?: Pick<typeof globalThis, "setInterval" | "clearInterval" | "setImmediate" | "clearImmediate">;
|
|
@@ -95,7 +99,7 @@ const ContactSupervisorParamsSchema = Type.Object({
|
|
|
95
99
|
}, { additionalProperties: false });
|
|
96
100
|
|
|
97
101
|
const IntercomParamsSchema = Type.Object({
|
|
98
|
-
action: Type.String({ enum: ["list", "
|
|
102
|
+
action: Type.String({ enum: ["list", "pending", "status", "reply"] }),
|
|
99
103
|
to: Type.Optional(Type.String()),
|
|
100
104
|
message: Type.Optional(Type.String()),
|
|
101
105
|
replyTo: Type.Optional(Type.String()),
|
|
@@ -128,34 +132,6 @@ function reasonHeading(reason: SupervisorReason): string {
|
|
|
128
132
|
return "Subagent needs a supervisor decision.";
|
|
129
133
|
}
|
|
130
134
|
|
|
131
|
-
function formatChildMessage(input: {
|
|
132
|
-
reason: SupervisorReason;
|
|
133
|
-
message?: string;
|
|
134
|
-
interview?: unknown;
|
|
135
|
-
runId: string;
|
|
136
|
-
agent: string;
|
|
137
|
-
childIndex: number;
|
|
138
|
-
childTarget?: string;
|
|
139
|
-
}): string {
|
|
140
|
-
const lines = [
|
|
141
|
-
reasonHeading(input.reason),
|
|
142
|
-
`Run: ${input.runId}`,
|
|
143
|
-
`Agent: ${input.agent}`,
|
|
144
|
-
`Child index: ${input.childIndex}`,
|
|
145
|
-
];
|
|
146
|
-
if (input.childTarget) lines.push(`Child intercom target: ${input.childTarget}`);
|
|
147
|
-
lines.push("");
|
|
148
|
-
if (input.message?.trim()) lines.push(input.message.trim());
|
|
149
|
-
if (input.reason === "interview_request") {
|
|
150
|
-
lines.push(
|
|
151
|
-
"",
|
|
152
|
-
"Structured response requested. Reply with JSON, optionally fenced in ```json, matching the requested interview shape.",
|
|
153
|
-
);
|
|
154
|
-
if (input.interview !== undefined) lines.push(JSON.stringify(input.interview, null, "\t"));
|
|
155
|
-
}
|
|
156
|
-
return lines.join("\n").trimEnd();
|
|
157
|
-
}
|
|
158
|
-
|
|
159
135
|
function parseStructuredReply(message: string): { value?: unknown; error?: string } {
|
|
160
136
|
const trimmed = message.trim();
|
|
161
137
|
const fenced = trimmed.match(/^```(?:json)?\s*([\s\S]*?)\s*```$/i)?.[1]?.trim();
|
|
@@ -210,8 +186,8 @@ async function waitForReply(channelDir: string, requestId: string, deadline: num
|
|
|
210
186
|
}
|
|
211
187
|
|
|
212
188
|
async function sendSupervisorRequest(params: ContactSupervisorParams, metadata: ChildSupervisorMetadata, signal?: AbortSignal, toolCallId?: string): Promise<AgentToolResult<Record<string, unknown>>> {
|
|
213
|
-
if (
|
|
214
|
-
throw new Error("message is required for supervisor decisions.");
|
|
189
|
+
if (!params.message?.trim() && params.reason !== "interview_request") {
|
|
190
|
+
throw new Error("message is required for supervisor decisions and progress updates.");
|
|
215
191
|
}
|
|
216
192
|
ensureSupervisorChannelDir(metadata.channelDir);
|
|
217
193
|
const requestId = randomUUID();
|
|
@@ -219,7 +195,7 @@ async function sendSupervisorRequest(params: ContactSupervisorParams, metadata:
|
|
|
219
195
|
const createdAt = Date.now();
|
|
220
196
|
const replyDeadline = createdAt + askTimeoutMs();
|
|
221
197
|
const expiresAt = expectsReply ? replyDeadline : undefined;
|
|
222
|
-
const message =
|
|
198
|
+
const message = params.message?.trim() ?? "";
|
|
223
199
|
const requestToolCallId = typeof toolCallId === "string" && toolCallId.length > 0 ? toolCallId : undefined;
|
|
224
200
|
const request: SupervisorRequest = {
|
|
225
201
|
type: "subagent.supervisor.request",
|
|
@@ -299,7 +275,7 @@ function parseRequestFile(file: string, channelDir: string): PendingSupervisorRe
|
|
|
299
275
|
if (parsed.type !== "subagent.supervisor.request") return undefined;
|
|
300
276
|
if (typeof parsed.id !== "string" || !parsed.id) return undefined;
|
|
301
277
|
if (parsed.reason !== "need_decision" && parsed.reason !== "interview_request" && parsed.reason !== "progress_update") return undefined;
|
|
302
|
-
if (typeof parsed.message !== "string" || !parsed.message) return undefined;
|
|
278
|
+
if (typeof parsed.message !== "string" || (!parsed.message.trim() && parsed.reason !== "interview_request")) return undefined;
|
|
303
279
|
if (typeof parsed.runId !== "string" || typeof parsed.agent !== "string" || typeof parsed.childIndex !== "number") return undefined;
|
|
304
280
|
return {
|
|
305
281
|
...parsed as SupervisorRequest,
|
|
@@ -312,18 +288,18 @@ function parseRequestFile(file: string, channelDir: string): PendingSupervisorRe
|
|
|
312
288
|
}
|
|
313
289
|
}
|
|
314
290
|
|
|
315
|
-
function listRequestFiles(): Array<{ channelDir: string; file: string }> {
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
291
|
+
function listRequestFiles(channelDirs?: string[]): Array<{ channelDir: string; file: string }> {
|
|
292
|
+
if (!channelDirs) {
|
|
293
|
+
try {
|
|
294
|
+
channelDirs = fs.readdirSync(SUPERVISOR_CHANNEL_ROOT, { withFileTypes: true })
|
|
295
|
+
.filter(entry => entry.isDirectory()).map(entry => path.join(SUPERVISOR_CHANNEL_ROOT, entry.name));
|
|
296
|
+
} catch (error) {
|
|
297
|
+
if ((error as NodeJS.ErrnoException).code === "ENOENT") return [];
|
|
298
|
+
throw error;
|
|
299
|
+
}
|
|
322
300
|
}
|
|
323
301
|
const files: Array<{ channelDir: string; file: string }> = [];
|
|
324
|
-
for (const
|
|
325
|
-
if (!entry.isDirectory()) continue;
|
|
326
|
-
const channelDir = path.join(SUPERVISOR_CHANNEL_ROOT, entry.name);
|
|
302
|
+
for (const channelDir of channelDirs) {
|
|
327
303
|
const requestsDir = path.join(channelDir, REQUESTS_DIR);
|
|
328
304
|
let requestEntries: fs.Dirent[];
|
|
329
305
|
try {
|
|
@@ -409,18 +385,8 @@ function cleanupStaleEmptySupervisorChannels(nowMs = Date.now()): number {
|
|
|
409
385
|
return removed;
|
|
410
386
|
}
|
|
411
387
|
|
|
412
|
-
function
|
|
413
|
-
|
|
414
|
-
const sessionId = ctx.sessionManager.getSessionId();
|
|
415
|
-
if (sessionId) return sessionId;
|
|
416
|
-
} catch {
|
|
417
|
-
// Fall through to the last known identity.
|
|
418
|
-
}
|
|
419
|
-
return state.currentSessionId ?? undefined;
|
|
420
|
-
}
|
|
421
|
-
|
|
422
|
-
function requestMatchesContext(request: SupervisorRequest, state: Pick<SubagentState, "currentSessionId">, ctx: ExtensionContext): boolean {
|
|
423
|
-
const currentSessionId = currentContextSessionId(state, ctx);
|
|
388
|
+
function requestMatchesOwner(request: SupervisorRequest, state: Pick<SubagentState, "supervisorOwnerSessionId">): boolean {
|
|
389
|
+
const currentSessionId = state.supervisorOwnerSessionId;
|
|
424
390
|
return Boolean(currentSessionId && request.orchestratorSessionId === currentSessionId);
|
|
425
391
|
}
|
|
426
392
|
|
|
@@ -490,12 +456,12 @@ function requestRunInactive(request: SupervisorRequest, state: SubagentState): b
|
|
|
490
456
|
return stepStatus === "complete" || stepStatus === "completed" || stepStatus === "failed" || stepStatus === "paused";
|
|
491
457
|
}
|
|
492
458
|
|
|
493
|
-
function requestLifecycle(request: PendingSupervisorRequest, state: SubagentState,
|
|
494
|
-
if (
|
|
459
|
+
function requestLifecycle(request: PendingSupervisorRequest, state: SubagentState, now: number, runState: SubagentState): SupervisorRequestLifecycle {
|
|
460
|
+
if (!requestMatchesOwner(request, state)) return "wrong-session";
|
|
495
461
|
if (!fs.existsSync(request.requestFile)) return "missing";
|
|
496
462
|
if (request.expectsReply && fs.existsSync(replyPath(request.channelDir, request.id))) return "resolved";
|
|
497
463
|
if (request.expectsReply && now > requestExpiresAt(request, now)) return "expired";
|
|
498
|
-
if (request.expectsReply && requestRunInactive(request,
|
|
464
|
+
if (request.expectsReply && requestRunInactive(request, runState)) return "inactive";
|
|
499
465
|
return "pending";
|
|
500
466
|
}
|
|
501
467
|
|
|
@@ -503,10 +469,10 @@ function cleanupRequestLifecycle(request: PendingSupervisorRequest, lifecycle: S
|
|
|
503
469
|
if (lifecycle === "resolved" || lifecycle === "expired" || lifecycle === "inactive") removeRequestFile(request.requestFile);
|
|
504
470
|
}
|
|
505
471
|
|
|
506
|
-
function refreshPendingRequests(pending: Map<string, PendingSupervisorRequest>, state: SubagentState,
|
|
472
|
+
function refreshPendingRequests(pending: Map<string, PendingSupervisorRequest>, state: SubagentState, onLifecycle: SupervisorRequestLifecycleObserver, runState: (request: SupervisorRequest) => SubagentState): void {
|
|
507
473
|
const now = Date.now();
|
|
508
474
|
for (const request of pending.values()) {
|
|
509
|
-
const lifecycle = requestLifecycle(request, state,
|
|
475
|
+
const lifecycle = requestLifecycle(request, state, now, runState(request));
|
|
510
476
|
if (lifecycle === "pending") continue;
|
|
511
477
|
pending.delete(request.id);
|
|
512
478
|
onLifecycle(request, lifecycle);
|
|
@@ -520,11 +486,24 @@ function formatPendingLine(request: PendingSupervisorRequest): string {
|
|
|
520
486
|
}
|
|
521
487
|
|
|
522
488
|
function requestVisibleText(request: PendingSupervisorRequest): string {
|
|
523
|
-
const lines = [
|
|
524
|
-
|
|
525
|
-
|
|
489
|
+
const lines = [
|
|
490
|
+
reasonHeading(request.reason),
|
|
491
|
+
`Run: ${request.runId}`,
|
|
492
|
+
`Agent: ${request.agent}`,
|
|
493
|
+
`Child index: ${request.childIndex}`,
|
|
494
|
+
];
|
|
495
|
+
lines.push("");
|
|
496
|
+
if (request.message) lines.push(request.message);
|
|
497
|
+
if (request.reason === "interview_request") {
|
|
498
|
+
lines.push(
|
|
499
|
+
"",
|
|
500
|
+
"Structured response requested. Reply with JSON, optionally fenced in ```json, matching the requested interview shape.",
|
|
501
|
+
);
|
|
502
|
+
if (request.interview !== undefined) lines.push(JSON.stringify(request.interview, null, "\t"));
|
|
526
503
|
}
|
|
527
|
-
|
|
504
|
+
if (request.expectsReply) lines.push("", `Reply with: ${supervisorReplyHint(request.id)}`);
|
|
505
|
+
lines.push("", `Live guidance: subagent({ action: "steer", id: ${JSON.stringify(request.runId)}, index: ${request.childIndex}, message: "..." })${request.expectsReply ? " (Reply to the pending request first.)" : ""}`);
|
|
506
|
+
return lines.join("\n").trimEnd();
|
|
528
507
|
}
|
|
529
508
|
|
|
530
509
|
function writeReply(request: PendingSupervisorRequest, message: string): SupervisorReply {
|
|
@@ -578,6 +557,7 @@ function resolvePendingRequest(pending: Map<string, PendingSupervisorRequest>, p
|
|
|
578
557
|
);
|
|
579
558
|
if (matches.length === 1) return matches[0]!;
|
|
580
559
|
if (matches.length > 1) throw new Error(`Multiple pending supervisor requests match '${params.to}'. Use replyTo.`);
|
|
560
|
+
throw new Error(`No pending supervisor request matches '${params.to}'. Use replyTo.`);
|
|
581
561
|
}
|
|
582
562
|
if (requests.length === 1) return requests[0]!;
|
|
583
563
|
if (requests.length === 0) throw new Error("No pending supervisor requests need a reply.");
|
|
@@ -595,14 +575,16 @@ function publicPendingRequests(pending: Map<string, PendingSupervisorRequest>):
|
|
|
595
575
|
}));
|
|
596
576
|
}
|
|
597
577
|
|
|
598
|
-
function buildParentSupervisorTool(pi: ExtensionAPI, pending: Map<string, PendingSupervisorRequest>, state: SubagentState, onLifecycle: SupervisorRequestLifecycleObserver): ToolDefinition<typeof IntercomParamsSchema, Record<string, unknown>> {
|
|
578
|
+
function buildParentSupervisorTool(pi: ExtensionAPI, pending: Map<string, PendingSupervisorRequest>, state: SubagentState, onLifecycle: SupervisorRequestLifecycleObserver, discover: () => void, runState: (request: SupervisorRequest) => SubagentState): ToolDefinition<typeof IntercomParamsSchema, Record<string, unknown>> {
|
|
599
579
|
return {
|
|
600
580
|
name: NATIVE_SUPERVISOR_TOOL_NAME,
|
|
601
581
|
label: "Subagent Supervisor",
|
|
602
582
|
description: "Native pi-subagents supervisor channel. Use reply/pending/status to answer child subagent requests without overriding pi-intercom.",
|
|
603
583
|
parameters: IntercomParamsSchema,
|
|
604
584
|
async execute(_id, params) {
|
|
605
|
-
|
|
585
|
+
// Discover new request files even when demand-gated polling is idle.
|
|
586
|
+
discover();
|
|
587
|
+
refreshPendingRequests(pending, state, onLifecycle, runState);
|
|
606
588
|
const input = params as IntercomParams;
|
|
607
589
|
if (input.action === "status") {
|
|
608
590
|
return { content: [{ type: "text", text: `Native supervisor channel active. Pending replies: ${pending.size}.` }], details: { active: true, pending: pending.size, root: SUPERVISOR_CHANNEL_ROOT } };
|
|
@@ -620,23 +602,29 @@ function buildParentSupervisorTool(pi: ExtensionAPI, pending: Map<string, Pendin
|
|
|
620
602
|
clearForegroundSupervisorAttention(request, pending, state);
|
|
621
603
|
return { content: [{ type: "text", text: `Replied to supervisor request ${request.id}.` }], details: { replyTo: request.id, runId: request.runId, agent: request.agent } };
|
|
622
604
|
}
|
|
623
|
-
if (input.action === "send" || input.action === "ask") {
|
|
624
|
-
throw new Error("The native subagent supervisor handles replies only. Child agents initiate asks with contact_supervisor.");
|
|
625
|
-
}
|
|
626
605
|
throw new Error(`Unsupported supervisor action: ${input.action}`);
|
|
627
606
|
},
|
|
628
607
|
};
|
|
629
608
|
}
|
|
630
609
|
|
|
631
610
|
export function createNativeSupervisorChannel(pi: ExtensionAPI, state: SubagentState, deps: NativeSupervisorChannelDeps = {}): {
|
|
611
|
+
registerTools: () => void;
|
|
632
612
|
start: () => void;
|
|
633
613
|
activateTransport: () => void;
|
|
614
|
+
findPendingAsks: (target: { runId: string; agent: string; childIndex: number }) => string[];
|
|
615
|
+
hasPendingRequests: () => boolean;
|
|
634
616
|
dispose: () => void;
|
|
635
617
|
pending: Map<string, PendingSupervisorRequest>;
|
|
636
618
|
getSupervisorRequestState: (event: ControlEvent) => SupervisorRequestState;
|
|
637
619
|
} {
|
|
638
620
|
const watch = deps.watch ?? fs.watch;
|
|
639
621
|
const timers = deps.timers ?? globalThis;
|
|
622
|
+
const runState = (request: SupervisorRequest): SubagentState => {
|
|
623
|
+
for (const ownerState of deps.getCurrentOwnerStates?.() ?? []) {
|
|
624
|
+
if (ownerState.asyncJobs.has(request.runId)) return ownerState;
|
|
625
|
+
}
|
|
626
|
+
return state;
|
|
627
|
+
};
|
|
640
628
|
const pending = new Map<string, PendingSupervisorRequest>();
|
|
641
629
|
const requestCorrelations = new Map<string, SupervisorRequestCorrelation>();
|
|
642
630
|
const correlationKey = (request: { runId: string; agent: string; childIndex: number; toolCallId?: string }): string | undefined => {
|
|
@@ -682,7 +670,7 @@ export function createNativeSupervisorChannel(pi: ExtensionAPI, state: SubagentS
|
|
|
682
670
|
if (!fs.existsSync(correlation.request.requestFile)
|
|
683
671
|
|| fs.existsSync(replyPath(correlation.request.channelDir, correlation.request.id))
|
|
684
672
|
|| now > requestExpiresAt(correlation.request, now)
|
|
685
|
-
|| requestRunInactive(correlation.request,
|
|
673
|
+
|| requestRunInactive(correlation.request, runState(correlation.request))) {
|
|
686
674
|
rememberResolvedRequest(correlation.request);
|
|
687
675
|
return "resolved";
|
|
688
676
|
}
|
|
@@ -697,18 +685,26 @@ export function createNativeSupervisorChannel(pi: ExtensionAPI, state: SubagentS
|
|
|
697
685
|
let started = false;
|
|
698
686
|
let lastStaleCleanupAt = 0;
|
|
699
687
|
const platform = deps.platform ?? process.platform;
|
|
700
|
-
const useNativeWatcher = () => shouldUseNativeFsWatch("supervisor-channel", platform) && platform !== "win32";
|
|
688
|
+
const useNativeWatcher = () => !deps.getChannelDirs && shouldUseNativeFsWatch("supervisor-channel", platform) && platform !== "win32";
|
|
701
689
|
const hasTransportDemand = () => {
|
|
702
690
|
if (pending.size > 0) return true;
|
|
703
691
|
if (state.foregroundControls.size > 0) return true;
|
|
704
|
-
|
|
692
|
+
if (deps.getChannelDirs?.().dirs.length) return true;
|
|
693
|
+
if ([...state.asyncJobs.values()].some((job) => job.status === "queued" || job.status === "running")) return true;
|
|
694
|
+
for (const ownerState of deps.getCurrentOwnerStates?.() ?? []) {
|
|
695
|
+
for (const job of ownerState.asyncJobs.values()) {
|
|
696
|
+
if (job.status === "queued" || job.status === "running") return true;
|
|
697
|
+
}
|
|
698
|
+
}
|
|
699
|
+
return false;
|
|
705
700
|
};
|
|
706
701
|
|
|
707
702
|
const registerParentTools = (): void => {
|
|
708
|
-
if (!hasTool(pi, NATIVE_SUPERVISOR_TOOL_NAME)) pi.registerTool(buildParentSupervisorTool(pi, pending, state, observeRequestLifecycle));
|
|
703
|
+
if (!hasTool(pi, NATIVE_SUPERVISOR_TOOL_NAME)) pi.registerTool(buildParentSupervisorTool(pi, pending, state, observeRequestLifecycle, () => poll(), runState));
|
|
709
704
|
};
|
|
710
705
|
|
|
711
706
|
const cleanupStaleChannelsIfDue = (): void => {
|
|
707
|
+
if (deps.getChannelDirs) return; // The root owns global retention cleanup.
|
|
712
708
|
const nowMs = Date.now();
|
|
713
709
|
if (nowMs - lastStaleCleanupAt < STALE_EMPTY_CHANNEL_CLEANUP_INTERVAL_MS) return;
|
|
714
710
|
lastStaleCleanupAt = nowMs;
|
|
@@ -721,15 +717,15 @@ export function createNativeSupervisorChannel(pi: ExtensionAPI, state: SubagentS
|
|
|
721
717
|
|
|
722
718
|
const poll = (): void => {
|
|
723
719
|
cleanupStaleChannelsIfDue();
|
|
724
|
-
|
|
725
|
-
|
|
726
|
-
refreshPendingRequests(pending, state, ctx, observeRequestLifecycle);
|
|
720
|
+
// Only display notifications require a live UI context, not request registration.
|
|
721
|
+
refreshPendingRequests(pending, state, observeRequestLifecycle, runState);
|
|
727
722
|
const now = Date.now();
|
|
728
|
-
|
|
723
|
+
const channels = deps.getChannelDirs?.();
|
|
724
|
+
for (const { channelDir, file } of listRequestFiles(channels?.dirs)) {
|
|
729
725
|
if (seenFiles.has(file)) continue;
|
|
730
726
|
const request = parseRequestFile(file, channelDir);
|
|
731
|
-
if (!request || !
|
|
732
|
-
const lifecycle = requestLifecycle(request, state,
|
|
727
|
+
if (!request || !requestMatchesOwner(request, state)) continue;
|
|
728
|
+
const lifecycle = requestLifecycle(request, state, now, runState(request));
|
|
733
729
|
if (lifecycle !== "pending") {
|
|
734
730
|
seenFiles.add(file);
|
|
735
731
|
observeRequestLifecycle(request, lifecycle);
|
|
@@ -737,48 +733,55 @@ export function createNativeSupervisorChannel(pi: ExtensionAPI, state: SubagentS
|
|
|
737
733
|
continue;
|
|
738
734
|
}
|
|
739
735
|
seenFiles.add(file);
|
|
740
|
-
if (request.expectsReply) {
|
|
741
|
-
|
|
742
|
-
|
|
743
|
-
markForegroundSupervisorAttention(request, state);
|
|
744
|
-
}
|
|
745
|
-
else {
|
|
736
|
+
if (!request.expectsReply) {
|
|
737
|
+
// Progress is already visible through child activity; do not inject a
|
|
738
|
+
// parent message or trigger a parent model turn.
|
|
746
739
|
removeRequestFile(request.requestFile);
|
|
740
|
+
continue;
|
|
747
741
|
}
|
|
748
|
-
|
|
749
|
-
|
|
750
|
-
|
|
751
|
-
|
|
752
|
-
|
|
753
|
-
|
|
754
|
-
|
|
755
|
-
|
|
756
|
-
|
|
757
|
-
|
|
758
|
-
|
|
759
|
-
|
|
760
|
-
|
|
761
|
-
|
|
762
|
-
|
|
763
|
-
|
|
764
|
-
|
|
765
|
-
|
|
766
|
-
|
|
767
|
-
|
|
768
|
-
|
|
769
|
-
|
|
770
|
-
|
|
771
|
-
});
|
|
772
|
-
|
|
742
|
+
rememberPendingRequest(request);
|
|
743
|
+
pending.set(request.id, request);
|
|
744
|
+
markForegroundSupervisorAttention(request, state);
|
|
745
|
+
// The ask is already queued above. A sendMessage failure (no UI, stale context) must not
|
|
746
|
+
// lose it, and must not abort the loop before the remaining asks register.
|
|
747
|
+
try {
|
|
748
|
+
pi.sendMessage({
|
|
749
|
+
customType: SUPERVISOR_REQUEST_MESSAGE_TYPE,
|
|
750
|
+
content: requestVisibleText(request),
|
|
751
|
+
display: true,
|
|
752
|
+
details: {
|
|
753
|
+
id: request.id,
|
|
754
|
+
requestId: request.id,
|
|
755
|
+
reason: request.reason,
|
|
756
|
+
expectsReply: request.expectsReply,
|
|
757
|
+
runId: request.runId,
|
|
758
|
+
agent: request.agent,
|
|
759
|
+
childIndex: request.childIndex,
|
|
760
|
+
...(request.childTarget ? { childTarget: request.childTarget } : {}),
|
|
761
|
+
...(request.interview !== undefined ? { interview: request.interview } : {}),
|
|
762
|
+
requestBody: request.message,
|
|
763
|
+
replyHint: supervisorReplyHint(request.id),
|
|
764
|
+
},
|
|
765
|
+
}, { triggerTurn: true });
|
|
766
|
+
} catch (error) {
|
|
767
|
+
console.error(`Failed to surface supervisor request ${request.id} as a user turn:`, error);
|
|
773
768
|
}
|
|
769
|
+
(pi as { events?: IntercomEventBus }).events?.emit(INTERCOM_DETACH_REQUEST_EVENT, {
|
|
770
|
+
requestId: request.id,
|
|
771
|
+
runId: request.runId,
|
|
772
|
+
agent: request.agent,
|
|
773
|
+
childIndex: request.childIndex,
|
|
774
|
+
});
|
|
775
|
+
if (pending.has(request.id)) markForegroundSupervisorAttention(request, state);
|
|
774
776
|
}
|
|
777
|
+
channels?.retire?.();
|
|
775
778
|
};
|
|
776
779
|
|
|
777
780
|
const startPolling = (): void => {
|
|
778
781
|
if (poller) return;
|
|
779
782
|
poller = timers.setInterval(() => {
|
|
780
783
|
poll();
|
|
781
|
-
if (!useNativeWatcher() && platform === "darwin" && !hasTransportDemand()) {
|
|
784
|
+
if (!useNativeWatcher() && (platform === "darwin" || deps.getChannelDirs) && !hasTransportDemand()) {
|
|
782
785
|
if (poller) timers.clearInterval(poller);
|
|
783
786
|
poller = undefined;
|
|
784
787
|
}
|
|
@@ -798,7 +801,7 @@ export function createNativeSupervisorChannel(pi: ExtensionAPI, state: SubagentS
|
|
|
798
801
|
try {
|
|
799
802
|
const watcher = watch(requestsDir, () => poll());
|
|
800
803
|
watcher.on("error", () => {
|
|
801
|
-
try { watcher.close(); } catch {}
|
|
804
|
+
try { watcher.close(); } catch { /* Best-effort watcher shutdown. */ }
|
|
802
805
|
requestWatchers.delete(requestsDir);
|
|
803
806
|
startPolling();
|
|
804
807
|
});
|
|
@@ -833,16 +836,40 @@ export function createNativeSupervisorChannel(pi: ExtensionAPI, state: SubagentS
|
|
|
833
836
|
};
|
|
834
837
|
|
|
835
838
|
return {
|
|
839
|
+
registerTools: registerParentTools,
|
|
836
840
|
activateTransport: () => {
|
|
837
841
|
if (!started) return;
|
|
838
842
|
poll();
|
|
839
843
|
if (!useNativeWatcher() && hasTransportDemand()) startPolling();
|
|
840
844
|
},
|
|
845
|
+
findPendingAsks: (target) => {
|
|
846
|
+
// Receipt-only discovery: no registration, notification, cleanup or reply writes.
|
|
847
|
+
const channelDir = resolveSupervisorChannelDir(target.runId, target.agent, target.childIndex);
|
|
848
|
+
let files: string[];
|
|
849
|
+
try { files = fs.readdirSync(path.join(channelDir, REQUESTS_DIR)); }
|
|
850
|
+
catch (error) {
|
|
851
|
+
if ((error as NodeJS.ErrnoException).code === "ENOENT") return [];
|
|
852
|
+
throw error;
|
|
853
|
+
}
|
|
854
|
+
const now = Date.now();
|
|
855
|
+
return files.filter(file => file.endsWith(".json")).flatMap(file => {
|
|
856
|
+
const request = parseRequestFile(path.join(channelDir, REQUESTS_DIR, file), channelDir);
|
|
857
|
+
return request?.expectsReply && request.runId === target.runId
|
|
858
|
+
&& request.agent === target.agent && request.childIndex === target.childIndex
|
|
859
|
+
&& requestLifecycle(request, state, now, runState(request)) === "pending" ? [request.id] : [];
|
|
860
|
+
}).sort();
|
|
861
|
+
},
|
|
862
|
+
hasPendingRequests: () => {
|
|
863
|
+
if (!started) return false;
|
|
864
|
+
poll();
|
|
865
|
+
return pending.size > 0;
|
|
866
|
+
},
|
|
841
867
|
start: () => {
|
|
842
868
|
if (started) return;
|
|
843
869
|
started = true;
|
|
844
870
|
registerParentTools();
|
|
845
871
|
poll();
|
|
872
|
+
if (deps.getChannelDirs) return; // Child polling starts only after a descendant launch.
|
|
846
873
|
try {
|
|
847
874
|
fs.mkdirSync(SUPERVISOR_CHANNEL_ROOT, { recursive: true });
|
|
848
875
|
if (!useNativeWatcher()) {
|
|
@@ -871,7 +898,7 @@ export function createNativeSupervisorChannel(pi: ExtensionAPI, state: SubagentS
|
|
|
871
898
|
}
|
|
872
899
|
rootWatcher = undefined;
|
|
873
900
|
for (const watcher of requestWatchers.values()) {
|
|
874
|
-
try { watcher.close(); } catch {}
|
|
901
|
+
try { watcher.close(); } catch { /* Best-effort watcher shutdown. */ }
|
|
875
902
|
}
|
|
876
903
|
requestWatchers.clear();
|
|
877
904
|
if (poller) timers.clearInterval(poller);
|
|
@@ -17,6 +17,7 @@ export interface SupervisorRequestMessageDetails {
|
|
|
17
17
|
childIndex?: number;
|
|
18
18
|
childTarget?: string;
|
|
19
19
|
interview?: unknown;
|
|
20
|
+
requestBody?: string;
|
|
20
21
|
replyHint?: string;
|
|
21
22
|
}
|
|
22
23
|
|
|
@@ -107,7 +108,7 @@ function optionalString(value: unknown): boolean {
|
|
|
107
108
|
|
|
108
109
|
function requestDetails(value: unknown): SupervisorRequestMessageDetails | undefined {
|
|
109
110
|
if (!isRecord(value)) return undefined;
|
|
110
|
-
if (!optionalString(value.id) || !optionalString(value.requestId) || !optionalString(value.replyHint) || !optionalString(value.runId) || !optionalString(value.agent) || !optionalString(value.childTarget)) return undefined;
|
|
111
|
+
if (!optionalString(value.id) || !optionalString(value.requestId) || !optionalString(value.replyHint) || !optionalString(value.requestBody) || !optionalString(value.runId) || !optionalString(value.agent) || !optionalString(value.childTarget)) return undefined;
|
|
111
112
|
if (value.reason !== undefined && !isSupervisorReason(value.reason)) return undefined;
|
|
112
113
|
if (value.expectsReply !== undefined && typeof value.expectsReply !== "boolean") return undefined;
|
|
113
114
|
if (value.childIndex !== undefined && (typeof value.childIndex !== "number" || !Number.isFinite(value.childIndex))) return undefined;
|
|
@@ -153,7 +154,7 @@ function requestLines(message: SupervisorMessageLike, details: SupervisorRequest
|
|
|
153
154
|
if (details.childTarget) lines.push(`Child target: ${boundedField(details.childTarget)}`);
|
|
154
155
|
lines.push(`Request ID: ${requestId}`);
|
|
155
156
|
if (details.expectsReply) lines.push(`Reply with: ${displayText(details.replyHint ?? supervisorReplyHint(requestId), MAX_BODY_CHARS, expanded)}`);
|
|
156
|
-
lines.push("", "Request:", displayText(contentText(message.content) || "(no request body)", MAX_BODY_CHARS, expanded));
|
|
157
|
+
lines.push("", "Request:", displayText((details.requestBody ?? contentText(message.content)) || "(no request body)", MAX_BODY_CHARS, expanded));
|
|
157
158
|
if (details.interview !== undefined) lines.push("", "Interview shape:", interviewText(details.interview, expanded));
|
|
158
159
|
return lines;
|
|
159
160
|
}
|
|
@@ -18,6 +18,12 @@ export interface MissionWorkflowState {
|
|
|
18
18
|
set(key: string, value: unknown): void;
|
|
19
19
|
}
|
|
20
20
|
|
|
21
|
+
export interface MissionWorkflowStateOptions {
|
|
22
|
+
isProcessAlive?: (pid: number) => boolean;
|
|
23
|
+
getProcessStartKey?: (pid: number) => string | undefined;
|
|
24
|
+
retryDelaysMs?: readonly number[];
|
|
25
|
+
}
|
|
26
|
+
|
|
21
27
|
export function missionStatePath(location: MissionStoreLocation, missionId: string): string {
|
|
22
28
|
return path.join(location.missionDir, validateMissionId(missionId), "state.json");
|
|
23
29
|
}
|
|
@@ -66,13 +72,22 @@ function windowsProcessStartKey(pid: number): string | undefined {
|
|
|
66
72
|
}
|
|
67
73
|
}
|
|
68
74
|
|
|
75
|
+
let currentProcessKey: string | undefined | null = null;
|
|
76
|
+
|
|
69
77
|
function processStartKey(pid: number): string | undefined {
|
|
78
|
+
// Foreign PIDs can be reused while this process lives, so resolve them afresh.
|
|
79
|
+
if (pid !== process.pid) return computeProcessStartKey(pid);
|
|
80
|
+
if (currentProcessKey === null) currentProcessKey = computeProcessStartKey(pid);
|
|
81
|
+
return currentProcessKey;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
function computeProcessStartKey(pid: number): string | undefined {
|
|
70
85
|
if (process.platform === "linux") return linuxProcessStartKey(pid) ?? psProcessStartKey(pid);
|
|
71
86
|
if (process.platform === "win32") return windowsProcessStartKey(pid);
|
|
72
87
|
return undefined;
|
|
73
88
|
}
|
|
74
89
|
|
|
75
|
-
|
|
90
|
+
type StateLockOptions = Required<MissionWorkflowStateOptions>;
|
|
76
91
|
|
|
77
92
|
function readStateLockOwner(lockPath: string): StateLockOwner | undefined {
|
|
78
93
|
try {
|
|
@@ -91,13 +106,13 @@ function readStateLockOwner(lockPath: string): StateLockOwner | undefined {
|
|
|
91
106
|
return undefined;
|
|
92
107
|
}
|
|
93
108
|
|
|
94
|
-
function stateLockIsStale(lockPath: string, now = Date.now()): boolean {
|
|
109
|
+
function stateLockIsStale(lockPath: string, options: StateLockOptions, now = Date.now()): boolean {
|
|
95
110
|
const owner = readStateLockOwner(lockPath);
|
|
96
111
|
if (owner) {
|
|
97
|
-
if (!isProcessAlive(owner.pid)) return true;
|
|
112
|
+
if (!options.isProcessAlive(owner.pid)) return true;
|
|
98
113
|
if (owner.processKey) {
|
|
99
|
-
const
|
|
100
|
-
if (
|
|
114
|
+
const observedProcessKey = options.getProcessStartKey(owner.pid);
|
|
115
|
+
if (observedProcessKey) return owner.processKey !== observedProcessKey;
|
|
101
116
|
if (owner.pid === process.pid) return true;
|
|
102
117
|
}
|
|
103
118
|
return false;
|
|
@@ -140,11 +155,11 @@ function waitForStateLock(delayMs: number | undefined, lockPath: string): void {
|
|
|
140
155
|
waitForFileSystemRetry(delayMs);
|
|
141
156
|
}
|
|
142
157
|
|
|
143
|
-
function reclaimStaleStateLock(lockPath: string, reclaimPath: string): boolean {
|
|
144
|
-
if (!stateLockIsStale(lockPath)) return false;
|
|
158
|
+
function reclaimStaleStateLock(lockPath: string, reclaimPath: string, options: StateLockOptions): boolean {
|
|
159
|
+
if (!stateLockIsStale(lockPath, options)) return false;
|
|
145
160
|
if (!tryMakeDirectory(reclaimPath, 0o700)) return false;
|
|
146
161
|
try {
|
|
147
|
-
if (!stateLockIsStale(lockPath)) return false;
|
|
162
|
+
if (!stateLockIsStale(lockPath, options)) return false;
|
|
148
163
|
fs.rmSync(lockPath, { recursive: true, force: true });
|
|
149
164
|
return true;
|
|
150
165
|
} finally {
|
|
@@ -152,7 +167,7 @@ function reclaimStaleStateLock(lockPath: string, reclaimPath: string): boolean {
|
|
|
152
167
|
}
|
|
153
168
|
}
|
|
154
169
|
|
|
155
|
-
function withStateFileLock<T>(filePath: string, operation: () => T): T {
|
|
170
|
+
function withStateFileLock<T>(filePath: string, operation: () => T, options: StateLockOptions): T {
|
|
156
171
|
fs.mkdirSync(path.dirname(filePath), { recursive: true });
|
|
157
172
|
const lockPath = `${filePath}.lock`;
|
|
158
173
|
const reclaimPath = `${lockPath}.reclaim`;
|
|
@@ -163,7 +178,7 @@ function withStateFileLock<T>(filePath: string, operation: () => T): T {
|
|
|
163
178
|
fs.rmSync(reclaimPath, { recursive: true, force: true });
|
|
164
179
|
continue;
|
|
165
180
|
}
|
|
166
|
-
waitForStateLock(
|
|
181
|
+
waitForStateLock(options.retryDelaysMs[attempt], lockPath);
|
|
167
182
|
continue;
|
|
168
183
|
}
|
|
169
184
|
let acquired = false;
|
|
@@ -171,17 +186,18 @@ function withStateFileLock<T>(filePath: string, operation: () => T): T {
|
|
|
171
186
|
acquired = tryMakeDirectory(lockPath, 0o700);
|
|
172
187
|
} catch (error) {
|
|
173
188
|
if (isRetryableFileSystemError(error)) {
|
|
174
|
-
waitForStateLock(
|
|
189
|
+
waitForStateLock(options.retryDelaysMs[attempt], lockPath);
|
|
175
190
|
continue;
|
|
176
191
|
}
|
|
177
192
|
throw new Error(`Failed to acquire mission state lock '${lockPath}': ${error instanceof Error ? error.message : String(error)}`);
|
|
178
193
|
}
|
|
179
194
|
if (!acquired) {
|
|
180
|
-
if (reclaimStaleStateLock(lockPath, reclaimPath)) continue;
|
|
181
|
-
waitForStateLock(
|
|
195
|
+
if (reclaimStaleStateLock(lockPath, reclaimPath, options)) continue;
|
|
196
|
+
waitForStateLock(options.retryDelaysMs[attempt], lockPath);
|
|
182
197
|
continue;
|
|
183
198
|
}
|
|
184
|
-
|
|
199
|
+
const key = options.getProcessStartKey(process.pid);
|
|
200
|
+
owner = { pid: process.pid, token: randomUUID(), createdAt: Date.now(), ...(key ? { processKey: key } : {}) };
|
|
185
201
|
try {
|
|
186
202
|
fs.writeFileSync(path.join(lockPath, "owner.json"), JSON.stringify(owner), { encoding: "utf-8", mode: 0o600 });
|
|
187
203
|
} catch (error) {
|
|
@@ -205,8 +221,13 @@ function validateStateKey(value: unknown): string {
|
|
|
205
221
|
return value;
|
|
206
222
|
}
|
|
207
223
|
|
|
208
|
-
export function createMissionWorkflowState(location: MissionStoreLocation, missionId: string): MissionWorkflowState {
|
|
224
|
+
export function createMissionWorkflowState(location: MissionStoreLocation, missionId: string, options: MissionWorkflowStateOptions = {}): MissionWorkflowState {
|
|
209
225
|
const filePath = missionStatePath(location, missionId);
|
|
226
|
+
const lockOptions: StateLockOptions = {
|
|
227
|
+
isProcessAlive: options.isProcessAlive ?? isProcessAlive,
|
|
228
|
+
getProcessStartKey: options.getProcessStartKey ?? processStartKey,
|
|
229
|
+
retryDelaysMs: options.retryDelaysMs ?? DEFAULT_FILE_SYSTEM_RETRY_DELAYS_MS,
|
|
230
|
+
};
|
|
210
231
|
let loaded = false;
|
|
211
232
|
let values: Record<string, unknown> = Object.create(null) as Record<string, unknown>;
|
|
212
233
|
|
|
@@ -254,7 +275,7 @@ export function createMissionWorkflowState(location: MissionStoreLocation, missi
|
|
|
254
275
|
writePrivateAtomicJson(filePath, next);
|
|
255
276
|
values = next;
|
|
256
277
|
loaded = true;
|
|
257
|
-
});
|
|
278
|
+
}, lockOptions);
|
|
258
279
|
},
|
|
259
280
|
};
|
|
260
281
|
}
|
package/src/policy/authority.ts
CHANGED
|
@@ -5,6 +5,8 @@ export const AUTHORITY_ACTIONS = [
|
|
|
5
5
|
"scheduleCreate",
|
|
6
6
|
"stopRun",
|
|
7
7
|
"steerRun",
|
|
8
|
+
"inspectorOpen",
|
|
9
|
+
"projectOpen",
|
|
8
10
|
] as const;
|
|
9
11
|
|
|
10
12
|
export type AuthorityAction = typeof AUTHORITY_ACTIONS[number];
|
|
@@ -18,6 +20,8 @@ const DEFAULT_AUTHORITY_POLICY: Record<AuthorityAction, AuthorityDecision> = {
|
|
|
18
20
|
scheduleCreate: "auto",
|
|
19
21
|
stopRun: "auto",
|
|
20
22
|
steerRun: "auto",
|
|
23
|
+
inspectorOpen: "auto",
|
|
24
|
+
projectOpen: "confirm",
|
|
21
25
|
};
|
|
22
26
|
|
|
23
27
|
export function resolveAuthorityDecision(input: {
|