@ferris1225/pi-subagents 4.3.30 → 4.3.32
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 +62 -0
- package/LICENSE +1 -1
- package/README.md +129 -265
- package/index.ts +5 -13
- package/package.json +5 -10
- package/src/configuration/config.ts +17 -125
- package/src/configuration/models.ts +1 -1
- package/src/configuration/setup.ts +90 -188
- package/src/configuration/ui.ts +28 -66
- package/src/delegation/agents.ts +78 -209
- package/src/delegation/builtin-agents.ts +60 -0
- package/src/delegation/dispatch.ts +21 -34
- package/src/delegation/prompt.ts +6 -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/durable.ts +3 -3
- package/src/lifecycle/runtime.ts +6 -1
- package/src/lifecycle/thread-lifecycle.ts +11 -8
- package/src/lifecycle/thread-shared.ts +4 -4
- package/src/lifecycle/tools.ts +2 -5
- package/src/presentation/announcements.ts +2 -4
- package/src/presentation/monitor.ts +22 -16
- package/src/presentation/widget.ts +2 -2
- package/agents/artisan.md +0 -18
- package/agents/scout.md +0 -19
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;
|
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
|
};
|
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";
|
|
@@ -76,6 +76,10 @@ export interface SubagentRuntime {
|
|
|
76
76
|
backgroundQueue: BackgroundTaskQueue;
|
|
77
77
|
/** Live parent tool names from ExtensionAPI, read again for each child launch. */
|
|
78
78
|
getActiveTools: () => string[];
|
|
79
|
+
/** Live metadata for the registered tools, read again for each child launch.
|
|
80
|
+
* Read-only role policy and write capability come from it, never from a
|
|
81
|
+
* hardcoded list of extension or MCP tool names. */
|
|
82
|
+
getToolInfos: () => ToolInfo[];
|
|
79
83
|
/** False after session_shutdown; guards delivery and queue work. */
|
|
80
84
|
sessionActive: boolean;
|
|
81
85
|
/** Resolves when the load-time durable restore pass has finished. Everything
|
|
@@ -137,6 +141,7 @@ export function createRuntime(pi: ExtensionAPI, configPath: string): SubagentRun
|
|
|
137
141
|
configPath,
|
|
138
142
|
backgroundQueue,
|
|
139
143
|
getActiveTools: () => pi.getActiveTools(),
|
|
144
|
+
getToolInfos: () => pi.getAllTools(),
|
|
140
145
|
sessionActive: true,
|
|
141
146
|
durableRestore: Promise.resolve(),
|
|
142
147
|
restoredRunIds: [],
|
|
@@ -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,8 @@ 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
|
-
if (isolation === "worktree" && !isWorktreeCapableAgent(agent)) {
|
|
115
|
+
const writeCapable = Boolean(startOptions.writeCapable) || isWriteCapableAgent(agent, toolInfos);
|
|
116
|
+
if (isolation === "worktree" && !isWorktreeCapableAgent(agent, toolInfos)) {
|
|
113
117
|
return {
|
|
114
118
|
...failedStartResult(agentName, task, `Agent "${agentName}" is read-only; worktree isolation is available only to write-capable agents such as artisan.`),
|
|
115
119
|
isolation,
|
|
@@ -223,14 +227,13 @@ export function createBackgroundDispatcher(options: BackgroundDispatcherOptions)
|
|
|
223
227
|
// queued behind the concurrency limit. Re-resolve the route at actual
|
|
224
228
|
// start so /subagents-setup edits apply to not-yet-started runs.
|
|
225
229
|
let activeRoute = route;
|
|
226
|
-
|
|
230
|
+
const activeIdleTimeoutMs = DEFAULT_IDLE_TIMEOUT_SEC * 1000;
|
|
227
231
|
try {
|
|
228
232
|
const startConfig = await loadConfig(runtime.configPath);
|
|
229
233
|
const resolvedStart = resolveDispatchModelRoute(agent, startConfig, runCtx);
|
|
230
234
|
activeRoute = isolation === "worktree"
|
|
231
235
|
? { ...resolvedStart, agent: withWorktreeSystemPrompt(resolvedStart.agent) }
|
|
232
236
|
: resolvedStart;
|
|
233
|
-
activeIdleTimeoutMs = startConfig.idleTimeoutSec * 1000;
|
|
234
237
|
monitor.setModel(runId, activeRoute.agent.model);
|
|
235
238
|
monitor.setThinking(runId, activeRoute.thinkingLevel);
|
|
236
239
|
} catch {
|
|
@@ -343,7 +346,7 @@ export function createBackgroundDispatcher(options: BackgroundDispatcherOptions)
|
|
|
343
346
|
);
|
|
344
347
|
runtime.registerRunResult(runId, result);
|
|
345
348
|
|
|
346
|
-
const block = formatCompletionBlock(result,
|
|
349
|
+
const block = formatCompletionBlock(result, DEFAULT_MAX_RESULT_LINES, {
|
|
347
350
|
resultRoot: projectResultsRoot(runtime.configPath, result.projectCwd ?? originalCwd),
|
|
348
351
|
});
|
|
349
352
|
const completion: CompletionMessageItem = {
|
|
@@ -452,7 +455,7 @@ export function createBackgroundDispatcher(options: BackgroundDispatcherOptions)
|
|
|
452
455
|
runCtx.ui.notify(`✗ ${crashed.agent} dispatch failed: ${notifyDetail(crashed.errorMessage, "dispatch crashed")}`, "error");
|
|
453
456
|
runtime.publishRunCompletion(runId, {
|
|
454
457
|
agent: crashed.agent,
|
|
455
|
-
block: formatCompletionBlock(crashed,
|
|
458
|
+
block: formatCompletionBlock(crashed, DEFAULT_MAX_RESULT_LINES, { resultRoot: projectResultsRoot(runtime.configPath, crashed.projectCwd ?? originalCwd) }),
|
|
456
459
|
usage: crashed.usage,
|
|
457
460
|
}, true);
|
|
458
461
|
} catch {
|
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
import { realpath } from "node:fs/promises";
|
|
4
4
|
import { join, resolve } from "node:path";
|
|
5
5
|
import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
|
|
6
|
-
import { isWriteCapableAgent, type AgentConfig } from "../delegation/agents.ts";
|
|
6
|
+
import { isWriteCapableAgent, type AgentConfig, type ToolMetadata } from "../delegation/agents.ts";
|
|
7
7
|
import type { PhaseScope } from "../delegation/phase-scope.ts";
|
|
8
8
|
import { roleThinkingLevel, type SubagentsConfig, type ThinkingLevel } from "../configuration/config.ts";
|
|
9
9
|
import { removeThreadRecord, threadRecordFromThread, upsertThreadRecord } from "./durable.ts";
|
|
@@ -138,8 +138,8 @@ export function withWorktreeSystemPrompt(agent: AgentConfig): AgentConfig {
|
|
|
138
138
|
}
|
|
139
139
|
|
|
140
140
|
/** Only write-capable agents can run in an isolated worktree. */
|
|
141
|
-
export function isWorktreeCapableAgent(agent: AgentConfig): boolean {
|
|
142
|
-
return isWriteCapableAgent(agent);
|
|
141
|
+
export function isWorktreeCapableAgent(agent: AgentConfig, toolInfos?: readonly ToolMetadata[]): boolean {
|
|
142
|
+
return isWriteCapableAgent(agent, toolInfos);
|
|
143
143
|
}
|
|
144
144
|
|
|
145
145
|
export interface DispatchEnvironment {
|
|
@@ -191,7 +191,7 @@ export function resolveDispatchModelRoute(
|
|
|
191
191
|
availableRefs: availableModels.map(modelRef),
|
|
192
192
|
});
|
|
193
193
|
// A `/subagents-setup` override wins; otherwise the role default. No
|
|
194
|
-
// per-call
|
|
194
|
+
// per-call thinking.
|
|
195
195
|
const preferred =
|
|
196
196
|
config.agentThinkingLevels[agent.name] ?? roleThinkingLevel(agent.name);
|
|
197
197
|
const thinkingLevelForModel = (ref?: string): ThinkingLevel => {
|
package/src/lifecycle/tools.ts
CHANGED
|
@@ -4,7 +4,7 @@ import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
|
|
|
4
4
|
import { Text } from "@earendil-works/pi-tui";
|
|
5
5
|
import { existsSync } from "node:fs";
|
|
6
6
|
import { Type } from "typebox";
|
|
7
|
-
import { DEFAULT_MAX_RESULT_LINES
|
|
7
|
+
import { DEFAULT_MAX_RESULT_LINES } from "../configuration/config.ts";
|
|
8
8
|
import { removeThreadRecord } from "./durable.ts";
|
|
9
9
|
import { formatCompletionBlock, matchRunIds } from "../presentation/format.ts";
|
|
10
10
|
import { emptyUsage } from "../execution/rpc-control.ts";
|
|
@@ -146,8 +146,6 @@ export function registerLookupTools(pi: ExtensionAPI, runtime: SubagentRuntime):
|
|
|
146
146
|
|
|
147
147
|
async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
|
|
148
148
|
await runtime.durableRestore;
|
|
149
|
-
// Claim every target before awaiting process cleanup or configuration I/O.
|
|
150
|
-
const configPromise = loadConfig(runtime.configPath).catch(() => undefined);
|
|
151
149
|
const completionResults: SingleResult[] = [];
|
|
152
150
|
const candidateIds = params.all === true
|
|
153
151
|
? [...new Set([
|
|
@@ -331,10 +329,9 @@ export function registerLookupTools(pi: ExtensionAPI, runtime: SubagentRuntime):
|
|
|
331
329
|
stopped.push(`#${runId} ${thread.agentName}${wasQueued ? " (queued)" : wasActive ? "" : ` (${previousState})`}`);
|
|
332
330
|
}
|
|
333
331
|
if (completionResults.length > 0) {
|
|
334
|
-
const maxResultLines = (await configPromise)?.maxResultLines ?? DEFAULT_MAX_RESULT_LINES;
|
|
335
332
|
runtime.sendCompletionGroup(completionResults.map((result) => ({
|
|
336
333
|
agent: result.agent,
|
|
337
|
-
block: formatCompletionBlock(result,
|
|
334
|
+
block: formatCompletionBlock(result, DEFAULT_MAX_RESULT_LINES, { resultRoot: projectResultsRoot(runtime.configPath, result.projectCwd ?? ctx.cwd) }),
|
|
338
335
|
triggerTurn: true,
|
|
339
336
|
usage: result.usage,
|
|
340
337
|
})));
|
|
@@ -1,10 +1,9 @@
|
|
|
1
1
|
/** Session-start recovery, stale-model cleanup, and progress-surface installation. */
|
|
2
2
|
|
|
3
3
|
import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
|
|
4
|
-
import { existsSync } from "node:fs";
|
|
5
4
|
import { loadConfig, saveConfig } from "../configuration/config.ts";
|
|
6
5
|
import { availableModelsInScope, filterUnavailableModelOverrides } from "../configuration/models.ts";
|
|
7
|
-
import {
|
|
6
|
+
import { ensureDefaultConfig } from "../configuration/setup.ts";
|
|
8
7
|
import { announceRecoveryRecords, relocateRecoveryManifest } from "../isolation/recovery.ts";
|
|
9
8
|
import type { SubagentRuntime } from "../lifecycle/runtime.ts";
|
|
10
9
|
import { installActiveRunsWidget } from "./widget.ts";
|
|
@@ -35,7 +34,7 @@ async function removeUnavailableAgentModels(
|
|
|
35
34
|
|
|
36
35
|
export function registerAnnouncements(pi: ExtensionAPI, runtime: SubagentRuntime): void {
|
|
37
36
|
pi.on("session_start", async (_event, ctx) => {
|
|
38
|
-
|
|
37
|
+
await ensureDefaultConfig(ctx, runtime.configPath);
|
|
39
38
|
await relocateRecoveryManifest(runtime.configPath);
|
|
40
39
|
await announceRecoveryRecords(runtime.configPath, ctx);
|
|
41
40
|
await removeUnavailableAgentModels(ctx, runtime);
|
|
@@ -53,7 +52,6 @@ export function registerAnnouncements(pi: ExtensionAPI, runtime: SubagentRuntime
|
|
|
53
52
|
// The active-run widget is TUI-only.
|
|
54
53
|
if (ctx.mode !== "tui") return;
|
|
55
54
|
installActiveRunsWidget(ctx);
|
|
56
|
-
if (firstRun) await offerFirstRunSetup(ctx, runtime.configPath);
|
|
57
55
|
});
|
|
58
56
|
|
|
59
57
|
// Compaction failures are otherwise silent in long orchestration sessions
|