@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,256 @@
|
|
|
1
|
+
import { randomUUID } from "node:crypto";
|
|
2
|
+
import * as fs from "node:fs";
|
|
3
|
+
import * as path from "node:path";
|
|
4
|
+
import type { AgentToolResult } from "@earendil-works/pi-agent-core";
|
|
5
|
+
import { writeAtomicJson } from "../../shared/atomic-json.ts";
|
|
6
|
+
import type { AsyncStatus, Details, SubagentState, ToolBudgetConfig, TurnBudgetConfig } from "../../shared/types.ts";
|
|
7
|
+
import { readStatus } from "../../shared/utils.ts";
|
|
8
|
+
import { consumeSteerAcks, deliverInterruptRequest, queueRevivalBrief, requestAsyncSteer, type SteerDeliveryMode, type SteerRequest } from "../background/control-channel.ts";
|
|
9
|
+
import { resolveAsyncResumeTarget } from "../background/async-resume.ts";
|
|
10
|
+
import { reconcileAsyncRun } from "../background/stale-run-reconciler.ts";
|
|
11
|
+
import { actionResultFromSteeringStatus, claimSteeringRecovery, createSteeringStatus, recordSteeringRequest, remainingSteeringRecoveryLimits, updateSteeringTarget, waitForSteeringAction } from "../background/steering.ts";
|
|
12
|
+
|
|
13
|
+
export async function steerAsyncRun(input: {
|
|
14
|
+
state: SubagentState;
|
|
15
|
+
runId: string;
|
|
16
|
+
message: string;
|
|
17
|
+
mode?: SteerDeliveryMode;
|
|
18
|
+
index?: number;
|
|
19
|
+
kill?: (pid: number, signal?: NodeJS.Signals | 0) => boolean;
|
|
20
|
+
location: { asyncDir: string | null };
|
|
21
|
+
signal?: AbortSignal;
|
|
22
|
+
ackTimeoutMs?: number;
|
|
23
|
+
recoveryTimeoutMs?: number;
|
|
24
|
+
onRequestQueued?: (requestPath: string) => void;
|
|
25
|
+
onBeforeRecoveryClaim?: (requestId: string, committedAt: number) => void;
|
|
26
|
+
onRecoveryCommitted?: (requestId: string, committedAt: number) => void;
|
|
27
|
+
recover?: (limits: { timeoutMs?: number; absoluteDeadlineAt?: number; turnBudget?: TurnBudgetConfig; toolBudget?: ToolBudgetConfig }) => Promise<AgentToolResult<Details>>;
|
|
28
|
+
}): Promise<AgentToolResult<Details>> {
|
|
29
|
+
if (!input.location.asyncDir) {
|
|
30
|
+
return {
|
|
31
|
+
content: [{ type: "text", text: `Async run '${input.runId}' has no live run directory to steer.` }],
|
|
32
|
+
isError: true,
|
|
33
|
+
details: { mode: "management", results: [] },
|
|
34
|
+
};
|
|
35
|
+
}
|
|
36
|
+
const asyncDir = input.location.asyncDir;
|
|
37
|
+
const status = reconcileAsyncRun(asyncDir, { kill: input.kill }).status;
|
|
38
|
+
if (input.state.currentSessionId && status?.sessionId !== input.state.currentSessionId) {
|
|
39
|
+
return {
|
|
40
|
+
content: [{ type: "text", text: `Async run '${input.runId}' was not found in the active session.` }],
|
|
41
|
+
isError: true,
|
|
42
|
+
details: { mode: "management", results: [] },
|
|
43
|
+
};
|
|
44
|
+
}
|
|
45
|
+
if (!status) {
|
|
46
|
+
return {
|
|
47
|
+
content: [{ type: "text", text: `Async run '${input.runId}' was not found.` }],
|
|
48
|
+
isError: true,
|
|
49
|
+
details: { mode: "management", results: [] },
|
|
50
|
+
};
|
|
51
|
+
}
|
|
52
|
+
const steps = status.steps ?? [];
|
|
53
|
+
if (status.state !== "running" && status.state !== "queued") {
|
|
54
|
+
const retained = input.mode === "follow_up" && status.state === "complete" && Boolean(status.parentWorkflowRunId) && steps.length === 1 && (steps[0]?.status === "complete" || steps[0]?.status === "completed") && Boolean(steps[0]?.sessionFile ?? status.sessionFile);
|
|
55
|
+
if (!retained) {
|
|
56
|
+
return {
|
|
57
|
+
content: [{ type: "text", text: `Async run '${input.runId}' is not running or queued and cannot be steered.` }],
|
|
58
|
+
isError: true,
|
|
59
|
+
details: { mode: "management", results: [] },
|
|
60
|
+
};
|
|
61
|
+
}
|
|
62
|
+
if (input.index !== undefined && input.index !== 0) {
|
|
63
|
+
return { content: [{ type: "text", text: `Retained async run '${status.runId}' has one child. Index ${input.index} is out of range.` }], isError: true, details: { mode: "management", results: [] } };
|
|
64
|
+
}
|
|
65
|
+
const request: SteerRequest = { type: "steer", id: randomUUID(), ts: Date.now(), message: input.message.trim(), mode: "follow_up", targetIndex: 0, source: "steer-action" };
|
|
66
|
+
try {
|
|
67
|
+
queueRevivalBrief(asyncDir, request);
|
|
68
|
+
} catch (error) {
|
|
69
|
+
return { content: [{ type: "text", text: `Failed to queue retained follow-up for async run ${status.runId}: ${error instanceof Error ? error.message : String(error)}` }], isError: true, details: { mode: "management", results: [] } };
|
|
70
|
+
}
|
|
71
|
+
status.steering ??= createSteeringStatus();
|
|
72
|
+
recordSteeringRequest(status.steering, { id: request.id, requestedAt: request.ts, source: request.source, message: request.message, targets: [{ index: 0, state: "scheduled" }] });
|
|
73
|
+
writeAtomicJson(path.join(asyncDir, "status.json"), status);
|
|
74
|
+
const queued = { requestId: request.id, state: "scheduled" as const, deliveryStatus: "queued" as const, sourceRunId: status.runId, targets: [{ index: 0, state: "scheduled" as const }] };
|
|
75
|
+
return { content: [{ type: "text", text: `Follow-up queued for the next resume of retained async run ${status.runId} (request ${request.id}).` }], details: { mode: "management", results: [], steering: queued } };
|
|
76
|
+
}
|
|
77
|
+
if (input.index !== undefined) {
|
|
78
|
+
if (input.index < 0 || input.index >= steps.length) {
|
|
79
|
+
return {
|
|
80
|
+
content: [{ type: "text", text: `Async run '${status.runId}' has ${steps.length} children. Index ${input.index} is out of range.` }],
|
|
81
|
+
isError: true,
|
|
82
|
+
details: { mode: "management", results: [] },
|
|
83
|
+
};
|
|
84
|
+
}
|
|
85
|
+
const targetStep = steps[input.index];
|
|
86
|
+
if (targetStep && targetStep.status !== "running" && targetStep.status !== "pending") {
|
|
87
|
+
return {
|
|
88
|
+
content: [{ type: "text", text: `Async run '${status.runId}' child ${input.index} is ${targetStep.status} and cannot be steered.` }],
|
|
89
|
+
isError: true,
|
|
90
|
+
details: { mode: "management", results: [] },
|
|
91
|
+
};
|
|
92
|
+
}
|
|
93
|
+
} else {
|
|
94
|
+
const running = steps.filter((step) => step.status === "running");
|
|
95
|
+
if (running.length === 0 && steps.length > 1) {
|
|
96
|
+
return {
|
|
97
|
+
content: [{ type: "text", text: `Async run '${status.runId}' has no running child yet. Provide index to steer a queued child.` }],
|
|
98
|
+
isError: true,
|
|
99
|
+
details: { mode: "management", results: [] },
|
|
100
|
+
};
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
const runningIndexes = steps
|
|
104
|
+
.map((step, index) => step.status === "running" ? index : undefined)
|
|
105
|
+
.filter((index): index is number => index !== undefined);
|
|
106
|
+
const effectiveTargetIndex = input.index ?? (status.mode === "single" && runningIndexes.length === 0 && steps[0]?.status === "pending" ? 0 : undefined);
|
|
107
|
+
const targetIndexes = effectiveTargetIndex !== undefined ? [effectiveTargetIndex] : runningIndexes;
|
|
108
|
+
if (targetIndexes.length === 0) {
|
|
109
|
+
return {
|
|
110
|
+
content: [{ type: "text", text: `Async run '${status.runId}' has no running child to steer.` }],
|
|
111
|
+
isError: true,
|
|
112
|
+
details: { mode: "management", results: [] },
|
|
113
|
+
};
|
|
114
|
+
}
|
|
115
|
+
const requestId = randomUUID();
|
|
116
|
+
let requestPath: string;
|
|
117
|
+
try {
|
|
118
|
+
requestPath = requestAsyncSteer(asyncDir, {
|
|
119
|
+
message: input.message,
|
|
120
|
+
mode: input.mode,
|
|
121
|
+
...(effectiveTargetIndex !== undefined ? { targetIndex: effectiveTargetIndex } : { targetIndexes }),
|
|
122
|
+
source: "steer-action",
|
|
123
|
+
id: requestId,
|
|
124
|
+
});
|
|
125
|
+
} catch (error) {
|
|
126
|
+
return {
|
|
127
|
+
content: [{ type: "text", text: `Failed to queue steering for async run ${status.runId}: ${error instanceof Error ? error.message : String(error)}` }],
|
|
128
|
+
isError: true,
|
|
129
|
+
details: { mode: "management", results: [] },
|
|
130
|
+
};
|
|
131
|
+
}
|
|
132
|
+
input.onRequestQueued?.(requestPath);
|
|
133
|
+
const tracked = input.state.asyncJobs.get(status.runId);
|
|
134
|
+
if (tracked) tracked.updatedAt = Date.now();
|
|
135
|
+
const targets = targetIndexes.map((index) => ({ index, state: status.steps?.[index]?.status === "pending" ? "scheduled" as const : "pending" as const }));
|
|
136
|
+
if (targets.every((target) => target.state === "scheduled")) {
|
|
137
|
+
const scheduled = { requestId, state: "scheduled" as const, deliveryStatus: "queued" as const, sourceRunId: status.runId, targets };
|
|
138
|
+
return { content: [{ type: "text", text: `Steering scheduled for async run ${status.runId} (request ${requestId}).` }], details: { mode: "management", results: [], steering: scheduled } };
|
|
139
|
+
}
|
|
140
|
+
const waited = await waitForSteeringAction({ asyncDir, sourceRunId: status.runId, requestId, timeoutMs: input.ackTimeoutMs ?? 3_000, signal: input.signal });
|
|
141
|
+
const result = waited ?? { requestId, state: "pending" as const, deliveryStatus: "queued" as const, sourceRunId: status.runId, targets };
|
|
142
|
+
if (input.signal?.aborted) {
|
|
143
|
+
return { content: [{ type: "text", text: `Steering pending for async run ${status.runId} (request ${requestId}); caller aborted before recovery.` }], details: { mode: "management", results: [], steering: result } };
|
|
144
|
+
}
|
|
145
|
+
const finalStatus = readStatus(asyncDir);
|
|
146
|
+
const finalResult = finalStatus?.steering ? actionResultFromSteeringStatus(finalStatus.steering, status.runId, requestId) : undefined;
|
|
147
|
+
if (finalResult?.state === "delivered") {
|
|
148
|
+
return { content: [{ type: "text", text: `Steering delivered for async run ${status.runId} (request ${requestId}).` }], details: { mode: "management", results: [], steering: finalResult } };
|
|
149
|
+
}
|
|
150
|
+
const running = (finalStatus?.steps ?? status.steps ?? []).filter((step) => step.status === "running");
|
|
151
|
+
const recoveryAllowed = (input.mode ?? "steer") === "steer" && status.mode === "single" && status.isNested !== true && running.length === 1 && Boolean(finalStatus?.steering) && (input.index === undefined || input.index === 0);
|
|
152
|
+
if (recoveryAllowed && finalResult?.state !== "scheduled" && input.recover) {
|
|
153
|
+
const appendSteeringNotice = (state: "failed" | "recovered", message: string): void => {
|
|
154
|
+
try {
|
|
155
|
+
fs.appendFileSync(path.join(asyncDir, "events.jsonl"), `${JSON.stringify({ type: "subagent.steering.notice", ts: Date.now(), runId: status.runId, requestId, state, message, ...(status.sessionId ? { currentSessionId: status.sessionId } : {}) })}\n`);
|
|
156
|
+
} catch {
|
|
157
|
+
// The action result and status remain authoritative if diagnostic notification persistence fails.
|
|
158
|
+
}
|
|
159
|
+
};
|
|
160
|
+
try {
|
|
161
|
+
const latest = readStatus(asyncDir);
|
|
162
|
+
const latestResult = latest?.steering ? actionResultFromSteeringStatus(latest.steering, status.runId, requestId) : undefined;
|
|
163
|
+
if (latestResult?.state === "delivered") return { content: [{ type: "text", text: `Steering delivered for async run ${status.runId} (request ${requestId}).` }], details: { mode: "management", results: [], steering: latestResult } };
|
|
164
|
+
const committedAt = Date.now();
|
|
165
|
+
input.onBeforeRecoveryClaim?.(requestId, committedAt);
|
|
166
|
+
const { claimPath, markerPath } = claimSteeringRecovery(asyncDir, { requestId, sourceRunId: status.runId, committedAt });
|
|
167
|
+
input.onRecoveryCommitted?.(requestId, committedAt);
|
|
168
|
+
const preCommitStatus = readStatus(asyncDir);
|
|
169
|
+
const preCommitResult = preCommitStatus?.steering ? actionResultFromSteeringStatus(preCommitStatus.steering, status.runId, requestId) : undefined;
|
|
170
|
+
if (preCommitResult?.state === "delivered" && preCommitResult.targets.every((target) => target.deliveredAt !== undefined && target.deliveredAt <= committedAt)) {
|
|
171
|
+
fs.rmSync(markerPath, { force: true });
|
|
172
|
+
fs.rmSync(claimPath, { force: true });
|
|
173
|
+
return { content: [{ type: "text", text: `Steering delivered for async run ${status.runId} (request ${requestId}).` }], details: { mode: "management", results: [], steering: preCommitResult } };
|
|
174
|
+
}
|
|
175
|
+
try {
|
|
176
|
+
deliverInterruptRequest({ asyncDir, pid: latest?.pid ?? status.pid, kill: input.kill, source: "steering-recovery" });
|
|
177
|
+
} catch (error) {
|
|
178
|
+
fs.rmSync(markerPath, { force: true });
|
|
179
|
+
fs.rmSync(claimPath, { force: true });
|
|
180
|
+
throw new Error(`Failed to commit steering recovery interrupt: ${error instanceof Error ? error.message : String(error)}`);
|
|
181
|
+
}
|
|
182
|
+
const pauseDeadline = Date.now() + (input.recoveryTimeoutMs ?? 15_000);
|
|
183
|
+
let paused: AsyncStatus | null = null;
|
|
184
|
+
while (Date.now() <= pauseDeadline) {
|
|
185
|
+
if (input.signal?.aborted) break;
|
|
186
|
+
const candidate = readStatus(asyncDir);
|
|
187
|
+
if (candidate?.state === "paused" && candidate.endedAt !== undefined) { paused = candidate; break; }
|
|
188
|
+
await new Promise<void>((resolve) => setTimeout(resolve, 50));
|
|
189
|
+
}
|
|
190
|
+
if (!paused) throw new Error("Source run did not reach confirmed paused state within 15 seconds; no replacement was launched and the recovery claim remains committed to prevent a delayed duplicate.");
|
|
191
|
+
let lateAckRecorded = false;
|
|
192
|
+
for (const ack of consumeSteerAcks(asyncDir)) {
|
|
193
|
+
if (!paused.steering?.recent.some((request) => request.id === ack.requestId && request.targets.some((target) => target.index === ack.index))) continue;
|
|
194
|
+
const state = ack.state === "delivered" ? "late" : "failed";
|
|
195
|
+
const reason = ack.state === "delivered" ? "acknowledged after recovery commit" : ack.message;
|
|
196
|
+
updateSteeringTarget(paused.steering, ack.requestId, ack.index, state, ack.ts, { reason });
|
|
197
|
+
const stepSteering = paused.steps?.[ack.index]?.steering;
|
|
198
|
+
if (stepSteering) updateSteeringTarget(stepSteering, ack.requestId, ack.index, state, ack.ts, { reason });
|
|
199
|
+
lateAckRecorded = true;
|
|
200
|
+
try {
|
|
201
|
+
fs.appendFileSync(path.join(asyncDir, "events.jsonl"), `${JSON.stringify({ type: ack.state === "delivered" ? "subagent.steer.delivered" : "subagent.steer.failed", ts: ack.ts, runId: status.runId, requestId: ack.requestId, index: ack.index, late: true, message: ack.message })}\n`);
|
|
202
|
+
} catch {
|
|
203
|
+
// Status remains authoritative when diagnostic event persistence fails.
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
if (lateAckRecorded) writeAtomicJson(path.join(asyncDir, "status.json"), paused);
|
|
207
|
+
let recoveryTarget;
|
|
208
|
+
try {
|
|
209
|
+
recoveryTarget = resolveAsyncResumeTarget(
|
|
210
|
+
{ id: status.runId },
|
|
211
|
+
{ kill: input.kill },
|
|
212
|
+
{ sessionId: input.state.currentSessionId ?? undefined },
|
|
213
|
+
);
|
|
214
|
+
} catch (error) {
|
|
215
|
+
throw new Error(`Source run remains paused and cannot be revived safely: ${error instanceof Error ? error.message : String(error)}`);
|
|
216
|
+
}
|
|
217
|
+
if (recoveryTarget.kind !== "revive" || !recoveryTarget.sessionFile) throw new Error("Source run has no valid persisted child session; it remains paused and requires a new run.");
|
|
218
|
+
if (!recoveryTarget.recoveryDescriptor) throw new Error("Source run has no private recovery descriptor; it remains paused and is not safely resumable.");
|
|
219
|
+
const limits = remainingSteeringRecoveryLimits(recoveryTarget.recoveryDescriptor, paused);
|
|
220
|
+
const revived = await input.recover(limits);
|
|
221
|
+
if (revived.isError || !revived.details.asyncId) throw new Error(revived.content[0]?.type === "text" ? revived.content[0].text : "Replacement launch failed; source run remains paused.");
|
|
222
|
+
const sourceStatus = readStatus(asyncDir);
|
|
223
|
+
const targetIndex = input.index ?? status.steps?.findIndex((step) => step.status === "running") ?? -1;
|
|
224
|
+
if (sourceStatus?.state === "paused" && sourceStatus.steering && targetIndex >= 0) {
|
|
225
|
+
updateSteeringTarget(sourceStatus.steering, requestId, targetIndex, "recovered", Date.now(), { replacementRunId: revived.details.asyncId });
|
|
226
|
+
const stepSteering = sourceStatus.steps?.[targetIndex]?.steering;
|
|
227
|
+
if (stepSteering) updateSteeringTarget(stepSteering, requestId, targetIndex, "recovered", Date.now(), { replacementRunId: revived.details.asyncId });
|
|
228
|
+
writeAtomicJson(path.join(asyncDir, "status.json"), sourceStatus);
|
|
229
|
+
}
|
|
230
|
+
const recovered = sourceStatus?.steering ? actionResultFromSteeringStatus(sourceStatus.steering, status.runId, requestId, revived.details.asyncId) : undefined;
|
|
231
|
+
appendSteeringNotice("recovered", `Steering recovered for run ${status.runId}; replacement ${revived.details.asyncId} launched.`);
|
|
232
|
+
return { content: [{ type: "text", text: `Steering recovered for async run ${status.runId}; replacement ${revived.details.asyncId} launched after the source paused.` }], details: { mode: "management", results: [], steering: recovered ?? { requestId, state: "recovered", sourceRunId: status.runId, replacementRunId: revived.details.asyncId, deliveryStatus: "delivered", targets: [{ index: input.index ?? 0, state: "recovered" }] } } };
|
|
233
|
+
} catch (error) {
|
|
234
|
+
const reason = error instanceof Error ? error.message : String(error);
|
|
235
|
+
const failedStatus = readStatus(asyncDir);
|
|
236
|
+
const targetIndex = input.index ?? status.steps?.findIndex((step) => step.status === "running") ?? -1;
|
|
237
|
+
if (failedStatus && failedStatus.state !== "running" && failedStatus.state !== "queued" && failedStatus.steering && targetIndex >= 0) {
|
|
238
|
+
updateSteeringTarget(failedStatus.steering, requestId, targetIndex, "failed", Date.now(), { reason });
|
|
239
|
+
const stepSteering = failedStatus.steps?.[targetIndex]?.steering;
|
|
240
|
+
if (stepSteering) updateSteeringTarget(stepSteering, requestId, targetIndex, "failed", Date.now(), { reason });
|
|
241
|
+
failedStatus.activityState = "needs_attention";
|
|
242
|
+
writeAtomicJson(path.join(asyncDir, "status.json"), failedStatus);
|
|
243
|
+
}
|
|
244
|
+
const failed = failedStatus?.steering ? actionResultFromSteeringStatus(failedStatus.steering, status.runId, requestId) : undefined;
|
|
245
|
+
appendSteeringNotice("failed", `Steering failed for run ${status.runId}: ${reason}`);
|
|
246
|
+
return { content: [{ type: "text", text: `Steering failed for async run ${status.runId} (request ${requestId}): ${reason}` }], isError: true, details: { mode: "management", results: [], steering: failed ?? { requestId, state: "failed", sourceRunId: status.runId, deliveryStatus: "queued", targets: [{ index: input.index ?? 0, state: "failed", reason }] } } };
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
const stateText = result.state === "failed" ? "failed" : result.state === "partial" ? "partial" : result.deliveryStatus === "queued" ? "queued" : result.state === "delivered" ? "delivered" : result.state === "scheduled" ? "scheduled" : result.state === "recovered" ? "recovered" : "pending";
|
|
250
|
+
const isError = result.state === "failed" || result.state === "partial";
|
|
251
|
+
return {
|
|
252
|
+
content: [{ type: "text", text: `Steering ${stateText} for async run ${status.runId} (request ${requestId}).` }],
|
|
253
|
+
...(isError ? { isError: true } : {}),
|
|
254
|
+
details: { mode: "management", results: [], steering: result },
|
|
255
|
+
};
|
|
256
|
+
}
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
import * as path from "node:path";
|
|
2
|
+
import type { AgentToolResult } from "@earendil-works/pi-agent-core";
|
|
3
|
+
import type { Details, SubagentState } from "../../shared/types.ts";
|
|
4
|
+
import { deliverStopRequest } from "../background/control-channel.ts";
|
|
5
|
+
import { reconcileAsyncRun } from "../background/stale-run-reconciler.ts";
|
|
6
|
+
|
|
7
|
+
function getAsyncStopTarget(
|
|
8
|
+
state: SubagentState,
|
|
9
|
+
runId: string | undefined,
|
|
10
|
+
location?: { asyncDir: string | null; resolvedId?: string },
|
|
11
|
+
): { asyncId: string; asyncDir: string } | undefined {
|
|
12
|
+
if (location?.asyncDir) {
|
|
13
|
+
return {
|
|
14
|
+
asyncId: location.resolvedId ?? runId ?? path.basename(location.asyncDir),
|
|
15
|
+
asyncDir: location.asyncDir,
|
|
16
|
+
};
|
|
17
|
+
}
|
|
18
|
+
if (!runId) return undefined;
|
|
19
|
+
const direct = state.asyncJobs.get(runId);
|
|
20
|
+
return direct ? { asyncId: direct.asyncId, asyncDir: direct.asyncDir } : undefined;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export function stopAsyncRun(
|
|
24
|
+
state: SubagentState,
|
|
25
|
+
runId: string | undefined,
|
|
26
|
+
kill?: (pid: number, signal?: NodeJS.Signals | 0) => boolean,
|
|
27
|
+
location?: { asyncDir: string | null; resolvedId?: string },
|
|
28
|
+
): AgentToolResult<Details> | null {
|
|
29
|
+
const target = getAsyncStopTarget(state, runId, location);
|
|
30
|
+
if (!target) return null;
|
|
31
|
+
const status = reconcileAsyncRun(target.asyncDir, { kill }).status;
|
|
32
|
+
if (state.currentSessionId && status?.sessionId !== state.currentSessionId) {
|
|
33
|
+
return {
|
|
34
|
+
content: [{ type: "text", text: `Async run '${target.asyncId}' was not found in the active session.` }],
|
|
35
|
+
isError: true,
|
|
36
|
+
details: { mode: "management", results: [] },
|
|
37
|
+
};
|
|
38
|
+
}
|
|
39
|
+
if (!status || (status.state !== "running" && status.state !== "queued")) {
|
|
40
|
+
return {
|
|
41
|
+
content: [{ type: "text", text: `No running or queued async run was found for '${runId ?? "current"}'.` }],
|
|
42
|
+
isError: true,
|
|
43
|
+
details: { mode: "management", results: [] },
|
|
44
|
+
};
|
|
45
|
+
}
|
|
46
|
+
try {
|
|
47
|
+
deliverStopRequest({ asyncDir: target.asyncDir, pid: typeof status.pid === "number" ? status.pid : undefined, kill, source: "stop-action" });
|
|
48
|
+
const tracked = state.asyncJobs.get(target.asyncId);
|
|
49
|
+
if (tracked) {
|
|
50
|
+
tracked.activityState = undefined;
|
|
51
|
+
tracked.updatedAt = Date.now();
|
|
52
|
+
}
|
|
53
|
+
return {
|
|
54
|
+
content: [{ type: "text", text: `Stop requested for async run ${target.asyncId}.` }],
|
|
55
|
+
details: { mode: "management", results: [] },
|
|
56
|
+
};
|
|
57
|
+
} catch (error) {
|
|
58
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
59
|
+
return {
|
|
60
|
+
content: [{ type: "text", text: `Failed to stop async run ${target.asyncId}: ${message}` }],
|
|
61
|
+
isError: true,
|
|
62
|
+
details: { mode: "management", results: [] },
|
|
63
|
+
};
|
|
64
|
+
}
|
|
65
|
+
}
|