@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
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* The `subagent` tool: dispatches
|
|
3
|
-
*
|
|
2
|
+
* The `subagent` tool: dispatches the built-in roles as isolated pi child
|
|
3
|
+
* processes, single or parallel.
|
|
4
4
|
* Owns the public dispatch contract and
|
|
5
5
|
* per-run status tracking. Stable thread generations, final integration, and
|
|
6
6
|
* completion ownership live in thread-lifecycle.ts.
|
|
@@ -11,13 +11,12 @@ import { resolve } from "node:path";
|
|
|
11
11
|
import type { ExtensionAPI, Theme } from "@earendil-works/pi-coding-agent";
|
|
12
12
|
import { Text } from "@earendil-works/pi-tui";
|
|
13
13
|
import { Type } from "typebox";
|
|
14
|
-
import {
|
|
15
|
-
import { loadConfig } from "../configuration/config.ts";
|
|
14
|
+
import { isWriteCapableAgent, loadBuiltinAgents, type AgentConfig, type ToolMetadata } from "./agents.ts";
|
|
15
|
+
import { DEFAULT_MAX_RESULT_LINES, loadConfig } from "../configuration/config.ts";
|
|
16
16
|
import { resolveSubagentConcurrency } from "../execution/background.ts";
|
|
17
17
|
import { formatCompletionBlock, formatUsage } from "../presentation/format.ts";
|
|
18
18
|
import {
|
|
19
19
|
formatTaskSummary,
|
|
20
|
-
formatToolActivity,
|
|
21
20
|
monitor,
|
|
22
21
|
statusIcon,
|
|
23
22
|
statusLabel,
|
|
@@ -35,43 +34,35 @@ import {
|
|
|
35
34
|
type PhaseScopeInput,
|
|
36
35
|
} from "./phase-scope.ts";
|
|
37
36
|
import type { SubagentRuntime, SubagentThread } from "../lifecycle/runtime.ts";
|
|
38
|
-
import {
|
|
37
|
+
import { createDispatchCore, type DispatchCore } from "../lifecycle/dispatch-core.ts";
|
|
39
38
|
import {
|
|
40
|
-
getResultError,
|
|
41
39
|
getResultOutput,
|
|
42
40
|
isFailedResult,
|
|
43
41
|
type SingleResult,
|
|
44
42
|
type SubagentDetails,
|
|
45
|
-
type SubagentLiveEvent,
|
|
46
|
-
type UsageStats,
|
|
47
43
|
} from "../execution/spawn.ts";
|
|
48
44
|
import {
|
|
49
45
|
isWorktreeCapableAgent,
|
|
50
|
-
persistThreadCheckpoint,
|
|
51
46
|
projectResultsRoot,
|
|
52
|
-
runInManagedRepositoryLane,
|
|
53
|
-
type DispatchEnvironment,
|
|
54
47
|
} from "../lifecycle/thread-shared.ts";
|
|
55
48
|
import type { IsolationMode } from "../isolation/worktree.ts";
|
|
56
49
|
|
|
57
|
-
export { isWorktreeCapableAgent, runInManagedRepositoryLane };
|
|
58
|
-
|
|
59
50
|
const NON_BLANK_TASK_OPTIONS = { minLength: 1, pattern: "\\S" } as const;
|
|
60
51
|
|
|
61
52
|
const ISOLATION_DESCRIPTION =
|
|
62
53
|
"Git isolation (not a sandbox): shared uses the caller's checkout; worktree creates a detached temporary worktree for write-capable agents only.";
|
|
63
54
|
|
|
64
|
-
const IsolationSchema = Type.Optional(
|
|
55
|
+
export const IsolationSchema = Type.Optional(
|
|
65
56
|
StringEnum(["shared", "worktree"] as const, { description: ISOLATION_DESCRIPTION }),
|
|
66
57
|
);
|
|
67
58
|
|
|
68
|
-
const PhaseIdSchema = Type.Optional(Type.String({
|
|
59
|
+
export const PhaseIdSchema = Type.Optional(Type.String({
|
|
69
60
|
minLength: 1,
|
|
70
61
|
maxLength: PHASE_ID_MAX_LENGTH,
|
|
71
62
|
pattern: PHASE_ID_PATTERN_SOURCE,
|
|
72
63
|
description: "Stable logical phase id. Reuse it when rewording the same phase; exact task+cwd is the fallback when omitted.",
|
|
73
64
|
}));
|
|
74
|
-
const ScopeSchema = Type.Optional(Type.Object({
|
|
65
|
+
export const ScopeSchema = Type.Optional(Type.Object({
|
|
75
66
|
paths: Type.Optional(Type.Array(Type.String({
|
|
76
67
|
...NON_BLANK_TASK_OPTIONS,
|
|
77
68
|
description: "Exact file or directory write claim resolved from the caller-facing cwd; wildcard * and ? are rejected, while other punctuation is literal.",
|
|
@@ -122,10 +113,8 @@ const SubagentParams = Type.Object({
|
|
|
122
113
|
* worktree-capable agents join them via the live catalog on the execute path. */
|
|
123
114
|
const WORKTREE_DEFAULT_AGENTS = new Set(["artisan"]);
|
|
124
115
|
|
|
125
|
-
/** Resolve the default isolation for a dispatch.
|
|
126
|
-
*
|
|
127
|
-
* honored for write-capable roles only; `shared` always), then the parallel
|
|
128
|
-
* write default — parallel write-capable agents get a detached worktree
|
|
116
|
+
/** Resolve the default isolation for a dispatch. An explicit per-call request
|
|
117
|
+
* wins; otherwise parallel write-capable agents get a detached worktree
|
|
129
118
|
* because shared writers serialize on the repository lane, so defaulting them
|
|
130
119
|
* to shared would turn one parallel batch into a convoy that also parks
|
|
131
120
|
* process slots. */
|
|
@@ -134,11 +123,8 @@ export function defaultIsolationMode(
|
|
|
134
123
|
agentName: string,
|
|
135
124
|
requested?: IsolationMode,
|
|
136
125
|
writeCapable = WORKTREE_DEFAULT_AGENTS.has(agentName),
|
|
137
|
-
declared?: IsolationMode,
|
|
138
126
|
): IsolationMode {
|
|
139
127
|
if (requested) return requested;
|
|
140
|
-
if (declared === "shared") return "shared";
|
|
141
|
-
if (declared === "worktree" && writeCapable) return "worktree";
|
|
142
128
|
return mode === "parallel" && writeCapable ? "worktree" : "shared";
|
|
143
129
|
}
|
|
144
130
|
|
|
@@ -157,6 +143,7 @@ function prepareDispatchTasks(
|
|
|
157
143
|
tasks: ReadonlyArray<{ agent: string; task: string; cwd?: string; phaseId?: string; scope?: PhaseScopeInput; isolation?: IsolationMode }>,
|
|
158
144
|
callerCwd: string,
|
|
159
145
|
agents: readonly AgentConfig[],
|
|
146
|
+
toolInfos?: readonly ToolMetadata[],
|
|
160
147
|
): PreparedDispatchTask[] {
|
|
161
148
|
return tasks.map((item, index) => {
|
|
162
149
|
const cwd = resolve(callerCwd, item.cwd ?? ".");
|
|
@@ -169,7 +156,7 @@ function prepareDispatchTasks(
|
|
|
169
156
|
phaseId: normalizePhaseId(item.phaseId),
|
|
170
157
|
scope: normalizePhaseScope(item.scope, cwd),
|
|
171
158
|
isolation: item.isolation,
|
|
172
|
-
writeCapable: agent ? isWriteCapableAgent(agent) : true,
|
|
159
|
+
writeCapable: agent ? isWriteCapableAgent(agent, toolInfos) : true,
|
|
173
160
|
};
|
|
174
161
|
});
|
|
175
162
|
}
|
|
@@ -247,7 +234,7 @@ function formatResultRow(r: SingleResult, theme: Theme): string {
|
|
|
247
234
|
|
|
248
235
|
/** In-turn wait for a fresh dispatch. Registration resolves it without a model-chosen
|
|
249
236
|
* timer; parent abort or removal ends the wait without losing background delivery. */
|
|
250
|
-
|
|
237
|
+
async function awaitRunResults(
|
|
251
238
|
runtime: SubagentRuntime,
|
|
252
239
|
runIds: number[],
|
|
253
240
|
signal: AbortSignal | undefined,
|
|
@@ -347,98 +334,12 @@ export async function awaitRunResults(
|
|
|
347
334
|
}
|
|
348
335
|
}
|
|
349
336
|
|
|
350
|
-
export function registerSubagentTool(
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
// them. Repeated publication of the same settlement is a no-op.
|
|
357
|
-
const publishedEndedAt = new Map<number, number>();
|
|
358
|
-
const finishRun = (
|
|
359
|
-
runId: number,
|
|
360
|
-
status: "done" | "failed",
|
|
361
|
-
opts?: { silent?: boolean },
|
|
362
|
-
): void => {
|
|
363
|
-
const run = monitor.findRun(runId);
|
|
364
|
-
if (!run) return;
|
|
365
|
-
monitor.setStatus(runId, status); // stamps endedAt for the elapsed time
|
|
366
|
-
const endedAt = monitor.findRun(runId)?.endedAt;
|
|
367
|
-
if (endedAt !== undefined && publishedEndedAt.get(runId) === endedAt) return;
|
|
368
|
-
if (endedAt !== undefined) publishedEndedAt.set(runId, endedAt);
|
|
369
|
-
if (opts?.silent || !runtime.sessionActive) return;
|
|
370
|
-
const icon = status === "done" ? "✓" : "✗";
|
|
371
|
-
const result = runtime.threads.get(runId)?.lastResult;
|
|
372
|
-
const error = status === "failed" ? result ? getResultError(result) : "No failure reason was recorded." : undefined;
|
|
373
|
-
environmentRef.current?.ctx.ui.notify(
|
|
374
|
-
`${icon} #${run.id} ${monitor.summarize(run)}${error ? ` · ${formatTaskSummary(error, 300, false)}` : ""}`,
|
|
375
|
-
status === "done" ? "info" : "error",
|
|
376
|
-
);
|
|
377
|
-
};
|
|
378
|
-
|
|
379
|
-
// Live sub-agent activity → concise one-line status ("thinking",
|
|
380
|
-
// "read src/index.ts", ...), never a raw args blob. The live handler
|
|
381
|
-
// only updates monitor state; the queue task owns terminal removal,
|
|
382
|
-
// notification, and lifecycle decisions.
|
|
383
|
-
const makeLiveHandler = (runId: number, generation?: number) => {
|
|
384
|
-
// Every child turn reports "running"; the manifest is rewritten only when
|
|
385
|
-
// what it records for recovery (session path, child pids) actually changed.
|
|
386
|
-
let checkpointKey: string | undefined;
|
|
387
|
-
return (e: SubagentLiveEvent): void => {
|
|
388
|
-
if (generation !== undefined && runtime.threads.get(runId)?.generation !== generation) return;
|
|
389
|
-
switch (e.kind) {
|
|
390
|
-
case "status":
|
|
391
|
-
monitor.setStatus(runId, e.status);
|
|
392
|
-
// A fresh running segment refreshes the durable checkpoint (session
|
|
393
|
-
// path plus child pids) so a crash mid-generation still restores.
|
|
394
|
-
if (e.status === "running") {
|
|
395
|
-
const thread = runtime.threads.get(runId);
|
|
396
|
-
if (thread?.sessionId && thread.sessionDir) {
|
|
397
|
-
const key = `${thread.sessionDir}\0${thread.control.getChildPids().join(",")}`;
|
|
398
|
-
if (key !== checkpointKey) {
|
|
399
|
-
checkpointKey = key;
|
|
400
|
-
persistThreadCheckpoint(runtime, thread, "parked");
|
|
401
|
-
}
|
|
402
|
-
}
|
|
403
|
-
}
|
|
404
|
-
break;
|
|
405
|
-
case "model":
|
|
406
|
-
monitor.setModel(runId, e.model, e.fallbackFrom);
|
|
407
|
-
monitor.setThinking(runId, e.thinking);
|
|
408
|
-
break;
|
|
409
|
-
case "usage":
|
|
410
|
-
monitor.setUsage(runId, e.usage, e.model);
|
|
411
|
-
break;
|
|
412
|
-
case "session": {
|
|
413
|
-
runtime.retainSession({ sessionDir: e.sessionDir });
|
|
414
|
-
const thread = runtime.threads.get(runId);
|
|
415
|
-
if (thread && (generation === undefined || runtime.threads.get(runId)?.generation === generation)) {
|
|
416
|
-
thread.sessionId = e.sessionId;
|
|
417
|
-
thread.sessionDir = e.sessionDir;
|
|
418
|
-
persistThreadCheckpoint(runtime, thread, "parked");
|
|
419
|
-
}
|
|
420
|
-
break;
|
|
421
|
-
}
|
|
422
|
-
case "tool_start":
|
|
423
|
-
monitor.recordToolStart(runId, e.toolName, formatToolActivity(e.toolName, e.args));
|
|
424
|
-
break;
|
|
425
|
-
case "tool_end":
|
|
426
|
-
monitor.recordToolEnd(runId, e.toolName, e.isError);
|
|
427
|
-
break;
|
|
428
|
-
case "thinking":
|
|
429
|
-
monitor.setActivity(runId, "thinking");
|
|
430
|
-
break;
|
|
431
|
-
case "text":
|
|
432
|
-
// A text delta is model output, not a filesystem write.
|
|
433
|
-
monitor.setActivity(runId, "responding");
|
|
434
|
-
break;
|
|
435
|
-
}
|
|
436
|
-
};
|
|
437
|
-
};
|
|
438
|
-
|
|
439
|
-
const makeDetails =
|
|
440
|
-
(mode: "single" | "parallel", background = false) =>
|
|
441
|
-
(results: SingleResult[]): SubagentDetails => ({ mode, results, background });
|
|
337
|
+
export function registerSubagentTool(
|
|
338
|
+
pi: ExtensionAPI,
|
|
339
|
+
runtime: SubagentRuntime,
|
|
340
|
+
core: DispatchCore = createDispatchCore(runtime),
|
|
341
|
+
): void {
|
|
342
|
+
const { startBackground, makeDetails } = core;
|
|
442
343
|
|
|
443
344
|
const phaseLeaseReceipt = (
|
|
444
345
|
runIds: number[],
|
|
@@ -480,23 +381,10 @@ export function registerSubagentTool(pi: ExtensionAPI, runtime: SubagentRuntime)
|
|
|
480
381
|
return ` Pacing: ${parts.join(" · ")}.`;
|
|
481
382
|
};
|
|
482
383
|
|
|
483
|
-
const startBackground = createBackgroundDispatcher({
|
|
484
|
-
runtime,
|
|
485
|
-
getEnvironment: () => {
|
|
486
|
-
if (!environmentRef.current) {
|
|
487
|
-
throw new Error("pi-subagents dispatch environment is not ready yet.");
|
|
488
|
-
}
|
|
489
|
-
return environmentRef.current;
|
|
490
|
-
},
|
|
491
|
-
finishRun,
|
|
492
|
-
makeLiveHandler,
|
|
493
|
-
makeDetails,
|
|
494
|
-
});
|
|
495
|
-
|
|
496
384
|
pi.registerTool({
|
|
497
385
|
name: "subagent",
|
|
498
386
|
label: "Subagent",
|
|
499
|
-
description: "Start one-shot leaf runs for
|
|
387
|
+
description: "Start one-shot leaf runs for delegated phases: independent work in parallel, or one bounded job that can be briefed self-contained. Duplicate phases and declared writer overlaps are rejected before allocation; scope does not prove independence or grant permissions. Parallel tasks without scope report `independence not verified`. Results arrive automatically, or in-turn with wait:true. Main handles incomplete work.",
|
|
500
388
|
// Declared to the model, never callable from codemode scripts. Dispatch shares
|
|
501
389
|
// the in-memory lease table, so a batch that includes it runs one tool at a time.
|
|
502
390
|
exposure: "model-only",
|
|
@@ -522,15 +410,12 @@ export function registerSubagentTool(pi: ExtensionAPI, runtime: SubagentRuntime)
|
|
|
522
410
|
await runtime.durableRestore;
|
|
523
411
|
monitor.beginTurn();
|
|
524
412
|
const config = await loadConfig(runtime.configPath);
|
|
525
|
-
runtime.backgroundQueue.setConcurrency(
|
|
526
|
-
|
|
527
|
-
|
|
528
|
-
|
|
529
|
-
|
|
530
|
-
|
|
531
|
-
});
|
|
532
|
-
const agents = discovery.agents;
|
|
533
|
-
environmentRef.current = { ctx, config, agents };
|
|
413
|
+
runtime.backgroundQueue.setConcurrency(resolveSubagentConcurrency());
|
|
414
|
+
const agents = loadBuiltinAgents();
|
|
415
|
+
// One admission snapshot: role boundaries and writer capability must
|
|
416
|
+
// describe the same catalog the batch is validated against.
|
|
417
|
+
const toolInfos = runtime.getToolInfos();
|
|
418
|
+
core.setEnvironment({ ctx, config, agents });
|
|
534
419
|
|
|
535
420
|
const hasTasks = (params.tasks?.length ?? 0) > 0;
|
|
536
421
|
const hasSingle = Boolean(params.agent) && params.task !== undefined;
|
|
@@ -581,7 +466,7 @@ export function registerSubagentTool(pi: ExtensionAPI, runtime: SubagentRuntime)
|
|
|
581
466
|
if (params.tasks && params.tasks.length > 0) {
|
|
582
467
|
let prepared: PreparedDispatchTask[];
|
|
583
468
|
try {
|
|
584
|
-
prepared = prepareDispatchTasks(params.tasks, ctx.cwd, agents);
|
|
469
|
+
prepared = prepareDispatchTasks(params.tasks, ctx.cwd, agents, toolInfos);
|
|
585
470
|
} catch (error) {
|
|
586
471
|
throw new Error(`Parallel admission rejected: ${error instanceof Error ? error.message : String(error)} No background tasks were started.`);
|
|
587
472
|
}
|
|
@@ -603,8 +488,7 @@ export function registerSubagentTool(pi: ExtensionAPI, runtime: SubagentRuntime)
|
|
|
603
488
|
"parallel",
|
|
604
489
|
item.agent,
|
|
605
490
|
item.isolation,
|
|
606
|
-
catalogAgent ? isWorktreeCapableAgent(catalogAgent) : undefined,
|
|
607
|
-
catalogAgent?.isolation,
|
|
491
|
+
catalogAgent ? isWorktreeCapableAgent(catalogAgent, toolInfos) : undefined,
|
|
608
492
|
),
|
|
609
493
|
{
|
|
610
494
|
deliveryRoute: params.wait ? "await" : "background",
|
|
@@ -633,7 +517,7 @@ export function registerSubagentTool(pi: ExtensionAPI, runtime: SubagentRuntime)
|
|
|
633
517
|
throw new Error(`No subagents started.\n${failureLines.join("\n")}`);
|
|
634
518
|
}
|
|
635
519
|
if (params.wait) {
|
|
636
|
-
const blocks = await awaitRunResults(runtime, startedIds, signal,
|
|
520
|
+
const blocks = await awaitRunResults(runtime, startedIds, signal, DEFAULT_MAX_RESULT_LINES, ctx.cwd, makeProgress(makeDetails("parallel", true)(results)));
|
|
637
521
|
if (signal?.aborted) runtime.fallbackAwaitDelivery(startedIds);
|
|
638
522
|
else runtime.completeAwaitDelivery(startedIds);
|
|
639
523
|
const resultText = failureLines.length > 0
|
|
@@ -664,7 +548,7 @@ export function registerSubagentTool(pi: ExtensionAPI, runtime: SubagentRuntime)
|
|
|
664
548
|
phaseId: params.phaseId,
|
|
665
549
|
scope: params.scope,
|
|
666
550
|
isolation: params.isolation as IsolationMode | undefined,
|
|
667
|
-
}], ctx.cwd, agents)[0]!;
|
|
551
|
+
}], ctx.cwd, agents, toolInfos)[0]!;
|
|
668
552
|
} catch (error) {
|
|
669
553
|
throw new Error(`Dispatch admission rejected: ${error instanceof Error ? error.message : String(error)}`);
|
|
670
554
|
}
|
|
@@ -677,8 +561,7 @@ export function registerSubagentTool(pi: ExtensionAPI, runtime: SubagentRuntime)
|
|
|
677
561
|
"single",
|
|
678
562
|
single.agent,
|
|
679
563
|
single.isolation,
|
|
680
|
-
singleCatalogAgent ? isWorktreeCapableAgent(singleCatalogAgent) : undefined,
|
|
681
|
-
singleCatalogAgent?.isolation,
|
|
564
|
+
singleCatalogAgent ? isWorktreeCapableAgent(singleCatalogAgent, toolInfos) : undefined,
|
|
682
565
|
),
|
|
683
566
|
{
|
|
684
567
|
deliveryRoute: params.wait ? "await" : "background",
|
|
@@ -691,7 +574,7 @@ export function registerSubagentTool(pi: ExtensionAPI, runtime: SubagentRuntime)
|
|
|
691
574
|
throw new Error(getResultOutput(result));
|
|
692
575
|
}
|
|
693
576
|
if (params.wait && result.runId !== undefined) {
|
|
694
|
-
const blocks = await awaitRunResults(runtime, [result.runId], signal,
|
|
577
|
+
const blocks = await awaitRunResults(runtime, [result.runId], signal, DEFAULT_MAX_RESULT_LINES, ctx.cwd, makeProgress(makeDetails("single", true)([result])));
|
|
695
578
|
if (signal?.aborted) runtime.fallbackAwaitDelivery([result.runId]);
|
|
696
579
|
else runtime.completeAwaitDelivery([result.runId]);
|
|
697
580
|
return {
|
package/src/delegation/prompt.ts
CHANGED
|
@@ -142,14 +142,14 @@ function preferredRoleUse(agents: readonly AgentConfig[]): string | undefined {
|
|
|
142
142
|
// The catalog above already carries each role's full description; this line
|
|
143
143
|
// adds only the routing preference and the boundary that most often misroutes.
|
|
144
144
|
if (names.has("scout")) {
|
|
145
|
-
uses.push("`scout` for read-only lookups (no shell — commands, tests, and builds stay in main)");
|
|
145
|
+
uses.push("`scout` for read-only lookups (read-only tools, no shell — commands, tests, and builds stay in main)");
|
|
146
146
|
}
|
|
147
147
|
if (names.has("artisan")) {
|
|
148
148
|
uses.push("`artisan` for one substantial change with its checks");
|
|
149
149
|
}
|
|
150
150
|
if (uses.length === 0) return undefined;
|
|
151
151
|
const preference = uses.length === 1 ? `Prefer ${uses[0]}` : `Prefer ${uses[0]}, and ${uses[1]}`;
|
|
152
|
-
return `${preference}. Keep a small edit already understood in the current context in main. Do not open a phase that repeats owned work, splits one tightly coupled change, or exists only to fill a free slot.`;
|
|
152
|
+
return `${preference}. Route broad or unfamiliar lookups to a child instead of running the same searches serially in main. Keep a small edit already understood in the current context in main. Do not open a phase that repeats owned work, splits one tightly coupled change, or exists only to fill a free slot.`;
|
|
153
153
|
}
|
|
154
154
|
|
|
155
155
|
function delegationBody(agents: AgentConfig[]): string {
|
|
@@ -158,9 +158,11 @@ function delegationBody(agents: AgentConfig[]): string {
|
|
|
158
158
|
|
|
159
159
|
const dispatchRules = [
|
|
160
160
|
"The user's task sets the outcome. If it conflicts with this section, follow the task. Admission still rejects duplicate phases and overlapping writers.",
|
|
161
|
-
"
|
|
161
|
+
"Delegate whenever the work has independent parts or a bounded job can be briefed self-contained: parallel phases usually beat a serialized main, and a child with a fresh context is often cheaper than growing yours. Keep in main the edit that needs your conversation context or is too small to brief.",
|
|
162
162
|
...(preferred ? [preferred] : []),
|
|
163
|
+
"Children inherit this session's live tool surface: a role without an allowlist gets everything you have, including `codemode`, and a read-only role keeps only the tools the host proves read-only. Do not plan a phase that needs a tool its role cannot reach.",
|
|
163
164
|
"Give each phase one owner, a stable `phaseId`, and exact writer `scope`. Parallelize independent phases in one call; never overlap writers or duplicate an owned phase. Dependent phases wait for prerequisites. Scope is conflict metadata, not permissions or a sandbox.",
|
|
165
|
+
"When the request is one deliverable spanning ordered phases (survey, then independent changes, then a single gate), declare the graph once with `subagent_workflow` instead of dispatching wave after wave: the runtime starts each node the moment its prerequisites settle and sends one summary when the graph does. Saved graphs under `.pi/workflows/` run by name.",
|
|
164
166
|
"Children have no parent conversation; send a self-contained brief and reuse established evidence.",
|
|
165
167
|
"One-shot runs return once. Main takes over failed or incomplete work from partial edits and artifacts; a different deliverable needs a new phase.",
|
|
166
168
|
"Use `wait: true` for an immediate dependency or one-shot session; otherwise continue disjoint work and end your turn when none remains — completions arrive automatically and wake you; do not poll or sleep to wait. Conclude the overall task only after every run settles or is stopped.",
|
|
@@ -177,13 +179,13 @@ ${bullets(dispatchRules)}`;
|
|
|
177
179
|
}
|
|
178
180
|
|
|
179
181
|
/** Routing contract without live leases. Empty when no role is enabled and no lease forces the catalog. */
|
|
180
|
-
|
|
182
|
+
function buildStableDelegationSection(agents: AgentConfig[], includeEmptyCatalog = false): string {
|
|
181
183
|
if (agents.length === 0 && !includeEmptyCatalog) return "";
|
|
182
184
|
return delegationBody(agents);
|
|
183
185
|
}
|
|
184
186
|
|
|
185
187
|
/** Active-lease block. Empty when nothing is queued, running, or settling. */
|
|
186
|
-
|
|
188
|
+
function buildActiveLeaseSection(sources: Iterable<PhaseLeaseSource>): string {
|
|
187
189
|
const activeLeases = formatActivePhaseLeases(sources);
|
|
188
190
|
if (!activeLeases) return "";
|
|
189
191
|
return `Active phase leases:\n${activeLeases}`;
|
|
@@ -106,13 +106,17 @@ export class RpcRunControl {
|
|
|
106
106
|
private stopRequested = false;
|
|
107
107
|
private stopMessage = "Subagent was aborted";
|
|
108
108
|
private childPids = new Set<number>();
|
|
109
|
+
readonly generation: number;
|
|
110
|
+
private readonly onPhase?: (phase: RpcControlPhase) => void;
|
|
109
111
|
|
|
110
112
|
constructor(
|
|
111
113
|
objective: string,
|
|
112
|
-
|
|
113
|
-
|
|
114
|
+
generation: number,
|
|
115
|
+
onPhase?: (phase: RpcControlPhase) => void,
|
|
114
116
|
) {
|
|
115
117
|
this.objective = objective;
|
|
118
|
+
this.generation = generation;
|
|
119
|
+
this.onPhase = onPhase;
|
|
116
120
|
}
|
|
117
121
|
|
|
118
122
|
getObjective(): string {
|
package/src/execution/rpc-run.ts
CHANGED
|
@@ -28,19 +28,19 @@ import {
|
|
|
28
28
|
type SubagentLiveEvent,
|
|
29
29
|
} from "./rpc-control.ts";
|
|
30
30
|
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
31
|
+
const DEPTH_ENV_VAR = "PI_SUBAGENT_DEPTH";
|
|
32
|
+
/** Every tool of an MCP server shares this prefix, whatever its exposure. */
|
|
33
|
+
const MCP_TOOL_PREFIX = "mcp__";
|
|
34
|
+
const SUBAGENT_KILL_GRACE_MS = 5_000;
|
|
35
35
|
/** ACK budget after the child is known to be reading RPC. */
|
|
36
|
-
|
|
36
|
+
const RPC_COMMAND_TIMEOUT_MS = 30_000;
|
|
37
37
|
|
|
38
38
|
/** clear_queue is stop-path hygiene ahead of the abort: give it its own short
|
|
39
39
|
* budget so a hung response cannot eat into the abort-settle window. */
|
|
40
40
|
const RPC_CLEAR_QUEUE_TIMEOUT_MS = 2_000;
|
|
41
41
|
/** Time allowed for the child to boot and answer get_state. */
|
|
42
|
-
|
|
43
|
-
|
|
42
|
+
const RPC_READY_TIMEOUT_MS = 60_000;
|
|
43
|
+
const RPC_ABORT_SETTLE_TIMEOUT_MS = 5_000;
|
|
44
44
|
/** Retained stderr tail. A chatty or crash-looping child must not grow parent
|
|
45
45
|
* memory without bound, and the tail carries the decisive diagnostic. */
|
|
46
46
|
export const RPC_STDERR_MAX_CHARS = 32_000;
|
|
@@ -88,7 +88,7 @@ export function sessionExists(sessionDir: string, sessionId: string): boolean {
|
|
|
88
88
|
}
|
|
89
89
|
|
|
90
90
|
/** Resolve how to invoke the same pi build as the current process. */
|
|
91
|
-
|
|
91
|
+
function getPiInvocation(args: string[]): { command: string; args: string[] } {
|
|
92
92
|
const currentScript = process.argv[1];
|
|
93
93
|
const isBunVirtualScript = currentScript?.startsWith("/$bunfs/root/");
|
|
94
94
|
if (currentScript && !isBunVirtualScript && existsSync(currentScript)) {
|
|
@@ -100,7 +100,7 @@ export function getPiInvocation(args: string[]): { command: string; args: string
|
|
|
100
100
|
return { command: "pi", args };
|
|
101
101
|
}
|
|
102
102
|
|
|
103
|
-
|
|
103
|
+
function extractToolErrorText(content: unknown): string {
|
|
104
104
|
const parts = Array.isArray(content) ? content : [];
|
|
105
105
|
const text = parts
|
|
106
106
|
.filter(
|
|
@@ -161,7 +161,7 @@ export function renderChildRetryPolicySource(modelRef?: string): string {
|
|
|
161
161
|
* stream adapter with its registered API implementation while forcing
|
|
162
162
|
* maxRetries=0. It uses Pi's public extension and pi-ai compatibility APIs, so
|
|
163
163
|
* it works in Node and standalone/Bun builds without touching user settings. */
|
|
164
|
-
|
|
164
|
+
async function writeChildRetryPolicyExtension(
|
|
165
165
|
scratchRoot: string,
|
|
166
166
|
modelRef?: string,
|
|
167
167
|
): Promise<ChildRetryPolicyExtension> {
|
|
@@ -181,7 +181,7 @@ export async function writeChildRetryPolicyExtension(
|
|
|
181
181
|
|
|
182
182
|
/** Hand the agent body to the child as a file rather than inline argv text.
|
|
183
183
|
* `--append-system-prompt` takes either, but a system prompt is unbounded — a
|
|
184
|
-
*
|
|
184
|
+
* role can carry a whole spec — while Windows caps a command line at
|
|
185
185
|
* 32767 characters, so inlining turns a long agent into an opaque spawn failure.
|
|
186
186
|
* The file lives in the run's scratch dir and is removed when the attempt ends. */
|
|
187
187
|
async function writePromptToTempFile(
|
|
@@ -288,36 +288,76 @@ export interface RunRpcAttemptOptions {
|
|
|
288
288
|
rpcCommandTimeoutMs?: number;
|
|
289
289
|
}
|
|
290
290
|
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
291
|
+
export interface ChildLaunchOptions {
|
|
292
|
+
agent: Pick<AgentConfig, "model" | "tools">;
|
|
293
|
+
thinkingLevel: ThinkingLevel;
|
|
294
|
+
sessionDir?: string;
|
|
295
|
+
sessionId?: string;
|
|
296
|
+
/** The session directory already holds the session being resumed. */
|
|
297
|
+
resumeExistingSession?: boolean;
|
|
298
|
+
/** Appended system prompt file, when the role carries one. */
|
|
299
|
+
promptPath?: string;
|
|
300
|
+
retryPolicyPath: string;
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
/** Command line for one child attempt.
|
|
304
|
+
*
|
|
305
|
+
* An explicit role list is a strict intersection of the parent's tools, but pi
|
|
306
|
+
* keeps MCP tools unless a `--tools` entry names one, so a list that names none
|
|
307
|
+
* has to exclude them by pattern. Scout depends on that: its read-only boundary
|
|
308
|
+
* must not leak an MCP writer. */
|
|
309
|
+
export function buildChildLaunchArgs(options: ChildLaunchOptions): string[] {
|
|
310
|
+
const { agent, thinkingLevel } = options;
|
|
311
|
+
const excludedTools: string[] = [...SUBAGENT_TOOL_NAMES];
|
|
312
|
+
const args: string[] = ["--mode", "rpc"];
|
|
295
313
|
if (options.sessionDir && options.sessionId) {
|
|
296
314
|
args.push("--session-dir", options.sessionDir);
|
|
297
|
-
args.push(
|
|
315
|
+
args.push(options.resumeExistingSession ? "--session" : "--session-id", options.sessionId);
|
|
298
316
|
} else {
|
|
299
317
|
args.push("--no-session");
|
|
300
318
|
}
|
|
301
319
|
if (agent.model) args.push("--model", agent.model);
|
|
302
320
|
args.push("--thinking", thinkingLevel);
|
|
303
321
|
if (agent.tools) {
|
|
304
|
-
if (agent.tools.length > 0)
|
|
305
|
-
|
|
322
|
+
if (agent.tools.length > 0) {
|
|
323
|
+
args.push("--tools", agent.tools.join(","));
|
|
324
|
+
if (!agent.tools.some((tool) => tool.startsWith(MCP_TOOL_PREFIX))) excludedTools.push(`${MCP_TOOL_PREFIX}*`);
|
|
325
|
+
} else {
|
|
326
|
+
args.push("--no-tools");
|
|
327
|
+
}
|
|
306
328
|
}
|
|
329
|
+
args.push("--exclude-tools", excludedTools.join(","));
|
|
330
|
+
if (options.promptPath) args.push("--append-system-prompt", options.promptPath);
|
|
331
|
+
args.push("--extension", options.retryPolicyPath);
|
|
332
|
+
return args;
|
|
333
|
+
}
|
|
307
334
|
|
|
335
|
+
/** Run one persistent RPC child until a stable `agent_settled` or control action. */
|
|
336
|
+
export async function runRpcAgentAttempt(options: RunRpcAttemptOptions): Promise<RpcSingleResult> {
|
|
337
|
+
const { agent, agentName, task, thinkingLevel, idleTimeoutMs, signal, onLive, control } = options;
|
|
308
338
|
let tmpPromptDir: string | null = null;
|
|
309
339
|
let tmpPromptPath: string | null = null;
|
|
310
340
|
if (agent.systemPrompt.trim()) {
|
|
311
341
|
const tmp = await writePromptToTempFile(options.scratchRoot, agent.name, agent.systemPrompt);
|
|
312
342
|
tmpPromptDir = tmp.dir;
|
|
313
343
|
tmpPromptPath = tmp.filePath;
|
|
314
|
-
args.push("--append-system-prompt", tmpPromptPath);
|
|
315
344
|
}
|
|
316
345
|
|
|
317
346
|
let retryPolicy: ChildRetryPolicyExtension;
|
|
347
|
+
let args: string[];
|
|
318
348
|
try {
|
|
319
349
|
retryPolicy = await writeChildRetryPolicyExtension(options.scratchRoot, agent.model);
|
|
320
|
-
args
|
|
350
|
+
args = buildChildLaunchArgs({
|
|
351
|
+
agent,
|
|
352
|
+
thinkingLevel,
|
|
353
|
+
sessionDir: options.sessionDir,
|
|
354
|
+
sessionId: options.sessionId,
|
|
355
|
+
resumeExistingSession: Boolean(
|
|
356
|
+
options.sessionDir && options.sessionId && sessionExists(options.sessionDir, options.sessionId),
|
|
357
|
+
),
|
|
358
|
+
promptPath: tmpPromptPath ?? undefined,
|
|
359
|
+
retryPolicyPath: retryPolicy.filePath,
|
|
360
|
+
});
|
|
321
361
|
} catch (error) {
|
|
322
362
|
if (tmpPromptDir) await rm(tmpPromptDir, { recursive: true, force: true }).catch(() => undefined);
|
|
323
363
|
throw error;
|