@ferris1225/pi-subagents 6.0.4 → 6.0.5
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 +31 -0
- package/README.md +16 -8
- package/index.ts +6 -1
- package/package.json +1 -1
- package/src/configuration/setup.ts +1 -31
- package/src/configuration/ui.ts +10 -22
- package/src/delegation/agents.ts +5 -5
- package/src/delegation/builtin-agents.ts +5 -5
- package/src/delegation/dispatch.ts +28 -50
- package/src/delegation/prompt.ts +21 -42
- package/src/execution/background.ts +2 -2
- package/src/execution/run-control.ts +1 -1
- package/src/execution/spawn.ts +2 -30
- package/src/isolation/worktree.ts +0 -14
- package/src/lifecycle/completion.ts +9 -21
- package/src/lifecycle/dispatch-core.ts +7 -7
- package/src/lifecycle/durable.ts +5 -11
- package/src/lifecycle/runtime.ts +4 -7
- package/src/lifecycle/stop.ts +1 -2
- package/src/lifecycle/thread-lifecycle.ts +37 -54
- package/src/lifecycle/thread-restore.ts +1 -0
- package/src/lifecycle/thread-shared.ts +10 -17
- package/src/lifecycle/tools.ts +13 -18
- package/src/presentation/announcements.ts +8 -6
- package/src/presentation/format.ts +39 -14
- package/src/presentation/monitor.ts +11 -41
- package/src/presentation/widget.ts +4 -14
package/src/execution/spawn.ts
CHANGED
|
@@ -61,29 +61,6 @@ function getFinalOutput(messages: Message[]): string {
|
|
|
61
61
|
return "";
|
|
62
62
|
}
|
|
63
63
|
|
|
64
|
-
export const RESULT_LINE_MAX = 200;
|
|
65
|
-
|
|
66
|
-
export interface TruncatedOutput {
|
|
67
|
-
text: string;
|
|
68
|
-
truncated: boolean;
|
|
69
|
-
shownLines: number;
|
|
70
|
-
totalLines: number;
|
|
71
|
-
widthClipped: boolean;
|
|
72
|
-
}
|
|
73
|
-
|
|
74
|
-
export function truncateResultOutput(output: string, maxLines: number): TruncatedOutput {
|
|
75
|
-
const lines = output.split("\n");
|
|
76
|
-
const totalLines = lines.length;
|
|
77
|
-
const widthClipped = lines.some((line) => line.length > RESULT_LINE_MAX);
|
|
78
|
-
if (totalLines <= maxLines && !widthClipped) {
|
|
79
|
-
return { text: output, truncated: false, shownLines: totalLines, totalLines, widthClipped: false };
|
|
80
|
-
}
|
|
81
|
-
const kept = lines.slice(0, maxLines).map((line) =>
|
|
82
|
-
line.length > RESULT_LINE_MAX ? `${line.slice(0, RESULT_LINE_MAX)}…` : line,
|
|
83
|
-
);
|
|
84
|
-
return { text: kept.join("\n"), truncated: true, shownLines: kept.length, totalLines, widthClipped };
|
|
85
|
-
}
|
|
86
|
-
|
|
87
64
|
const RESULT_ARTIFACT_MAX_AGE_MS = 7 * 24 * 60 * 60 * 1_000;
|
|
88
65
|
const RESULT_ARTIFACT_MAX_FILES_PER_PROJECT = 50;
|
|
89
66
|
// Explicit current prefix plus the strict timestamp/token convention used by 1.1.0.
|
|
@@ -377,7 +354,7 @@ export async function runSingleAgentWithMainFallback(
|
|
|
377
354
|
mainFallbackRef?: string,
|
|
378
355
|
): Promise<SingleResult> {
|
|
379
356
|
const agent = options.agent;
|
|
380
|
-
const launchedRef = agent
|
|
357
|
+
const launchedRef = agent.model;
|
|
381
358
|
|
|
382
359
|
const sessionId = options.sessionId ?? randomUUID();
|
|
383
360
|
const sessionDir = options.sessionDir ?? (await createSessionDir(options.sessionRoot));
|
|
@@ -509,12 +486,7 @@ export async function runSingleAgentWithMainFallback(
|
|
|
509
486
|
: {}),
|
|
510
487
|
};
|
|
511
488
|
try {
|
|
512
|
-
options.onLive?.({
|
|
513
|
-
kind: "model",
|
|
514
|
-
model: candidate.ref,
|
|
515
|
-
thinking: candidateThinking,
|
|
516
|
-
...(candidateIndex > 0 && launchedRef ? { fallbackFrom: launchedRef } : {}),
|
|
517
|
-
});
|
|
489
|
+
options.onLive?.({ kind: "model", model: candidate.ref, thinking: candidateThinking });
|
|
518
490
|
} catch {
|
|
519
491
|
/* never throw from event handling */
|
|
520
492
|
}
|
|
@@ -108,10 +108,6 @@ export interface WorktreeIsolation {
|
|
|
108
108
|
getContinuationCheckpoint(): WorktreeCheckpoint | undefined;
|
|
109
109
|
/** Remove an unused worktree whose dispatch was cancelled. */
|
|
110
110
|
discard(): Promise<void>;
|
|
111
|
-
/** Whether anything is pending against the integration base — the same
|
|
112
|
-
* question finalization answers as `hadChanges`, asked before settlement so
|
|
113
|
-
* policy can tell a run that produced a diff from one that produced none. */
|
|
114
|
-
hasPendingChanges(): Promise<boolean>;
|
|
115
111
|
/** Idempotent across stale generations and repeated stop/shutdown paths. */
|
|
116
112
|
finalize(): Promise<WorktreeFinalization>;
|
|
117
113
|
}
|
|
@@ -387,16 +383,6 @@ class GitWorktreeIsolation implements WorktreeIsolation {
|
|
|
387
383
|
return this.discardPromise;
|
|
388
384
|
}
|
|
389
385
|
|
|
390
|
-
async hasPendingChanges(): Promise<boolean> {
|
|
391
|
-
// A settled worktree already recorded the answer; asking Git again after
|
|
392
|
-
// removal would fail. Diffing the integration base (not HEAD) excludes
|
|
393
|
-
// previously integrated work from the recovered run's pending changes.
|
|
394
|
-
if (this.currentState === "no_changes") return false;
|
|
395
|
-
if (this.currentState !== "active" || !existsSync(this.worktreePath)) return true;
|
|
396
|
-
const diff = await this.collectChanges(this.integrationBaseHead);
|
|
397
|
-
return diff.stdout.length > 0;
|
|
398
|
-
}
|
|
399
|
-
|
|
400
386
|
finalize(): Promise<WorktreeFinalization> {
|
|
401
387
|
if (this.finalization) return this.finalization;
|
|
402
388
|
this.currentState = "finalizing";
|
|
@@ -7,17 +7,11 @@
|
|
|
7
7
|
* failure directly so it is never delayed.
|
|
8
8
|
*/
|
|
9
9
|
|
|
10
|
-
import { formatUsageTokens, sumUsage
|
|
10
|
+
import { formatUsageTokens, sumUsage } from "../presentation/monitor.ts";
|
|
11
11
|
import type { UsageStats } from "../execution/run-control.ts";
|
|
12
|
-
export interface CompletionBatchTimings {
|
|
13
|
-
debounceMs: number;
|
|
14
|
-
maxWaitMs: number;
|
|
15
|
-
}
|
|
16
12
|
|
|
17
|
-
const
|
|
18
|
-
|
|
19
|
-
maxWaitMs: 1_000,
|
|
20
|
-
};
|
|
13
|
+
const COMPLETION_DEBOUNCE_MS = 150;
|
|
14
|
+
const COMPLETION_MAX_WAIT_MS = 1_000;
|
|
21
15
|
|
|
22
16
|
type TimerHandle = ReturnType<typeof setTimeout>;
|
|
23
17
|
|
|
@@ -34,7 +28,6 @@ function unrefHandle(handle: TimerHandle): void {
|
|
|
34
28
|
|
|
35
29
|
export interface CompletionBatcherOptions<T> {
|
|
36
30
|
emit: (items: T[]) => void;
|
|
37
|
-
timings?: Partial<CompletionBatchTimings>;
|
|
38
31
|
}
|
|
39
32
|
|
|
40
33
|
export interface CompletionBatcher<T> {
|
|
@@ -47,7 +40,6 @@ export interface CompletionBatcher<T> {
|
|
|
47
40
|
}
|
|
48
41
|
|
|
49
42
|
export function createCompletionBatcher<T>(options: CompletionBatcherOptions<T>): CompletionBatcher<T> {
|
|
50
|
-
const timings = { ...DEFAULT_COMPLETION_BATCH_TIMINGS, ...options.timings };
|
|
51
43
|
let pending: T[] = [];
|
|
52
44
|
let debounceTimer: TimerHandle | null = null;
|
|
53
45
|
let maxWaitTimer: TimerHandle | null = null;
|
|
@@ -76,11 +68,11 @@ export function createCompletionBatcher<T>(options: CompletionBatcherOptions<T>)
|
|
|
76
68
|
pending.push(item);
|
|
77
69
|
|
|
78
70
|
if (debounceTimer !== null) clearTimeout(debounceTimer);
|
|
79
|
-
debounceTimer = setTimeout(emitGroup,
|
|
71
|
+
debounceTimer = setTimeout(emitGroup, COMPLETION_DEBOUNCE_MS);
|
|
80
72
|
unrefHandle(debounceTimer);
|
|
81
73
|
|
|
82
74
|
if (maxWaitTimer === null) {
|
|
83
|
-
maxWaitTimer = setTimeout(emitGroup,
|
|
75
|
+
maxWaitTimer = setTimeout(emitGroup, COMPLETION_MAX_WAIT_MS);
|
|
84
76
|
unrefHandle(maxWaitTimer);
|
|
85
77
|
}
|
|
86
78
|
},
|
|
@@ -97,7 +89,7 @@ export function createCompletionBatcher<T>(options: CompletionBatcherOptions<T>)
|
|
|
97
89
|
export interface CompletionMessageItem {
|
|
98
90
|
agent: string;
|
|
99
91
|
block: string;
|
|
100
|
-
/** Final usage of the underlying run
|
|
92
|
+
/** Final usage of the underlying run; aggregated into the group totals. */
|
|
101
93
|
usage?: UsageStats;
|
|
102
94
|
/** Model ref that produced this run's usage; group totals stay per model
|
|
103
95
|
* instead of summing different models' spend into one number. */
|
|
@@ -143,12 +135,8 @@ export interface ActiveRunFoot {
|
|
|
143
135
|
agent: string;
|
|
144
136
|
/** Optional content label (task-derived) shown next to the agent name. */
|
|
145
137
|
label?: string;
|
|
146
|
-
/**
|
|
147
|
-
|
|
148
|
-
}
|
|
149
|
-
|
|
150
|
-
function activeRunWaitTag(wait: RunWaitReason | undefined): string {
|
|
151
|
-
return wait ? " (starting)" : "";
|
|
138
|
+
/** The child process is still starting. */
|
|
139
|
+
starting?: boolean;
|
|
152
140
|
}
|
|
153
141
|
|
|
154
142
|
/**
|
|
@@ -163,7 +151,7 @@ export function formatActiveRunsFooter(runs: readonly ActiveRunFoot[], maxListed
|
|
|
163
151
|
if (runs.length === 0) return "";
|
|
164
152
|
const listed = runs.slice(0, maxListed);
|
|
165
153
|
const items = listed
|
|
166
|
-
.map((run) => `#${run.id} ${run.agent}${run.label ? `·${run.label}` : ""}${
|
|
154
|
+
.map((run) => `#${run.id} ${run.agent}${run.label ? `·${run.label}` : ""}${run.starting ? " (starting)" : ""}`)
|
|
167
155
|
.join(", ");
|
|
168
156
|
const more = runs.length > listed.length ? `, +${runs.length - listed.length} more` : "";
|
|
169
157
|
return `\n\n⚠ ${runs.length} other run${runs.length === 1 ? "" : "s"} still active: ${items}${more}. Do not conclude the overall task yet — their results wake you automatically.`;
|
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* Shared background-dispatch machinery
|
|
2
|
+
* Shared background-dispatch machinery for fresh runs and completed-run
|
|
3
|
+
* follow-ups.
|
|
3
4
|
*
|
|
4
|
-
*
|
|
5
|
-
* dispatcher, live-activity projection, terminal-notification path, and
|
|
6
|
-
* details builder
|
|
7
|
-
*
|
|
8
|
-
* and completion accounting.
|
|
5
|
+
* `subagent` and `subagent_message` start children through the same
|
|
6
|
+
* dispatcher, live-activity projection, terminal-notification path, and
|
|
7
|
+
* tool-card details builder, so every run shares lifecycle ownership,
|
|
8
|
+
* isolation, admission, durable checkpointing, and completion accounting.
|
|
9
9
|
*/
|
|
10
10
|
|
|
11
11
|
import { createBackgroundDispatcher } from "./thread-lifecycle.ts";
|
|
@@ -90,7 +90,7 @@ export function createDispatchCore(runtime: SubagentRuntime): DispatchCore {
|
|
|
90
90
|
}
|
|
91
91
|
break;
|
|
92
92
|
case "model":
|
|
93
|
-
monitor.setModel(runId, e.model
|
|
93
|
+
monitor.setModel(runId, e.model);
|
|
94
94
|
monitor.setThinking(runId, e.thinking);
|
|
95
95
|
break;
|
|
96
96
|
case "usage":
|
package/src/lifecycle/durable.ts
CHANGED
|
@@ -84,8 +84,6 @@ export interface ThreadRecord {
|
|
|
84
84
|
executionCwd: string;
|
|
85
85
|
/** Resolved (clamped) level of the last generation. */
|
|
86
86
|
thinkingLevel?: string;
|
|
87
|
-
/** Originally requested level, retained with the recovery metadata. */
|
|
88
|
-
requestedThinkingLevel?: string;
|
|
89
87
|
isolation: IsolationMode;
|
|
90
88
|
state: "parked" | "completed" | "failed";
|
|
91
89
|
elapsedMs: number;
|
|
@@ -182,9 +180,6 @@ function normalizeRecord(value: unknown): ThreadRecord | undefined {
|
|
|
182
180
|
cwd: raw.cwd,
|
|
183
181
|
executionCwd: typeof raw.executionCwd === "string" && raw.executionCwd ? raw.executionCwd : raw.cwd,
|
|
184
182
|
...(typeof raw.thinkingLevel === "string" && raw.thinkingLevel ? { thinkingLevel: raw.thinkingLevel } : {}),
|
|
185
|
-
...(typeof raw.requestedThinkingLevel === "string" && raw.requestedThinkingLevel
|
|
186
|
-
? { requestedThinkingLevel: raw.requestedThinkingLevel }
|
|
187
|
-
: {}),
|
|
188
183
|
isolation: raw.isolation,
|
|
189
184
|
state: raw.state,
|
|
190
185
|
elapsedMs: typeof raw.elapsedMs === "number" && Number.isFinite(raw.elapsedMs) ? Math.max(0, raw.elapsedMs) : 0,
|
|
@@ -403,19 +398,19 @@ function summarizeResult(result: SingleResult): ThreadResultSummary | undefined
|
|
|
403
398
|
|
|
404
399
|
/** Project a live thread into its durable record. Only handles whose
|
|
405
400
|
* filesystem is still meaningful are persisted; finalized-and-removed
|
|
406
|
-
* worktrees keep their checkpoint commit as recovery evidence.
|
|
401
|
+
* worktrees keep their checkpoint commit as recovery evidence. An upsert keeps
|
|
402
|
+
* the stored record's creation time. */
|
|
407
403
|
export function threadRecordFromThread(
|
|
408
404
|
thread: SubagentThread,
|
|
409
405
|
state: "parked" | "completed" | "failed",
|
|
410
|
-
previous?: ThreadRecord,
|
|
411
|
-
now = Date.now(),
|
|
412
406
|
): ThreadRecord {
|
|
407
|
+
const now = Date.now();
|
|
413
408
|
const worktree = thread.worktree ? worktreeSnapshot(thread.worktree) : undefined;
|
|
414
|
-
thread.durableId ??=
|
|
409
|
+
thread.durableId ??= randomUUID();
|
|
415
410
|
return {
|
|
416
411
|
durableId: thread.durableId,
|
|
417
412
|
runId: thread.id,
|
|
418
|
-
createdAt:
|
|
413
|
+
createdAt: now,
|
|
419
414
|
updatedAt: now,
|
|
420
415
|
generation: thread.generation,
|
|
421
416
|
agentName: thread.agentName,
|
|
@@ -423,7 +418,6 @@ export function threadRecordFromThread(
|
|
|
423
418
|
cwd: thread.cwd,
|
|
424
419
|
executionCwd: thread.executionCwd,
|
|
425
420
|
...(thread.thinkingLevel ? { thinkingLevel: thread.thinkingLevel } : {}),
|
|
426
|
-
...(thread.requestedThinkingLevel ? { requestedThinkingLevel: thread.requestedThinkingLevel } : {}),
|
|
427
421
|
isolation: thread.isolation,
|
|
428
422
|
state,
|
|
429
423
|
elapsedMs: thread.elapsedMs,
|
package/src/lifecycle/runtime.ts
CHANGED
|
@@ -41,7 +41,6 @@ export interface SubagentThread {
|
|
|
41
41
|
/** Actual child cwd (the equivalent path inside an isolated worktree). */
|
|
42
42
|
executionCwd: string;
|
|
43
43
|
thinkingLevel?: ThinkingLevel;
|
|
44
|
-
requestedThinkingLevel?: ThinkingLevel;
|
|
45
44
|
isolation: IsolationMode;
|
|
46
45
|
worktree?: WorktreeIsolation;
|
|
47
46
|
/** Original durable evidence retained when its worktree handle is unavailable. */
|
|
@@ -61,8 +60,7 @@ export interface SubagentThread {
|
|
|
61
60
|
elapsedMs: number;
|
|
62
61
|
/** Terminal or interrupted partial result; independent of the transient monitor row. */
|
|
63
62
|
lastResult?: SingleResult;
|
|
64
|
-
/**
|
|
65
|
-
retireOnSettle?: boolean;
|
|
63
|
+
/** Retired by a destructive stop: its session is deleted and it cannot be continued. */
|
|
66
64
|
retired?: boolean;
|
|
67
65
|
/** All owners finalize under the same original-repository lane. */
|
|
68
66
|
finalizeIsolation: (generation: number, result?: SingleResult) => Promise<WorktreeFinalization | undefined>;
|
|
@@ -182,7 +180,7 @@ export function createRuntime(pi: ExtensionAPI, configPath: string): SubagentRun
|
|
|
182
180
|
id: run.id,
|
|
183
181
|
agent: run.agent,
|
|
184
182
|
label: run.label,
|
|
185
|
-
...(run.status === "queued"
|
|
183
|
+
...(run.status === "queued" ? { starting: true } : {}),
|
|
186
184
|
}));
|
|
187
185
|
const message = {
|
|
188
186
|
customType: "subagent-result",
|
|
@@ -271,10 +269,9 @@ export function createRuntime(pi: ExtensionAPI, configPath: string): SubagentRun
|
|
|
271
269
|
continue;
|
|
272
270
|
}
|
|
273
271
|
if (thread.lifecycleOperation === "settle") continue;
|
|
272
|
+
// Unlike subagent_stop, shutdown interrupts to the last checkpoint and
|
|
273
|
+
// preserves session/worktree artifacts for manual recovery.
|
|
274
274
|
thread.lifecycleOperation = "stop";
|
|
275
|
-
// Deliberately NOT retireOnSettle: shutdown interrupts to the last
|
|
276
|
-
// checkpoint and preserves session/worktree artifacts for manual recovery.
|
|
277
|
-
thread.retireOnSettle = false;
|
|
278
275
|
if (liveStates.has(thread.state)) thread.state = "stopped";
|
|
279
276
|
}
|
|
280
277
|
runtime.completionBatcher.dispose();
|
package/src/lifecycle/stop.ts
CHANGED
|
@@ -35,7 +35,6 @@ export async function stopThreads(runtime: SubagentRuntime, targets: readonly nu
|
|
|
35
35
|
const stopVersion = ++thread.lifecycleVersion;
|
|
36
36
|
thread.lifecycleOperation = "stop";
|
|
37
37
|
thread.retired = true;
|
|
38
|
-
thread.retireOnSettle = true;
|
|
39
38
|
thread.state = "stopped";
|
|
40
39
|
const completion = thread.generationCompletion;
|
|
41
40
|
let releaseQuiescence!: () => void;
|
|
@@ -60,7 +59,7 @@ export async function stopThreads(runtime: SubagentRuntime, targets: readonly nu
|
|
|
60
59
|
// Interrupt every claimed generation before awaiting any one of them.
|
|
61
60
|
// An isolated stop may need the repository lane for final integration;
|
|
62
61
|
// cancelling all holders first prevents stop-all from waiting behind a
|
|
63
|
-
// later
|
|
62
|
+
// later run that this same operation has not interrupted yet.
|
|
64
63
|
const interruptionPromises = claimed.map(({ thread, stopMessage, controller }) => {
|
|
65
64
|
const stopping = thread.control.stop(stopMessage).catch(() => undefined);
|
|
66
65
|
runtime.backgroundQueue.cancel(controller);
|
|
@@ -9,10 +9,10 @@
|
|
|
9
9
|
|
|
10
10
|
import { randomUUID } from "node:crypto";
|
|
11
11
|
import { join, resolve } from "node:path";
|
|
12
|
-
import { resolveAgentTools, type AgentConfig } from "../delegation/agents.ts";
|
|
12
|
+
import { isWriteCapableAgent, resolveAgentTools, type AgentConfig } from "../delegation/agents.ts";
|
|
13
13
|
import type { CompletionMessageItem } from "./completion.ts";
|
|
14
14
|
import { DEFAULT_IDLE_TIMEOUT_SEC, DEFAULT_MAX_RESULT_LINES, loadConfig } from "../configuration/config.ts";
|
|
15
|
-
import { dispatchFailedResult, failedStartResult, formatCompletionBlock,
|
|
15
|
+
import { dispatchFailedResult, failedStartResult, formatCompletionBlock, queuedResult } from "../presentation/format.ts";
|
|
16
16
|
import { formatTaskSummary, monitor } from "../presentation/monitor.ts";
|
|
17
17
|
import { findDuplicateDispatch } from "../delegation/prompt.ts";
|
|
18
18
|
import { persistRecoveryRecords, recoveryRecordFromFinalization } from "../isolation/recovery.ts";
|
|
@@ -27,7 +27,6 @@ import {
|
|
|
27
27
|
type SubagentLiveEvent,
|
|
28
28
|
} from "../execution/spawn.ts";
|
|
29
29
|
import {
|
|
30
|
-
isWorktreeCapableAgent,
|
|
31
30
|
persistThreadCheckpoint,
|
|
32
31
|
projectResultsRoot,
|
|
33
32
|
resolveDispatchModelRoute,
|
|
@@ -99,8 +98,7 @@ export function createBackgroundDispatcher(options: BackgroundDispatcherOptions)
|
|
|
99
98
|
resolveAgentTools(candidate, runtime.getActiveTools(), runtime.getToolInfos());
|
|
100
99
|
const agent = resolveLiveAgentTools(discoveredAgent);
|
|
101
100
|
const originalCwd = resolve(cwd ?? runCtx.cwd);
|
|
102
|
-
|
|
103
|
-
if (isolation === "worktree" && !isWorktreeCapableAgent(agent, toolInfos)) {
|
|
101
|
+
if (isolation === "worktree" && !isWriteCapableAgent(agent, toolInfos)) {
|
|
104
102
|
return {
|
|
105
103
|
...failedStartResult(agentName, task, `Agent "${agentName}" is read-only; worktree isolation is available only to write-capable agents such as artisan.`),
|
|
106
104
|
isolation,
|
|
@@ -110,15 +108,18 @@ export function createBackgroundDispatcher(options: BackgroundDispatcherOptions)
|
|
|
110
108
|
if (duplicate) {
|
|
111
109
|
// A phase stays owned across reloads: an interrupted run keeps its claim
|
|
112
110
|
// until it is retired, so "let it finish" is wrong advice for a parked
|
|
113
|
-
// owner and leaves the caller with no way forward.
|
|
111
|
+
// owner and leaves the caller with no way forward. A retired owner is
|
|
112
|
+
// still releasing its child or worktree after subagent_stop.
|
|
114
113
|
const owner = duplicate.source;
|
|
115
|
-
const remedy = owner.
|
|
116
|
-
?
|
|
117
|
-
: owner.state === "
|
|
118
|
-
? `
|
|
119
|
-
: owner.state === "
|
|
120
|
-
?
|
|
121
|
-
:
|
|
114
|
+
const remedy = owner.retired
|
|
115
|
+
? "It is still stopping; dispatch the phase again after the stop finishes."
|
|
116
|
+
: owner.state === "parked"
|
|
117
|
+
? `That interrupted run keeps the phase claimed. Inspect its retained result with subagent_status and finish from that evidence. Retire it with subagent_stop({ id: "${owner.id}" }) only if discarding its retained session is intended; then the phase can be reused.`
|
|
118
|
+
: owner.state === "completed"
|
|
119
|
+
? `Reuse its result via subagent_status({ id: ${owner.id} }); use subagent_message({ id: ${owner.id}, message: "<bounded next step>" }) for additional work. A new deliverable needs its own brief.`
|
|
120
|
+
: owner.state === "failed"
|
|
121
|
+
? "Inspect the failure with subagent_status and finish the remaining work from its evidence. Do not repeat the same phase."
|
|
122
|
+
: "Do not redispatch it; let it finish or steer it with subagent_message. Its result returns automatically; then continue the task.";
|
|
122
123
|
return failedStartResult(agentName, task,
|
|
123
124
|
`Run #${owner.id} (${owner.agentName}) already owns this logical phase (${owner.state}). ${remedy}`);
|
|
124
125
|
}
|
|
@@ -129,15 +130,10 @@ export function createBackgroundDispatcher(options: BackgroundDispatcherOptions)
|
|
|
129
130
|
let worktree: WorktreeIsolation | undefined;
|
|
130
131
|
let executionCwd = originalCwd;
|
|
131
132
|
let worktreeGroup: string | undefined;
|
|
132
|
-
const
|
|
133
|
-
let route = isolation === "worktree"
|
|
134
|
-
? { ...resolvedRoute, agent: withWorktreeSystemPrompt(resolvedRoute.agent) }
|
|
135
|
-
: resolvedRoute;
|
|
133
|
+
const route = resolveDispatchModelRoute(agent, runConfig, runCtx);
|
|
136
134
|
const thinkingLevel = route.thinkingLevel;
|
|
137
|
-
const runId = monitor.addRun(agent.name, task, route.agent.model, thinkingLevel,
|
|
138
|
-
|
|
139
|
-
});
|
|
140
|
-
if (!quiet) runtime.claimRunDelivery(runId, startOptions.deliveryRoute ?? "background");
|
|
135
|
+
const runId = monitor.addRun(agent.name, task, route.agent.model, thinkingLevel, isolation);
|
|
136
|
+
runtime.claimRunDelivery(runId, startOptions.deliveryRoute ?? "background");
|
|
141
137
|
const generation = 1;
|
|
142
138
|
const pending: SingleResult = {
|
|
143
139
|
...queuedResult(route.agent, task, thinkingLevel),
|
|
@@ -188,7 +184,7 @@ export function createBackgroundDispatcher(options: BackgroundDispatcherOptions)
|
|
|
188
184
|
runtime,
|
|
189
185
|
runCtx,
|
|
190
186
|
});
|
|
191
|
-
if (isolation === "shared"
|
|
187
|
+
if (isolation === "shared") installCurrentLifecycle();
|
|
192
188
|
|
|
193
189
|
const onLive = makeLiveHandler(runId, generation);
|
|
194
190
|
const runGeneration = async (backgroundSignal: AbortSignal): Promise<void> => {
|
|
@@ -205,7 +201,6 @@ export function createBackgroundDispatcher(options: BackgroundDispatcherOptions)
|
|
|
205
201
|
pending.isolation = "shared";
|
|
206
202
|
delete pending.integrationStatus;
|
|
207
203
|
pending.isolationNote = `Using the caller's directory: ${error.reason}; automatic worktree isolation is unavailable.`;
|
|
208
|
-
route = resolvedRoute;
|
|
209
204
|
monitor.setIsolation(runId, "shared");
|
|
210
205
|
runCtx.ui.notify(`#${runId}: ${pending.isolationNote}`, "info");
|
|
211
206
|
installCurrentLifecycle();
|
|
@@ -224,28 +219,24 @@ export function createBackgroundDispatcher(options: BackgroundDispatcherOptions)
|
|
|
224
219
|
installCurrentLifecycle();
|
|
225
220
|
}
|
|
226
221
|
}
|
|
227
|
-
// Independent runs start immediately; only worktree integration serializes.
|
|
228
|
-
monitor.setWaitReason(runId, "starting");
|
|
229
222
|
// Re-read model preferences after asynchronous worktree preparation.
|
|
230
223
|
let activeRoute = route;
|
|
231
224
|
const activeIdleTimeoutMs = DEFAULT_IDLE_TIMEOUT_SEC * 1000;
|
|
232
225
|
try {
|
|
233
226
|
const startConfig = await loadConfig(runtime.configPath);
|
|
234
|
-
|
|
235
|
-
activeRoute = isolation === "worktree"
|
|
236
|
-
? { ...resolvedStart, agent: withWorktreeSystemPrompt(resolvedStart.agent) }
|
|
237
|
-
: resolvedStart;
|
|
227
|
+
activeRoute = resolveDispatchModelRoute(agent, startConfig, runCtx);
|
|
238
228
|
monitor.setModel(runId, activeRoute.agent.model);
|
|
239
229
|
monitor.setThinking(runId, activeRoute.thinkingLevel);
|
|
240
230
|
} catch {
|
|
241
231
|
/* keep the dispatch-time route when fresh config is unavailable */
|
|
242
232
|
}
|
|
233
|
+
const launchAgent = worktree ? withWorktreeSystemPrompt(activeRoute.agent, worktree) : activeRoute.agent;
|
|
243
234
|
let result: SingleResult;
|
|
244
235
|
try {
|
|
245
236
|
result = await runSingleAgentWithMainFallback(
|
|
246
237
|
{
|
|
247
238
|
defaultCwd: executionCwd,
|
|
248
|
-
agent:
|
|
239
|
+
agent: launchAgent,
|
|
249
240
|
resolveAgentForAttempt: resolveLiveAgentTools,
|
|
250
241
|
agentName,
|
|
251
242
|
task,
|
|
@@ -286,7 +277,7 @@ export function createBackgroundDispatcher(options: BackgroundDispatcherOptions)
|
|
|
286
277
|
thread.sessionDir = result.sessionDir;
|
|
287
278
|
thread.lastResult = result;
|
|
288
279
|
runtime.retainSession(result);
|
|
289
|
-
monitor.setModel(runId, result.model
|
|
280
|
+
monitor.setModel(runId, result.model);
|
|
290
281
|
monitor.setThinking(runId, result.thinking);
|
|
291
282
|
// Checkpoint the session location durably: a crash or reload before
|
|
292
283
|
// settlement still restores this thread with its retained context.
|
|
@@ -305,7 +296,6 @@ export function createBackgroundDispatcher(options: BackgroundDispatcherOptions)
|
|
|
305
296
|
// aborted partial.
|
|
306
297
|
if (backgroundSignal.aborted || !runtime.sessionActive) return;
|
|
307
298
|
|
|
308
|
-
if (thread.retireOnSettle) runtime.retireThreadSession(thread);
|
|
309
299
|
// Claim terminal settlement synchronously before the first slow await.
|
|
310
300
|
// Shutdown therefore either wins while the child is still active, or is rejected
|
|
311
301
|
// once settlement owns the generation. Destructive stop may supersede
|
|
@@ -339,30 +329,23 @@ export function createBackgroundDispatcher(options: BackgroundDispatcherOptions)
|
|
|
339
329
|
const ownedController = thread.queueController;
|
|
340
330
|
if (runtime.runControllers.get(runId) === ownedController) runtime.runControllers.delete(runId);
|
|
341
331
|
thread.queueController = undefined;
|
|
342
|
-
finishRun(
|
|
343
|
-
runId,
|
|
344
|
-
failed ? "failed" : "done",
|
|
345
|
-
quiet || modelLevel || dispatchFailed ? { silent: true } : undefined,
|
|
346
|
-
);
|
|
332
|
+
finishRun(runId, failed ? "failed" : "done", modelLevel || dispatchFailed ? { silent: true } : undefined);
|
|
347
333
|
runtime.registerRunResult(runId, result);
|
|
348
|
-
|
|
349
|
-
|
|
334
|
+
const completion: CompletionMessageItem = {
|
|
335
|
+
agent: result.agent,
|
|
336
|
+
block: formatCompletionBlock(result, DEFAULT_MAX_RESULT_LINES, {
|
|
350
337
|
resultRoot: projectResultsRoot(runtime.configPath, result.projectCwd ?? originalCwd),
|
|
351
|
-
})
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
};
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
runCtx.ui.notify(`✗ ${result.agent} dispatch failed: ${detail} — task handed to the main window`, "error");
|
|
361
|
-
} else if (dispatchFailed) {
|
|
362
|
-
runCtx.ui.notify(`✗ ${result.agent} dispatch failed: ${notifyDetail(result.errorMessage, "dispatch crashed")}`, "error");
|
|
363
|
-
}
|
|
364
|
-
runtime.publishRunCompletion(runId, completion, failed);
|
|
338
|
+
}),
|
|
339
|
+
usage: result.usage,
|
|
340
|
+
model: result.model,
|
|
341
|
+
};
|
|
342
|
+
if (modelLevel) {
|
|
343
|
+
const detail = notifyDetail(result.errorMessage, "model unavailable or broken");
|
|
344
|
+
runCtx.ui.notify(`✗ ${result.agent} dispatch failed: ${detail} — task handed to the main window`, "error");
|
|
345
|
+
} else if (dispatchFailed) {
|
|
346
|
+
runCtx.ui.notify(`✗ ${result.agent} dispatch failed: ${notifyDetail(result.errorMessage, "dispatch crashed")}`, "error");
|
|
365
347
|
}
|
|
348
|
+
runtime.publishRunCompletion(runId, completion, failed);
|
|
366
349
|
} finally {
|
|
367
350
|
if (ownsSettlement()) thread.lifecycleOperation = undefined;
|
|
368
351
|
}
|
|
@@ -433,13 +416,13 @@ export function createBackgroundDispatcher(options: BackgroundDispatcherOptions)
|
|
|
433
416
|
runtime.runControllers.delete(runId);
|
|
434
417
|
thread.queueController = undefined;
|
|
435
418
|
if (!runtime.sessionActive || !ownsSettlement()) return;
|
|
436
|
-
if (quiet) return;
|
|
437
419
|
try {
|
|
438
420
|
runCtx.ui.notify(`✗ ${crashed.agent} dispatch failed: ${notifyDetail(crashed.errorMessage, "dispatch crashed")}`, "error");
|
|
439
421
|
runtime.publishRunCompletion(runId, {
|
|
440
422
|
agent: crashed.agent,
|
|
441
423
|
block: formatCompletionBlock(crashed, DEFAULT_MAX_RESULT_LINES, { resultRoot: projectResultsRoot(runtime.configPath, crashed.projectCwd ?? originalCwd) }),
|
|
442
424
|
usage: crashed.usage,
|
|
425
|
+
model: crashed.model,
|
|
443
426
|
}, true);
|
|
444
427
|
} catch {
|
|
445
428
|
/* a second delivery failure must not throw through the queue */
|
|
@@ -152,6 +152,7 @@ export async function restoreDurableThreads(runtime: SubagentRuntime, cwd: strin
|
|
|
152
152
|
agent: record.agentName,
|
|
153
153
|
block: `### Subagent restoration failed: #${record.runId} ${record.agentName}\n\n${reason}`,
|
|
154
154
|
usage: failed.usage,
|
|
155
|
+
model: failed.model,
|
|
155
156
|
}, true);
|
|
156
157
|
continue;
|
|
157
158
|
}
|
|
@@ -4,7 +4,7 @@ import { utimesSync } from "node:fs";
|
|
|
4
4
|
import { realpath } from "node:fs/promises";
|
|
5
5
|
import { join, resolve } from "node:path";
|
|
6
6
|
import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
|
|
7
|
-
import {
|
|
7
|
+
import type { AgentConfig } from "../delegation/agents.ts";
|
|
8
8
|
import { roleThinkingLevel, type SubagentsConfig, type ThinkingLevel } from "../configuration/config.ts";
|
|
9
9
|
import { removeThreadRecord, threadRecordFromThread, threadRecordIdentity, upsertThreadRecord } from "./durable.ts";
|
|
10
10
|
import {
|
|
@@ -17,7 +17,7 @@ import {
|
|
|
17
17
|
} from "../configuration/models.ts";
|
|
18
18
|
import type { SubagentRuntime, SubagentThread } from "./runtime.ts";
|
|
19
19
|
import { getProjectRoot, type SingleResult } from "../execution/spawn.ts";
|
|
20
|
-
import { resolveRepositoryRoot, type IsolationMode } from "../isolation/worktree.ts";
|
|
20
|
+
import { resolveRepositoryRoot, type IsolationMode, type WorktreeIsolation } from "../isolation/worktree.ts";
|
|
21
21
|
|
|
22
22
|
/** Control operations must never wait forever on a settling generation: the
|
|
23
23
|
* queue task can legitimately spend minutes in worktree finalization (bounded
|
|
@@ -102,19 +102,14 @@ export function persistThreadCheckpoint(
|
|
|
102
102
|
void write.catch(() => undefined);
|
|
103
103
|
}
|
|
104
104
|
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
};
|
|
113
|
-
}
|
|
114
|
-
|
|
115
|
-
/** Only write-capable agents can run in an isolated worktree. */
|
|
116
|
-
export function isWorktreeCapableAgent(agent: AgentConfig, toolInfos?: readonly ToolMetadata[]): boolean {
|
|
117
|
-
return isWriteCapableAgent(agent, toolInfos);
|
|
105
|
+
/** Briefs name paths in the caller's checkout. Naming both roots lets an
|
|
106
|
+
* isolated child map them into its worktree instead of editing the original. */
|
|
107
|
+
export function withWorktreeSystemPrompt(
|
|
108
|
+
agent: AgentConfig,
|
|
109
|
+
worktree: Pick<WorktreeIsolation, "originalRoot" | "worktreePath">,
|
|
110
|
+
): AgentConfig {
|
|
111
|
+
const instructions = `You are running in a temporary detached Git worktree at ${worktree.worktreePath}, a snapshot of the original checkout ${worktree.originalRoot}. Work only inside this worktree: map every brief path under the original checkout to the same relative path here. Do not write to the original checkout, create another worktree, or copy/apply changes back manually. The runtime merges your tracked, deleted, and untracked changes after you finish.`;
|
|
112
|
+
return { ...agent, systemPrompt: `${agent.systemPrompt.trimEnd()}\n\n${instructions}` };
|
|
118
113
|
}
|
|
119
114
|
|
|
120
115
|
export interface DispatchEnvironment {
|
|
@@ -131,8 +126,6 @@ export interface StartBackgroundOptions {
|
|
|
131
126
|
automaticIsolation?: boolean;
|
|
132
127
|
/** Chosen by the tool call before the queue can start a fast child. */
|
|
133
128
|
deliveryRoute?: "background" | "await";
|
|
134
|
-
/** Suppress per-run completion messages and toasts when needed. */
|
|
135
|
-
quiet?: boolean;
|
|
136
129
|
}
|
|
137
130
|
|
|
138
131
|
export type StartBackgroundInternal = (
|