@ferris1225/pi-subagents 4.3.31 → 4.3.33
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 +80 -0
- package/LICENSE +1 -1
- package/README.md +215 -273
- package/index.ts +15 -14
- package/package.json +10 -10
- package/skills/workflow/SKILL.md +226 -0
- package/src/configuration/config.ts +17 -121
- package/src/configuration/models.ts +1 -1
- package/src/configuration/setup.ts +80 -176
- package/src/configuration/ui.ts +28 -66
- package/src/delegation/agents.ts +79 -209
- package/src/delegation/builtin-agents.ts +60 -0
- package/src/delegation/dispatch.ts +32 -149
- package/src/delegation/prompt.ts +7 -5
- package/src/execution/rpc-control.ts +6 -2
- package/src/execution/rpc-run.ts +60 -20
- package/src/execution/spawn.ts +17 -28
- package/src/isolation/git-command.ts +1 -2
- package/src/isolation/recovery.ts +1 -1
- package/src/isolation/temp-hygiene.ts +2 -2
- package/src/isolation/worktree.ts +31 -17
- package/src/lifecycle/completion.ts +1 -1
- package/src/lifecycle/dispatch-core.ts +142 -0
- package/src/lifecycle/durable.ts +3 -3
- package/src/lifecycle/runtime.ts +34 -1
- package/src/lifecycle/thread-lifecycle.ts +36 -25
- package/src/lifecycle/thread-shared.ts +11 -4
- package/src/lifecycle/tools.ts +84 -11
- package/src/presentation/monitor.ts +39 -17
- package/src/presentation/widget.ts +2 -2
- package/src/workflow/durable.ts +195 -0
- package/src/workflow/engine.ts +625 -0
- package/src/workflow/files.ts +217 -0
- package/src/workflow/plan.ts +340 -0
- package/src/workflow/state.ts +48 -0
- package/src/workflow/tool.ts +269 -0
- package/workflows/code-review.md +57 -0
- package/workflows/migration.md +52 -0
- package/workflows/research.md +47 -0
- package/agents/artisan.md +0 -18
- package/agents/scout.md +0 -19
package/src/execution/spawn.ts
CHANGED
|
@@ -24,45 +24,34 @@ import {
|
|
|
24
24
|
} from "./rpc-control.ts";
|
|
25
25
|
import {
|
|
26
26
|
currentSubagentDepth,
|
|
27
|
-
DEPTH_ENV_VAR,
|
|
28
|
-
extractToolErrorText,
|
|
29
|
-
getPiInvocation,
|
|
30
27
|
isRpcCommandTimeoutError,
|
|
31
28
|
runRpcAgentAttempt,
|
|
32
29
|
sessionExists,
|
|
33
|
-
writeChildRetryPolicyExtension,
|
|
34
|
-
SUBAGENT_KILL_GRACE_MS,
|
|
35
30
|
} from "./rpc-run.ts";
|
|
36
31
|
import { writeTempOwnerMarker } from "../isolation/temp-hygiene.ts";
|
|
37
32
|
|
|
38
33
|
export {
|
|
39
34
|
currentSubagentDepth,
|
|
40
|
-
DEPTH_ENV_VAR,
|
|
41
|
-
extractToolErrorText,
|
|
42
|
-
getPiInvocation,
|
|
43
|
-
isRpcCommandTimeoutError,
|
|
44
35
|
RpcRunControl,
|
|
45
36
|
sessionExists,
|
|
46
|
-
SUBAGENT_KILL_GRACE_MS,
|
|
47
|
-
writeChildRetryPolicyExtension,
|
|
48
37
|
};
|
|
49
38
|
export type { SubagentLiveEvent, UsageStats };
|
|
50
39
|
|
|
51
|
-
|
|
40
|
+
const SUBAGENT_THINKING_LEVEL: ThinkingLevel = DEFAULT_THINKING_LEVEL;
|
|
52
41
|
/** 0 disables the watchdog; dispatch supplies the configured timeout. */
|
|
53
|
-
|
|
42
|
+
const SUBAGENT_DEFAULT_IDLE_TIMEOUT_MS = 0;
|
|
54
43
|
/** Base delays cover Pi's stale-lock window and leave headroom beyond the
|
|
55
44
|
* default four-way launch fan-out. Additive jitter below reduces the chance
|
|
56
45
|
* that contenders retry in the same lockstep waves. */
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
46
|
+
const SUBAGENT_STARTUP_RETRY_DELAYS_MS = [250, 750, 1500, 3000, 6000] as const;
|
|
47
|
+
const MAX_SUBAGENT_STARTUP_FAILURE_DURATION_MS = 2000;
|
|
48
|
+
const MAX_SUBAGENT_STARTUP_RETRY_JITTER_MS = 1000;
|
|
60
49
|
|
|
61
50
|
function normalizeStartupRetryDelay(delayMs: number): number {
|
|
62
51
|
return Number.isFinite(delayMs) && delayMs > 0 ? delayMs : 0;
|
|
63
52
|
}
|
|
64
53
|
|
|
65
|
-
|
|
54
|
+
function addStartupRetryJitter(delayMs: number, randomValue = Math.random()): number {
|
|
66
55
|
const baseDelay = Math.floor(normalizeStartupRetryDelay(delayMs));
|
|
67
56
|
if (baseDelay === 0) return 0;
|
|
68
57
|
const boundedRandom = Number.isFinite(randomValue) ? Math.max(0, Math.min(1, randomValue)) : 0;
|
|
@@ -80,7 +69,7 @@ export interface SubagentDetails {
|
|
|
80
69
|
/** Text of the newest assistant message that has any. A final answer may be
|
|
81
70
|
* split into several text blocks (for example around interleaved thinking);
|
|
82
71
|
* returning only the first block silently dropped the rest of the result. */
|
|
83
|
-
|
|
72
|
+
function getFinalOutput(messages: Message[]): string {
|
|
84
73
|
for (let i = messages.length - 1; i >= 0; i--) {
|
|
85
74
|
const msg = messages[i];
|
|
86
75
|
if (msg.role !== "assistant") continue;
|
|
@@ -113,13 +102,13 @@ export function truncateResultOutput(output: string, maxLines: number): Truncate
|
|
|
113
102
|
return { text: kept.join("\n"), truncated: true, shownLines: kept.length, totalLines, widthClipped };
|
|
114
103
|
}
|
|
115
104
|
|
|
116
|
-
|
|
117
|
-
|
|
105
|
+
const RESULT_ARTIFACT_MAX_AGE_MS = 7 * 24 * 60 * 60 * 1_000;
|
|
106
|
+
const RESULT_ARTIFACT_MAX_FILES_PER_PROJECT = 50;
|
|
118
107
|
// Explicit current prefix plus the strict timestamp/token convention used by 1.1.0.
|
|
119
108
|
const RESULT_ARTIFACT_NAME = /^(?:pi-subagent-\d{13,}-[0-9a-f]{12}|\d{13,}-[a-z0-9]{6})-[\w.-]+\.md$/;
|
|
120
109
|
|
|
121
110
|
/** Name of the single internal-state root under the pi agent directory. */
|
|
122
|
-
|
|
111
|
+
const PROJECT_ROOTS_DIR_NAME = "ferris-pi-subagents";
|
|
123
112
|
|
|
124
113
|
export function getSubagentsRoot(configPath: string): string {
|
|
125
114
|
return join(dirname(configPath), PROJECT_ROOTS_DIR_NAME);
|
|
@@ -142,7 +131,7 @@ interface ResultArtifactRetentionOptions {
|
|
|
142
131
|
* results directory, newest kept first. Unknown files and symlinks are never
|
|
143
132
|
* touched. Runs on every artifact write, so an active project stays bounded
|
|
144
133
|
* without ever deleting the result the current completion just linked. */
|
|
145
|
-
|
|
134
|
+
function pruneResultArtifacts(
|
|
146
135
|
resultsDir: string,
|
|
147
136
|
options: ResultArtifactRetentionOptions = {},
|
|
148
137
|
): void {
|
|
@@ -196,7 +185,7 @@ export function sweepProjectResultArtifacts(
|
|
|
196
185
|
}
|
|
197
186
|
}
|
|
198
187
|
|
|
199
|
-
|
|
188
|
+
function resultArtifactProjectKey(cwd?: string): string {
|
|
200
189
|
if (!cwd) return "default";
|
|
201
190
|
let canonical: string;
|
|
202
191
|
try {
|
|
@@ -289,11 +278,11 @@ export function isRetryableStartupFailure(result: SingleResult, durationMs: numb
|
|
|
289
278
|
return true;
|
|
290
279
|
}
|
|
291
280
|
|
|
292
|
-
|
|
281
|
+
function formatStartupRetryExhaustedError(model: string, attempts: number): string {
|
|
293
282
|
return `Subagent failed to start after ${attempts} attempt${attempts === 1 ? "" : "s"} on ${model}: the child failed before its initial RPC prompt was dispatched and produced no model, tool, output, or usage activity. Main handles this phase; inspect launch diagnostics instead of redispatching it.`;
|
|
294
283
|
}
|
|
295
284
|
|
|
296
|
-
|
|
285
|
+
async function waitForStartupRetry(delayMs: number, signal?: AbortSignal): Promise<boolean> {
|
|
297
286
|
const normalizedDelay = normalizeStartupRetryDelay(delayMs);
|
|
298
287
|
if (normalizedDelay === 0) return !signal?.aborted;
|
|
299
288
|
if (!signal) {
|
|
@@ -366,14 +355,14 @@ export function buildResumePrompt(task: string, reason: string): string {
|
|
|
366
355
|
/** Create a fresh private session directory under the given root. The owner
|
|
367
356
|
* marker is what lets a later load tell a session this process still owns from
|
|
368
357
|
* one a crash abandoned. */
|
|
369
|
-
|
|
358
|
+
async function createSessionDir(root: string): Promise<string> {
|
|
370
359
|
await mkdir(root, { recursive: true });
|
|
371
360
|
const dir = await mkdtemp(join(root, "pi-subagent-session-"));
|
|
372
361
|
writeTempOwnerMarker(dir);
|
|
373
362
|
return dir;
|
|
374
363
|
}
|
|
375
364
|
|
|
376
|
-
|
|
365
|
+
function buildFallbackResumeReason(fromModel?: string): string {
|
|
377
366
|
return fromModel
|
|
378
367
|
? `the selected model (${fromModel}) failed at the model/provider level, so the current main model is continuing`
|
|
379
368
|
: "the selected model failed at the model/provider level, so the current main model is continuing";
|
|
@@ -444,7 +433,7 @@ function signalAbortDisposition(options: RunSingleOptions, base: SingleResult):
|
|
|
444
433
|
}
|
|
445
434
|
|
|
446
435
|
/** Spawn one RPC attempt and wait for stable settlement. */
|
|
447
|
-
|
|
436
|
+
async function runSingleAgent(options: RunSingleOptions): Promise<SingleResult> {
|
|
448
437
|
const {
|
|
449
438
|
agent,
|
|
450
439
|
agentName,
|
|
@@ -27,9 +27,8 @@ export type CommandRunner = (
|
|
|
27
27
|
) => Promise<CommandResult>;
|
|
28
28
|
|
|
29
29
|
export const GIT_COMMAND_TIMEOUT_MS = 120_000;
|
|
30
|
-
|
|
30
|
+
const GIT_COMMAND_KILL_GRACE_MS = 2_000;
|
|
31
31
|
export const GIT_OUTPUT_MAX_BYTES = 64 * 1024 * 1024;
|
|
32
|
-
export const WORKTREE_PATCH_MAX_BYTES = GIT_OUTPUT_MAX_BYTES;
|
|
33
32
|
|
|
34
33
|
/** Default argument-safe runner. Output is bounded before binary patches enter
|
|
35
34
|
* memory, and timeout/abort terminates the complete checkout-filter process tree. */
|
|
@@ -9,7 +9,7 @@ import { getProjectRoot, getSubagentsRoot } from "../execution/spawn.ts";
|
|
|
9
9
|
import { managedRecoveryGroup, samePath } from "./managed-paths.ts";
|
|
10
10
|
import { removeWorktreeGroup, type WorktreeFinalization } from "./worktree.ts";
|
|
11
11
|
|
|
12
|
-
|
|
12
|
+
const RECOVERY_MANIFEST_FILE_NAME = "pi-subagents-recovery.json";
|
|
13
13
|
const RECOVERY_MANIFEST_VERSION = 1;
|
|
14
14
|
|
|
15
15
|
export interface RecoveryRecord {
|
|
@@ -43,7 +43,7 @@ const DURABLE_SUBDIRS = ["sessions", "worktrees"] as const;
|
|
|
43
43
|
|
|
44
44
|
/** Unmarked directories (crash before the marker write) must outlive this age
|
|
45
45
|
* before removal. */
|
|
46
|
-
|
|
46
|
+
const UNMARKED_TEMP_MAX_AGE_MS = 7 * 24 * 60 * 60 * 1_000;
|
|
47
47
|
|
|
48
48
|
interface TempOwner {
|
|
49
49
|
pid: number;
|
|
@@ -138,7 +138,7 @@ function directoryAgeMs(entry: Dirent, dir: string, now: number): number | undef
|
|
|
138
138
|
|
|
139
139
|
/** Remove dead-owner and old-unmarked directories under `rootDir`.
|
|
140
140
|
* Returns how many directories were removed. */
|
|
141
|
-
|
|
141
|
+
function sweepOrphanTempDirs(
|
|
142
142
|
rootDir: string,
|
|
143
143
|
options: SweepOptions = {},
|
|
144
144
|
): number {
|
|
@@ -116,11 +116,8 @@ export interface WorktreeIsolation {
|
|
|
116
116
|
finalize(): Promise<WorktreeFinalization>;
|
|
117
117
|
}
|
|
118
118
|
|
|
119
|
-
|
|
120
|
-
constructor(
|
|
121
|
-
message: string,
|
|
122
|
-
readonly retainedPaths: readonly string[] = [],
|
|
123
|
-
) {
|
|
119
|
+
class WorktreeSetupError extends Error {
|
|
120
|
+
constructor(message: string) {
|
|
124
121
|
super(message);
|
|
125
122
|
this.name = "WorktreeSetupError";
|
|
126
123
|
}
|
|
@@ -276,7 +273,7 @@ export async function resolveRepositoryRoot(
|
|
|
276
273
|
}
|
|
277
274
|
|
|
278
275
|
/** Resolve and validate the Git repository/worktree that contains cwd. */
|
|
279
|
-
|
|
276
|
+
async function resolveWorktreeTarget(
|
|
280
277
|
cwd: string,
|
|
281
278
|
runner: CommandRunner = runCommand,
|
|
282
279
|
): Promise<WorktreeTarget> {
|
|
@@ -308,23 +305,41 @@ class GitWorktreeIsolation implements WorktreeIsolation {
|
|
|
308
305
|
private discardPromise?: Promise<void>;
|
|
309
306
|
/** Full workspace checkpoint retained for manual recovery. */
|
|
310
307
|
private continuationCheckpoint?: WorktreeCheckpoint;
|
|
308
|
+
readonly originalCwd: string;
|
|
309
|
+
readonly originalRoot: string;
|
|
310
|
+
readonly cwd: string;
|
|
311
|
+
readonly worktreePath: string;
|
|
312
|
+
readonly tempDir: string;
|
|
313
|
+
readonly patchPath: string;
|
|
314
|
+
readonly head: string;
|
|
315
|
+
private readonly runner: CommandRunner;
|
|
316
|
+
/** A restored base may represent work already integrated into the parent. */
|
|
317
|
+
readonly integrationBaseHead: string;
|
|
311
318
|
|
|
312
319
|
constructor(
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
readonly integrationBaseHead: string = head,
|
|
320
|
+
originalCwd: string,
|
|
321
|
+
originalRoot: string,
|
|
322
|
+
cwd: string,
|
|
323
|
+
worktreePath: string,
|
|
324
|
+
tempDir: string,
|
|
325
|
+
patchPath: string,
|
|
326
|
+
head: string,
|
|
327
|
+
runner: CommandRunner,
|
|
328
|
+
integrationBaseHead: string = head,
|
|
323
329
|
restored?: {
|
|
324
330
|
state: WorktreeIsolation["state"];
|
|
325
331
|
checkpoint?: WorktreeCheckpoint;
|
|
326
332
|
},
|
|
327
333
|
) {
|
|
334
|
+
this.originalCwd = originalCwd;
|
|
335
|
+
this.originalRoot = originalRoot;
|
|
336
|
+
this.cwd = cwd;
|
|
337
|
+
this.worktreePath = worktreePath;
|
|
338
|
+
this.tempDir = tempDir;
|
|
339
|
+
this.patchPath = patchPath;
|
|
340
|
+
this.head = head;
|
|
341
|
+
this.runner = runner;
|
|
342
|
+
this.integrationBaseHead = integrationBaseHead;
|
|
328
343
|
if (restored) {
|
|
329
344
|
this.currentState = restored.state;
|
|
330
345
|
if (restored.checkpoint) this.continuationCheckpoint = cloneCheckpoint(restored.checkpoint);
|
|
@@ -648,7 +663,6 @@ export async function createWorktreeIsolation(
|
|
|
648
663
|
const cause = error instanceof Error ? error.message : String(error);
|
|
649
664
|
throw new WorktreeSetupError(
|
|
650
665
|
`Could not create isolated Git worktree: ${cause}${rollbackErrors.length > 0 ? ` Rollback errors: ${rollbackErrors.join("; ")}` : ""}${retainedPaths.length > 0 ? ` Retained artifacts: ${retainedPaths.join(", ")}` : ""}`,
|
|
651
|
-
retainedPaths,
|
|
652
666
|
);
|
|
653
667
|
}
|
|
654
668
|
}
|
|
@@ -14,7 +14,7 @@ export interface CompletionBatchTimings {
|
|
|
14
14
|
maxWaitMs: number;
|
|
15
15
|
}
|
|
16
16
|
|
|
17
|
-
|
|
17
|
+
const DEFAULT_COMPLETION_BATCH_TIMINGS: CompletionBatchTimings = {
|
|
18
18
|
debounceMs: 150,
|
|
19
19
|
maxWaitMs: 1_000,
|
|
20
20
|
};
|
|
@@ -0,0 +1,142 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Shared background-dispatch machinery used by both delegation tools.
|
|
3
|
+
*
|
|
4
|
+
* The `subagent` tool and the workflow runner start children through the same
|
|
5
|
+
* dispatcher, live-activity projection, terminal-notification path, and tool-card
|
|
6
|
+
* details builder. Keeping them here means a workflow node is an ordinary
|
|
7
|
+
* managed run: same queue pacing, isolation, admission, durable checkpointing,
|
|
8
|
+
* and completion accounting.
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
import { createBackgroundDispatcher } from "./thread-lifecycle.ts";
|
|
12
|
+
import { getResultError, type SingleResult, type SubagentDetails, type SubagentLiveEvent } from "../execution/spawn.ts";
|
|
13
|
+
import { formatTaskSummary, formatToolActivity, monitor } from "../presentation/monitor.ts";
|
|
14
|
+
import type { StartBackgroundInternal, DispatchEnvironment } from "./thread-shared.ts";
|
|
15
|
+
import { persistThreadCheckpoint } from "./thread-shared.ts";
|
|
16
|
+
import type { SubagentRuntime } from "./runtime.ts";
|
|
17
|
+
|
|
18
|
+
export interface DispatchCore {
|
|
19
|
+
/** Publish the context/config/catalog a dispatch needs; every fresh call refreshes it. */
|
|
20
|
+
setEnvironment(environment: DispatchEnvironment): void;
|
|
21
|
+
startBackground: StartBackgroundInternal;
|
|
22
|
+
/** Stamp a terminal monitor state and toast the result once. */
|
|
23
|
+
finishRun: (runId: number, status: "done" | "failed", opts?: { silent?: boolean }) => void;
|
|
24
|
+
makeLiveHandler: (runId: number, generation?: number) => (event: SubagentLiveEvent) => void;
|
|
25
|
+
makeDetails: (mode: "single" | "parallel", background?: boolean) => (results: SingleResult[]) => SubagentDetails;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export function createDispatchCore(runtime: SubagentRuntime): DispatchCore {
|
|
29
|
+
const environmentRef: { current: DispatchEnvironment | undefined } = { current: undefined };
|
|
30
|
+
|
|
31
|
+
// Terminal rows stay in the monitor until the next beginTurn so the footer
|
|
32
|
+
// can count them beside siblings that are still live. The widget ignores
|
|
33
|
+
// them. Repeated publication of the same settlement is a no-op.
|
|
34
|
+
const publishedEndedAt = new Map<number, number>();
|
|
35
|
+
const finishRun = (
|
|
36
|
+
runId: number,
|
|
37
|
+
status: "done" | "failed",
|
|
38
|
+
opts?: { silent?: boolean },
|
|
39
|
+
): void => {
|
|
40
|
+
const run = monitor.findRun(runId);
|
|
41
|
+
if (!run) return;
|
|
42
|
+
monitor.setStatus(runId, status); // stamps endedAt for the elapsed time
|
|
43
|
+
const endedAt = monitor.findRun(runId)?.endedAt;
|
|
44
|
+
if (endedAt !== undefined && publishedEndedAt.get(runId) === endedAt) return;
|
|
45
|
+
if (endedAt !== undefined) publishedEndedAt.set(runId, endedAt);
|
|
46
|
+
if (opts?.silent || !runtime.sessionActive) return;
|
|
47
|
+
const icon = status === "done" ? "✓" : "✗";
|
|
48
|
+
const result = runtime.threads.get(runId)?.lastResult;
|
|
49
|
+
const error = status === "failed" ? result ? getResultError(result) : "No failure reason was recorded." : undefined;
|
|
50
|
+
environmentRef.current?.ctx.ui.notify(
|
|
51
|
+
`${icon} #${run.id} ${monitor.summarize(run)}${error ? ` · ${formatTaskSummary(error, 300, false)}` : ""}`,
|
|
52
|
+
status === "done" ? "info" : "error",
|
|
53
|
+
);
|
|
54
|
+
};
|
|
55
|
+
|
|
56
|
+
// Live sub-agent activity → concise one-line status ("thinking",
|
|
57
|
+
// "read src/index.ts", ...), never a raw args blob. The live handler
|
|
58
|
+
// only updates monitor state; the queue task owns terminal removal,
|
|
59
|
+
// notification, and lifecycle decisions.
|
|
60
|
+
const makeLiveHandler = (runId: number, generation?: number) => {
|
|
61
|
+
// Every child turn reports "running"; the manifest is rewritten only when
|
|
62
|
+
// what it records for recovery (session path, child pids) actually changed.
|
|
63
|
+
let checkpointKey: string | undefined;
|
|
64
|
+
return (e: SubagentLiveEvent): void => {
|
|
65
|
+
if (generation !== undefined && runtime.threads.get(runId)?.generation !== generation) return;
|
|
66
|
+
switch (e.kind) {
|
|
67
|
+
case "status":
|
|
68
|
+
monitor.setStatus(runId, e.status);
|
|
69
|
+
// A fresh running segment refreshes the durable checkpoint (session
|
|
70
|
+
// path plus child pids) so a crash mid-generation still restores.
|
|
71
|
+
if (e.status === "running") {
|
|
72
|
+
const thread = runtime.threads.get(runId);
|
|
73
|
+
if (thread?.sessionId && thread.sessionDir) {
|
|
74
|
+
const key = `${thread.sessionDir}\0${thread.control.getChildPids().join(",")}`;
|
|
75
|
+
if (key !== checkpointKey) {
|
|
76
|
+
checkpointKey = key;
|
|
77
|
+
persistThreadCheckpoint(runtime, thread, "parked");
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
break;
|
|
82
|
+
case "model":
|
|
83
|
+
monitor.setModel(runId, e.model, e.fallbackFrom);
|
|
84
|
+
monitor.setThinking(runId, e.thinking);
|
|
85
|
+
break;
|
|
86
|
+
case "usage":
|
|
87
|
+
monitor.setUsage(runId, e.usage, e.model);
|
|
88
|
+
break;
|
|
89
|
+
case "session": {
|
|
90
|
+
runtime.retainSession({ sessionDir: e.sessionDir });
|
|
91
|
+
const thread = runtime.threads.get(runId);
|
|
92
|
+
if (thread && (generation === undefined || runtime.threads.get(runId)?.generation === generation)) {
|
|
93
|
+
thread.sessionId = e.sessionId;
|
|
94
|
+
thread.sessionDir = e.sessionDir;
|
|
95
|
+
persistThreadCheckpoint(runtime, thread, "parked");
|
|
96
|
+
}
|
|
97
|
+
break;
|
|
98
|
+
}
|
|
99
|
+
case "tool_start":
|
|
100
|
+
monitor.recordToolStart(runId, e.toolName, formatToolActivity(e.toolName, e.args));
|
|
101
|
+
break;
|
|
102
|
+
case "tool_end":
|
|
103
|
+
monitor.recordToolEnd(runId, e.toolName, e.isError);
|
|
104
|
+
break;
|
|
105
|
+
case "thinking":
|
|
106
|
+
monitor.setActivity(runId, "thinking");
|
|
107
|
+
break;
|
|
108
|
+
case "text":
|
|
109
|
+
// A text delta is model output, not a filesystem write.
|
|
110
|
+
monitor.setActivity(runId, "responding");
|
|
111
|
+
break;
|
|
112
|
+
}
|
|
113
|
+
};
|
|
114
|
+
};
|
|
115
|
+
|
|
116
|
+
const makeDetails =
|
|
117
|
+
(mode: "single" | "parallel", background = false) =>
|
|
118
|
+
(results: SingleResult[]): SubagentDetails => ({ mode, results, background });
|
|
119
|
+
|
|
120
|
+
const startBackground = createBackgroundDispatcher({
|
|
121
|
+
runtime,
|
|
122
|
+
getEnvironment: () => {
|
|
123
|
+
if (!environmentRef.current) {
|
|
124
|
+
throw new Error("pi-subagents dispatch environment is not ready yet.");
|
|
125
|
+
}
|
|
126
|
+
return environmentRef.current;
|
|
127
|
+
},
|
|
128
|
+
finishRun,
|
|
129
|
+
makeLiveHandler,
|
|
130
|
+
makeDetails,
|
|
131
|
+
});
|
|
132
|
+
|
|
133
|
+
return {
|
|
134
|
+
setEnvironment: (environment) => {
|
|
135
|
+
environmentRef.current = environment;
|
|
136
|
+
},
|
|
137
|
+
startBackground,
|
|
138
|
+
finishRun,
|
|
139
|
+
makeLiveHandler,
|
|
140
|
+
makeDetails,
|
|
141
|
+
};
|
|
142
|
+
}
|
package/src/lifecycle/durable.ts
CHANGED
|
@@ -34,7 +34,7 @@ import {
|
|
|
34
34
|
worktreeSnapshot,
|
|
35
35
|
} from "../isolation/worktree.ts";
|
|
36
36
|
|
|
37
|
-
|
|
37
|
+
const THREADS_MANIFEST_FILE_NAME = "pi-subagents-threads.json";
|
|
38
38
|
const THREADS_MANIFEST_VERSION = 1;
|
|
39
39
|
|
|
40
40
|
/** Project directories whose newest file has not been touched for this long
|
|
@@ -98,7 +98,7 @@ export interface ThreadRecord {
|
|
|
98
98
|
}
|
|
99
99
|
|
|
100
100
|
/** Approximate timestamp of the machine's current boot. */
|
|
101
|
-
|
|
101
|
+
function currentBootId(now = Date.now()): number {
|
|
102
102
|
return Math.round(now - uptime() * 1_000);
|
|
103
103
|
}
|
|
104
104
|
|
|
@@ -475,7 +475,7 @@ export async function pruneThreadRecords(
|
|
|
475
475
|
|
|
476
476
|
/** Paths a thread manifest still references; combined with recovery references by
|
|
477
477
|
* startup retention before any durable directory is swept. */
|
|
478
|
-
|
|
478
|
+
function referencedDurablePaths(records: readonly ThreadRecord[]): Set<string> {
|
|
479
479
|
const paths = new Set<string>();
|
|
480
480
|
for (const record of records) {
|
|
481
481
|
if (record.sessionDir) paths.add(record.sessionDir);
|
package/src/lifecycle/runtime.ts
CHANGED
|
@@ -8,7 +8,7 @@
|
|
|
8
8
|
* to every registration site, so state stays in one place without globals.
|
|
9
9
|
*/
|
|
10
10
|
|
|
11
|
-
import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
|
|
11
|
+
import type { ExtensionAPI, ToolInfo } from "@earendil-works/pi-coding-agent";
|
|
12
12
|
import type { PhaseScope } from "../delegation/phase-scope.ts";
|
|
13
13
|
import { rmSync } from "node:fs";
|
|
14
14
|
import { resolveSubagentConcurrency, BackgroundTaskQueue } from "../execution/background.ts";
|
|
@@ -25,6 +25,7 @@ import { isRunActiveStatus, monitor } from "../presentation/monitor.ts";
|
|
|
25
25
|
import type { RpcRunControl } from "../execution/rpc-control.ts";
|
|
26
26
|
import { isFailedResult, type SingleResult } from "../execution/spawn.ts";
|
|
27
27
|
import type { IsolationMode, WorktreeFinalization, WorktreeIsolation } from "../isolation/worktree.ts";
|
|
28
|
+
import type { WorkflowRun } from "../workflow/state.ts";
|
|
28
29
|
|
|
29
30
|
export type ThreadState = "queued" | "running" | "interrupting" | "parked" | "completed" | "failed" | "stopped";
|
|
30
31
|
|
|
@@ -76,6 +77,10 @@ export interface SubagentRuntime {
|
|
|
76
77
|
backgroundQueue: BackgroundTaskQueue;
|
|
77
78
|
/** Live parent tool names from ExtensionAPI, read again for each child launch. */
|
|
78
79
|
getActiveTools: () => string[];
|
|
80
|
+
/** Live metadata for the registered tools, read again for each child launch.
|
|
81
|
+
* Read-only role policy and write capability come from it, never from a
|
|
82
|
+
* hardcoded list of extension or MCP tool names. */
|
|
83
|
+
getToolInfos: () => ToolInfo[];
|
|
79
84
|
/** False after session_shutdown; guards delivery and queue work. */
|
|
80
85
|
sessionActive: boolean;
|
|
81
86
|
/** Resolves when the load-time durable restore pass has finished. Everything
|
|
@@ -111,6 +116,15 @@ export interface SubagentRuntime {
|
|
|
111
116
|
registerRunResult: (runId: number, result: SingleResult) => void;
|
|
112
117
|
/** Logical threads outlive process attempts and completed generations. */
|
|
113
118
|
threads: Map<number, SubagentThread>;
|
|
119
|
+
/** Workflow graphs started in this parent session, live and settled. */
|
|
120
|
+
workflows: Map<number, WorkflowRun>;
|
|
121
|
+
/** Allocate a graph id that no retained or live workflow record owns. */
|
|
122
|
+
reserveWorkflowId: () => number;
|
|
123
|
+
/** Raise the graph-id allocator above an id restored from a durable record. */
|
|
124
|
+
ensureWorkflowIdAbove: (id: number) => void;
|
|
125
|
+
/** Session-teardown tasks that must run before runtime state is released
|
|
126
|
+
* (persisting a graph's shape, for example). */
|
|
127
|
+
shutdownHooks: Array<() => Promise<void> | void>;
|
|
114
128
|
/** Every session directory retained for this parent session. */
|
|
115
129
|
sessionDirs: Set<string>;
|
|
116
130
|
retainSession: (result: Pick<SingleResult, "sessionDir">) => void;
|
|
@@ -121,6 +135,7 @@ export interface SubagentRuntime {
|
|
|
121
135
|
|
|
122
136
|
export function createRuntime(pi: ExtensionAPI, configPath: string): SubagentRuntime {
|
|
123
137
|
const backgroundQueue = new BackgroundTaskQueue(resolveSubagentConcurrency());
|
|
138
|
+
let nextWorkflowId = 1;
|
|
124
139
|
// Compaction reads the whole history, summarizes it, and replaces it. A
|
|
125
140
|
// completion injected into that window can be swallowed by the summary,
|
|
126
141
|
// silently losing a result a child spent minutes producing — so delivery is
|
|
@@ -137,6 +152,7 @@ export function createRuntime(pi: ExtensionAPI, configPath: string): SubagentRun
|
|
|
137
152
|
configPath,
|
|
138
153
|
backgroundQueue,
|
|
139
154
|
getActiveTools: () => pi.getActiveTools(),
|
|
155
|
+
getToolInfos: () => pi.getAllTools(),
|
|
140
156
|
sessionActive: true,
|
|
141
157
|
durableRestore: Promise.resolve(),
|
|
142
158
|
restoredRunIds: [],
|
|
@@ -210,6 +226,12 @@ export function createRuntime(pi: ExtensionAPI, configPath: string): SubagentRun
|
|
|
210
226
|
settledRuns: new Map<number, SingleResult>(),
|
|
211
227
|
settledListeners: new Map<number, Set<(result: SingleResult) => void>>(),
|
|
212
228
|
threads: new Map<number, SubagentThread>(),
|
|
229
|
+
workflows: new Map<number, WorkflowRun>(),
|
|
230
|
+
reserveWorkflowId: () => nextWorkflowId++,
|
|
231
|
+
ensureWorkflowIdAbove: (id) => {
|
|
232
|
+
if (id >= nextWorkflowId) nextWorkflowId = id + 1;
|
|
233
|
+
},
|
|
234
|
+
shutdownHooks: [],
|
|
213
235
|
sessionDirs: new Set<string>(),
|
|
214
236
|
retainSession: (result) => {
|
|
215
237
|
if (result.sessionDir) runtime.sessionDirs.add(result.sessionDir);
|
|
@@ -329,6 +351,15 @@ export function createRuntime(pi: ExtensionAPI, configPath: string): SubagentRun
|
|
|
329
351
|
/* best-effort; the state-root sweep catches leftovers later */
|
|
330
352
|
}
|
|
331
353
|
}
|
|
354
|
+
// Let owners persist their own last state (a workflow's shape) while the
|
|
355
|
+
// threads it refers to still exist.
|
|
356
|
+
for (const hook of runtime.shutdownHooks) {
|
|
357
|
+
try {
|
|
358
|
+
await hook();
|
|
359
|
+
} catch {
|
|
360
|
+
/* a teardown hook must never block shutdown */
|
|
361
|
+
}
|
|
362
|
+
}
|
|
332
363
|
runtime.settledRuns.clear();
|
|
333
364
|
runtime.settledListeners.clear();
|
|
334
365
|
runtime.runControllers.clear();
|
|
@@ -337,6 +368,8 @@ export function createRuntime(pi: ExtensionAPI, configPath: string): SubagentRun
|
|
|
337
368
|
// manifest; the next process re-registers them at restore.
|
|
338
369
|
runtime.sessionDirs.clear();
|
|
339
370
|
runtime.threads.clear();
|
|
371
|
+
runtime.workflows.clear();
|
|
372
|
+
runtime.shutdownHooks = [];
|
|
340
373
|
monitor.clear();
|
|
341
374
|
},
|
|
342
375
|
};
|
|
@@ -10,7 +10,7 @@
|
|
|
10
10
|
import { join, resolve } from "node:path";
|
|
11
11
|
import { isWriteCapableAgent, resolveAgentTools, type AgentConfig } from "../delegation/agents.ts";
|
|
12
12
|
import type { CompletionMessageItem } from "./completion.ts";
|
|
13
|
-
import { loadConfig } from "../configuration/config.ts";
|
|
13
|
+
import { DEFAULT_IDLE_TIMEOUT_SEC, DEFAULT_MAX_RESULT_LINES, loadConfig } from "../configuration/config.ts";
|
|
14
14
|
import { dispatchFailedResult, failedStartResult, formatCompletionBlock, modelLevelTakeoverNote, queuedResult } from "../presentation/format.ts";
|
|
15
15
|
import { formatTaskSummary, monitor } from "../presentation/monitor.ts";
|
|
16
16
|
import { findDuplicateDispatch } from "../delegation/prompt.ts";
|
|
@@ -96,8 +96,12 @@ export function createBackgroundDispatcher(options: BackgroundDispatcherOptions)
|
|
|
96
96
|
const runConfig = baseEnvironment.config;
|
|
97
97
|
const discoveredAgent = baseEnvironment.agents.find((candidate) => candidate.name === agentName);
|
|
98
98
|
if (!discoveredAgent) return failedStartResult(agentName, task, `Unknown agent: "${agentName}".`);
|
|
99
|
+
// Admission reads the catalog once; each child launch reads the live one
|
|
100
|
+
// again, like the active tool set, so a server that connected meanwhile
|
|
101
|
+
// is classified by its own annotations.
|
|
102
|
+
const toolInfos = runtime.getToolInfos();
|
|
99
103
|
const resolveLiveAgentTools = (candidate: AgentConfig): AgentConfig =>
|
|
100
|
-
resolveAgentTools(
|
|
104
|
+
resolveAgentTools(candidate, runtime.getActiveTools(), runtime.getToolInfos());
|
|
101
105
|
const agent = resolveLiveAgentTools(discoveredAgent);
|
|
102
106
|
const originalCwd = resolve(cwd ?? runCtx.cwd);
|
|
103
107
|
let phaseId: string | undefined;
|
|
@@ -108,8 +112,12 @@ export function createBackgroundDispatcher(options: BackgroundDispatcherOptions)
|
|
|
108
112
|
} catch (error) {
|
|
109
113
|
return failedStartResult(agentName, task, error instanceof Error ? error.message : String(error));
|
|
110
114
|
}
|
|
111
|
-
const writeCapable = Boolean(startOptions.writeCapable) || isWriteCapableAgent(agent);
|
|
112
|
-
|
|
115
|
+
const writeCapable = Boolean(startOptions.writeCapable) || isWriteCapableAgent(agent, toolInfos);
|
|
116
|
+
// A workflow node is an ordinary managed run whose reporting belongs to
|
|
117
|
+
// the graph: it settles into the graph's single summary instead of
|
|
118
|
+
// waking the parent once per node.
|
|
119
|
+
const quiet = startOptions.quiet === true;
|
|
120
|
+
if (isolation === "worktree" && !isWorktreeCapableAgent(agent, toolInfos)) {
|
|
113
121
|
return {
|
|
114
122
|
...failedStartResult(agentName, task, `Agent "${agentName}" is read-only; worktree isolation is available only to write-capable agents such as artisan.`),
|
|
115
123
|
isolation,
|
|
@@ -139,7 +147,10 @@ export function createBackgroundDispatcher(options: BackgroundDispatcherOptions)
|
|
|
139
147
|
? { ...resolvedRoute, agent: withWorktreeSystemPrompt(resolvedRoute.agent) }
|
|
140
148
|
: resolvedRoute;
|
|
141
149
|
const thinkingLevel = route.thinkingLevel;
|
|
142
|
-
const runId = monitor.addRun(agent.name, task, route.agent.model, thinkingLevel, {
|
|
150
|
+
const runId = monitor.addRun(agent.name, task, route.agent.model, thinkingLevel, {
|
|
151
|
+
isolation,
|
|
152
|
+
...(startOptions.workflow ? { workflow: startOptions.workflow } : {}),
|
|
153
|
+
});
|
|
143
154
|
runtime.claimRunDelivery(runId, startOptions.deliveryRoute ?? "background");
|
|
144
155
|
const generation = 1;
|
|
145
156
|
const pending: SingleResult = {
|
|
@@ -223,14 +234,13 @@ export function createBackgroundDispatcher(options: BackgroundDispatcherOptions)
|
|
|
223
234
|
// queued behind the concurrency limit. Re-resolve the route at actual
|
|
224
235
|
// start so /subagents-setup edits apply to not-yet-started runs.
|
|
225
236
|
let activeRoute = route;
|
|
226
|
-
|
|
237
|
+
const activeIdleTimeoutMs = DEFAULT_IDLE_TIMEOUT_SEC * 1000;
|
|
227
238
|
try {
|
|
228
239
|
const startConfig = await loadConfig(runtime.configPath);
|
|
229
240
|
const resolvedStart = resolveDispatchModelRoute(agent, startConfig, runCtx);
|
|
230
241
|
activeRoute = isolation === "worktree"
|
|
231
242
|
? { ...resolvedStart, agent: withWorktreeSystemPrompt(resolvedStart.agent) }
|
|
232
243
|
: resolvedStart;
|
|
233
|
-
activeIdleTimeoutMs = startConfig.idleTimeoutSec * 1000;
|
|
234
244
|
monitor.setModel(runId, activeRoute.agent.model);
|
|
235
245
|
monitor.setThinking(runId, activeRoute.thinkingLevel);
|
|
236
246
|
} catch {
|
|
@@ -339,26 +349,26 @@ export function createBackgroundDispatcher(options: BackgroundDispatcherOptions)
|
|
|
339
349
|
finishRun(
|
|
340
350
|
runId,
|
|
341
351
|
failed ? "failed" : "done",
|
|
342
|
-
modelLevel || dispatchFailed ? { silent: true } : undefined,
|
|
352
|
+
quiet || modelLevel || dispatchFailed ? { silent: true } : undefined,
|
|
343
353
|
);
|
|
344
354
|
runtime.registerRunResult(runId, result);
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
355
|
+
if (!quiet) {
|
|
356
|
+
const block = formatCompletionBlock(result, DEFAULT_MAX_RESULT_LINES, {
|
|
357
|
+
resultRoot: projectResultsRoot(runtime.configPath, result.projectCwd ?? originalCwd),
|
|
358
|
+
});
|
|
359
|
+
const completion: CompletionMessageItem = {
|
|
360
|
+
agent: result.agent,
|
|
361
|
+
block: modelLevel ? `${block}\n\n${modelLevelTakeoverNote(result)}` : block,
|
|
362
|
+
usage: result.usage,
|
|
363
|
+
model: result.model,
|
|
364
|
+
};
|
|
365
|
+
if (modelLevel) {
|
|
366
|
+
const detail = notifyDetail(result.errorMessage, "model unavailable or broken");
|
|
367
|
+
runCtx.ui.notify(`✗ ${result.agent} dispatch failed: ${detail} — task handed to the main window`, "error");
|
|
368
|
+
} else if (dispatchFailed) {
|
|
369
|
+
runCtx.ui.notify(`✗ ${result.agent} dispatch failed: ${notifyDetail(result.errorMessage, "dispatch crashed")}`, "error");
|
|
370
|
+
}
|
|
360
371
|
}
|
|
361
|
-
runtime.publishRunCompletion(runId, completion, failed);
|
|
362
372
|
} finally {
|
|
363
373
|
if (ownsSettlement()) thread.lifecycleOperation = undefined;
|
|
364
374
|
}
|
|
@@ -448,11 +458,12 @@ export function createBackgroundDispatcher(options: BackgroundDispatcherOptions)
|
|
|
448
458
|
runtime.runControllers.delete(runId);
|
|
449
459
|
thread.queueController = undefined;
|
|
450
460
|
if (!runtime.sessionActive || !ownsSettlement()) return;
|
|
461
|
+
if (quiet) return;
|
|
451
462
|
try {
|
|
452
463
|
runCtx.ui.notify(`✗ ${crashed.agent} dispatch failed: ${notifyDetail(crashed.errorMessage, "dispatch crashed")}`, "error");
|
|
453
464
|
runtime.publishRunCompletion(runId, {
|
|
454
465
|
agent: crashed.agent,
|
|
455
|
-
block: formatCompletionBlock(crashed,
|
|
466
|
+
block: formatCompletionBlock(crashed, DEFAULT_MAX_RESULT_LINES, { resultRoot: projectResultsRoot(runtime.configPath, crashed.projectCwd ?? originalCwd) }),
|
|
456
467
|
usage: crashed.usage,
|
|
457
468
|
}, true);
|
|
458
469
|
} catch {
|