@ferris1225/pi-subagents 7.0.3 → 7.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 +33 -0
- package/README.md +32 -15
- package/package.json +1 -1
- package/src/configuration/config.ts +3 -3
- package/src/configuration/models.ts +2 -2
- package/src/configuration/setup.ts +4 -2
- package/src/configuration/ui.ts +66 -69
- package/src/delegation/builtin-agents.ts +19 -34
- package/src/delegation/dispatch.ts +81 -168
- package/src/delegation/prompt.ts +39 -25
- package/src/execution/background.ts +83 -21
- package/src/execution/cli-run.ts +2 -2
- package/src/execution/run-control.ts +1 -1
- package/src/execution/spawn.ts +3 -1
- package/src/isolation/cleanup.ts +6 -6
- package/src/isolation/git-command.ts +1 -1
- package/src/isolation/managed-paths.ts +1 -1
- package/src/isolation/temp-hygiene.ts +1 -1
- package/src/isolation/worktree.ts +80 -39
- package/src/lifecycle/await-results.ts +4 -2
- package/src/lifecycle/completion.ts +2 -2
- package/src/lifecycle/durable.ts +1 -1
- package/src/lifecycle/runtime.ts +1 -1
- package/src/lifecycle/thread-lifecycle.ts +10 -6
- package/src/lifecycle/thread-shared.ts +34 -44
- package/src/lifecycle/tools.ts +12 -5
- package/src/presentation/format.ts +1 -1
- package/src/presentation/monitor.ts +2 -2
package/src/execution/spawn.ts
CHANGED
|
@@ -45,6 +45,8 @@ export interface SingleResult extends RunResult {}
|
|
|
45
45
|
export interface SubagentDetails {
|
|
46
46
|
mode: "single" | "parallel";
|
|
47
47
|
results: SingleResult[];
|
|
48
|
+
/** Present on final tool results that waited for settlement. */
|
|
49
|
+
awaited?: boolean;
|
|
48
50
|
}
|
|
49
51
|
|
|
50
52
|
/** Text of the newest assistant message that has any. A final answer may be
|
|
@@ -250,7 +252,7 @@ async function createSessionDir(root: string): Promise<string> {
|
|
|
250
252
|
return dir;
|
|
251
253
|
}
|
|
252
254
|
|
|
253
|
-
|
|
255
|
+
interface RunSingleOptions {
|
|
254
256
|
defaultCwd: string;
|
|
255
257
|
agent: AgentConfig;
|
|
256
258
|
agentName: string;
|
package/src/isolation/cleanup.ts
CHANGED
|
@@ -17,7 +17,7 @@ import type { SubagentRuntime } from "../lifecycle/runtime.ts";
|
|
|
17
17
|
import { isProcessAlive, readTempOwnerMarker, sweepProjectDurableDirs, sweepProjectTempDirs } from "./temp-hygiene.ts";
|
|
18
18
|
|
|
19
19
|
/** Bytes a directory tree occupies, without following symlinks. */
|
|
20
|
-
|
|
20
|
+
function directoryBytes(path: string): number {
|
|
21
21
|
let total = 0;
|
|
22
22
|
const stack = [path];
|
|
23
23
|
while (stack.length > 0) {
|
|
@@ -45,7 +45,7 @@ export function directoryBytes(path: string): number {
|
|
|
45
45
|
return total;
|
|
46
46
|
}
|
|
47
47
|
|
|
48
|
-
|
|
48
|
+
interface CleanupUsage {
|
|
49
49
|
/** Absolute path of the extension's durable root. */
|
|
50
50
|
root: string;
|
|
51
51
|
/** Per-project usage, largest first. */
|
|
@@ -117,7 +117,7 @@ function removeEmptySessionCopies(path: string, claimed: readonly string[]): voi
|
|
|
117
117
|
}
|
|
118
118
|
}
|
|
119
119
|
|
|
120
|
-
|
|
120
|
+
interface CleanupResult {
|
|
121
121
|
before: CleanupUsage;
|
|
122
122
|
after: CleanupUsage;
|
|
123
123
|
/** Bytes actually reclaimed, measured rather than estimated. */
|
|
@@ -178,7 +178,7 @@ export function formatBytes(bytes: number): string {
|
|
|
178
178
|
/** Sessions of settled runs are kept only so a follow-up can resume them. After
|
|
179
179
|
* this window they are pure disk cost: `subagent_message` with
|
|
180
180
|
* `context: "summary"` still works, and rework usually starts long before it. */
|
|
181
|
-
|
|
181
|
+
const SETTLED_SESSION_MAX_AGE_MS = 30 * 60 * 1_000;
|
|
182
182
|
|
|
183
183
|
/** Recent sessions are never reclaimed regardless of budget: a follow-up can
|
|
184
184
|
* legitimately arrive seconds after settlement. */
|
|
@@ -190,11 +190,11 @@ const AUTO_CLEANUP_INTERVAL_MS = 5 * 60 * 1_000;
|
|
|
190
190
|
|
|
191
191
|
/** Upper bound for one project's artifacts; the oldest settled sessions go
|
|
192
192
|
* first until the project fits. */
|
|
193
|
-
|
|
193
|
+
const PROJECT_BUDGET_BYTES = 1.5 * 1024 * 1024 * 1024;
|
|
194
194
|
|
|
195
195
|
let lastAutomaticCleanupAt = 0;
|
|
196
196
|
|
|
197
|
-
|
|
197
|
+
interface AutomaticCleanupOptions {
|
|
198
198
|
now?: number;
|
|
199
199
|
/** Retained-session age before automatic reclamation. */
|
|
200
200
|
maxSessionAgeMs?: number;
|
|
@@ -80,7 +80,7 @@ export async function isManagedSessionDir(
|
|
|
80
80
|
return isManagedDirectory(sessionsRoot, sessionDir, SESSION_DIR_NAME);
|
|
81
81
|
}
|
|
82
82
|
|
|
83
|
-
|
|
83
|
+
interface PersistedWorktreePaths {
|
|
84
84
|
cwd: string;
|
|
85
85
|
worktreePath: string;
|
|
86
86
|
tempDir: string;
|
|
@@ -24,6 +24,35 @@ export type IsolationMode = "shared" | "worktree";
|
|
|
24
24
|
|
|
25
25
|
const WORKTREE_TEMP_DIR_PREFIX = "pi-subagent-worktree-";
|
|
26
26
|
|
|
27
|
+
const repositoryOperationTails = new Map<string, Promise<void>>();
|
|
28
|
+
|
|
29
|
+
/** Serialize original-repository index snapshots, patch integration, and Git
|
|
30
|
+
* worktree metadata mutations per repository root so concurrent parallel workers
|
|
31
|
+
* never collide on `.git/worktrees` creation, locks, or `worktree prune` while
|
|
32
|
+
* their child processes execute in parallel inside detached worktrees. */
|
|
33
|
+
function runInRepositoryWorktreeLock<T>(
|
|
34
|
+
repositoryRoot: string,
|
|
35
|
+
operation: () => Promise<T>,
|
|
36
|
+
): Promise<T> {
|
|
37
|
+
const key = process.platform === "win32" ? resolve(repositoryRoot).toLowerCase() : resolve(repositoryRoot);
|
|
38
|
+
const previous = repositoryOperationTails.get(key) ?? Promise.resolve();
|
|
39
|
+
let release!: () => void;
|
|
40
|
+
const gate = new Promise<void>((resolveGate) => {
|
|
41
|
+
release = resolveGate;
|
|
42
|
+
});
|
|
43
|
+
const tail = previous.catch(() => undefined).then(() => gate);
|
|
44
|
+
repositoryOperationTails.set(key, tail);
|
|
45
|
+
return previous
|
|
46
|
+
.catch(() => undefined)
|
|
47
|
+
.then(operation)
|
|
48
|
+
.finally(() => {
|
|
49
|
+
release();
|
|
50
|
+
void tail.then(() => {
|
|
51
|
+
if (repositoryOperationTails.get(key) === tail) repositoryOperationTails.delete(key);
|
|
52
|
+
});
|
|
53
|
+
});
|
|
54
|
+
}
|
|
55
|
+
|
|
27
56
|
/** Short stable identity of one isolated worktree group (the mkdtemp suffix). */
|
|
28
57
|
export function worktreeGroupId(worktree: Pick<WorktreeIsolation, "tempDir">): string {
|
|
29
58
|
const base = worktree.tempDir.split(/[\\/]/).filter(Boolean).pop() ?? worktree.tempDir;
|
|
@@ -32,7 +61,7 @@ export function worktreeGroupId(worktree: Pick<WorktreeIsolation, "tempDir">): s
|
|
|
32
61
|
: base;
|
|
33
62
|
}
|
|
34
63
|
|
|
35
|
-
|
|
64
|
+
interface WorktreeTarget {
|
|
36
65
|
/** Canonical cwd requested by the caller. */
|
|
37
66
|
originalCwd: string;
|
|
38
67
|
/** Canonical top-level directory of the source Git worktree. */
|
|
@@ -42,7 +71,7 @@ export interface WorktreeTarget {
|
|
|
42
71
|
head: string;
|
|
43
72
|
}
|
|
44
73
|
|
|
45
|
-
|
|
74
|
+
interface WorktreeCheckpoint {
|
|
46
75
|
/** Commit checked out when this isolated generation began. */
|
|
47
76
|
baseHead: string;
|
|
48
77
|
/** Synthetic commit whose tree is the generation's complete final state. */
|
|
@@ -51,7 +80,7 @@ export interface WorktreeCheckpoint {
|
|
|
51
80
|
patch: Buffer;
|
|
52
81
|
}
|
|
53
82
|
|
|
54
|
-
|
|
83
|
+
interface WorktreeCheckpointRef {
|
|
55
84
|
baseHead: string;
|
|
56
85
|
commit: string;
|
|
57
86
|
}
|
|
@@ -72,7 +101,7 @@ export interface WorktreeSnapshot {
|
|
|
72
101
|
checkpoint?: WorktreeCheckpointRef;
|
|
73
102
|
}
|
|
74
103
|
|
|
75
|
-
|
|
104
|
+
interface WorktreeCreateOptions {
|
|
76
105
|
runner?: CommandRunner;
|
|
77
106
|
/** Parent directory for the worktree group: the project-scoped durable
|
|
78
107
|
* worktrees root, so isolation never lands in the OS temp directory. */
|
|
@@ -188,7 +217,7 @@ export function isPathInside(root: string, candidate: string): boolean {
|
|
|
188
217
|
* ("Filename too long"), so the Node removal decides the outcome and the prune
|
|
189
218
|
* clears any stale registration left behind. Returns an error string when
|
|
190
219
|
* artifacts still exist afterwards. */
|
|
191
|
-
|
|
220
|
+
async function removeWorktreeGroupUnlocked(
|
|
192
221
|
paths: { originalRoot?: string; tempDir: string; worktreePath: string },
|
|
193
222
|
runner: CommandRunner = runCommand,
|
|
194
223
|
): Promise<string | undefined> {
|
|
@@ -229,6 +258,14 @@ export async function removeWorktreeGroup(
|
|
|
229
258
|
return undefined;
|
|
230
259
|
}
|
|
231
260
|
|
|
261
|
+
export async function removeWorktreeGroup(
|
|
262
|
+
paths: { originalRoot?: string; tempDir: string; worktreePath: string },
|
|
263
|
+
runner: CommandRunner = runCommand,
|
|
264
|
+
): Promise<string | undefined> {
|
|
265
|
+
if (!paths.originalRoot) return removeWorktreeGroupUnlocked(paths, runner);
|
|
266
|
+
return runInRepositoryWorktreeLock(paths.originalRoot, () => removeWorktreeGroupUnlocked(paths, runner));
|
|
267
|
+
}
|
|
268
|
+
|
|
232
269
|
interface RepositoryLocation {
|
|
233
270
|
originalCwd: string;
|
|
234
271
|
originalRoot: string;
|
|
@@ -378,7 +415,10 @@ class GitWorktreeIsolation implements WorktreeIsolation {
|
|
|
378
415
|
return this.finalization.then(() => undefined);
|
|
379
416
|
}
|
|
380
417
|
this.currentState = "finalizing";
|
|
381
|
-
this.discardPromise =
|
|
418
|
+
this.discardPromise = removeWorktreeGroup(
|
|
419
|
+
{ originalRoot: this.originalRoot, worktreePath: this.worktreePath, tempDir: this.tempDir },
|
|
420
|
+
this.runner,
|
|
421
|
+
).then((error) => {
|
|
382
422
|
if (error) {
|
|
383
423
|
this.currentState = "retained";
|
|
384
424
|
throw new Error(error);
|
|
@@ -470,10 +510,14 @@ class GitWorktreeIsolation implements WorktreeIsolation {
|
|
|
470
510
|
if (hadChanges) {
|
|
471
511
|
await writeFile(this.patchPath, diff.stdout, { flag: "wx" });
|
|
472
512
|
patchWritten = true;
|
|
473
|
-
integrated = await this.applyPatchThreeWay();
|
|
474
513
|
}
|
|
475
|
-
|
|
476
|
-
|
|
514
|
+
const cleanupError = await runInRepositoryWorktreeLock(this.originalRoot, async () => {
|
|
515
|
+
if (hadChanges) integrated = await this.applyPatchThreeWay();
|
|
516
|
+
return removeWorktreeGroupUnlocked(
|
|
517
|
+
{ originalRoot: this.originalRoot, worktreePath: this.worktreePath, tempDir: this.tempDir },
|
|
518
|
+
this.runner,
|
|
519
|
+
);
|
|
520
|
+
});
|
|
477
521
|
if (cleanupError) {
|
|
478
522
|
return this.retainedResult(hadChanges, integrated, patchWritten, cleanupError);
|
|
479
523
|
}
|
|
@@ -563,14 +607,6 @@ class GitWorktreeIsolation implements WorktreeIsolation {
|
|
|
563
607
|
await rm(indexCopy, { force: true }).catch(() => undefined);
|
|
564
608
|
}
|
|
565
609
|
}
|
|
566
|
-
|
|
567
|
-
/** Return an error string instead of throwing so applied work is never retried. */
|
|
568
|
-
private removeAndPrune(): Promise<string | undefined> {
|
|
569
|
-
return removeWorktreeGroup(
|
|
570
|
-
{ originalRoot: this.originalRoot, worktreePath: this.worktreePath, tempDir: this.tempDir },
|
|
571
|
-
this.runner,
|
|
572
|
-
);
|
|
573
|
-
}
|
|
574
610
|
}
|
|
575
611
|
|
|
576
612
|
/** Link the origin checkout's `node_modules` into a fresh worktree, because a
|
|
@@ -700,14 +736,17 @@ export async function createWorktreeIsolation(
|
|
|
700
736
|
const patchPath = join(tempDir, "changes.patch");
|
|
701
737
|
let added = false;
|
|
702
738
|
try {
|
|
703
|
-
const baseline = await
|
|
704
|
-
|
|
705
|
-
|
|
706
|
-
|
|
707
|
-
|
|
708
|
-
|
|
709
|
-
|
|
710
|
-
|
|
739
|
+
const baseline = await runInRepositoryWorktreeLock(target.originalRoot, async () => {
|
|
740
|
+
const commit = await createWorktreeBaseline(target, tempDir, runner);
|
|
741
|
+
await runGit(
|
|
742
|
+
runner,
|
|
743
|
+
target.originalRoot,
|
|
744
|
+
["worktree", "add", "--detach", worktreePath, commit],
|
|
745
|
+
`Creating detached worktree from ${target.originalRoot}`,
|
|
746
|
+
);
|
|
747
|
+
added = true;
|
|
748
|
+
return commit;
|
|
749
|
+
});
|
|
711
750
|
const isolatedCwd = target.relativeCwd ? join(worktreePath, target.relativeCwd) : worktreePath;
|
|
712
751
|
// A requested subdirectory can be untracked/empty in the source worktree;
|
|
713
752
|
// recreate the directory so the child still starts at the equivalent path.
|
|
@@ -726,28 +765,30 @@ export async function createWorktreeIsolation(
|
|
|
726
765
|
);
|
|
727
766
|
} catch (error) {
|
|
728
767
|
const rollbackErrors: string[] = [];
|
|
729
|
-
|
|
768
|
+
await runInRepositoryWorktreeLock(target.originalRoot, async () => {
|
|
769
|
+
if (added || existsSync(worktreePath)) {
|
|
770
|
+
try {
|
|
771
|
+
await runGit(
|
|
772
|
+
runner,
|
|
773
|
+
target.originalRoot,
|
|
774
|
+
["worktree", "remove", "--force", worktreePath],
|
|
775
|
+
`Rolling back isolated worktree ${worktreePath}`,
|
|
776
|
+
);
|
|
777
|
+
} catch (rollbackError) {
|
|
778
|
+
rollbackErrors.push(rollbackError instanceof Error ? rollbackError.message : String(rollbackError));
|
|
779
|
+
}
|
|
780
|
+
}
|
|
730
781
|
try {
|
|
731
782
|
await runGit(
|
|
732
783
|
runner,
|
|
733
784
|
target.originalRoot,
|
|
734
|
-
["worktree", "
|
|
735
|
-
`
|
|
785
|
+
["worktree", "prune"],
|
|
786
|
+
`Pruning Git worktree metadata after setup failure`,
|
|
736
787
|
);
|
|
737
788
|
} catch (rollbackError) {
|
|
738
789
|
rollbackErrors.push(rollbackError instanceof Error ? rollbackError.message : String(rollbackError));
|
|
739
790
|
}
|
|
740
|
-
}
|
|
741
|
-
try {
|
|
742
|
-
await runGit(
|
|
743
|
-
runner,
|
|
744
|
-
target.originalRoot,
|
|
745
|
-
["worktree", "prune"],
|
|
746
|
-
`Pruning Git worktree metadata after setup failure`,
|
|
747
|
-
);
|
|
748
|
-
} catch (rollbackError) {
|
|
749
|
-
rollbackErrors.push(rollbackError instanceof Error ? rollbackError.message : String(rollbackError));
|
|
750
|
-
}
|
|
791
|
+
});
|
|
751
792
|
try {
|
|
752
793
|
await rm(tempDir, { recursive: true, force: true });
|
|
753
794
|
} catch (rollbackError) {
|
|
@@ -8,7 +8,7 @@ import type { SubagentRuntime } from "./runtime.ts";
|
|
|
8
8
|
import { projectResultsRoot } from "./thread-shared.ts";
|
|
9
9
|
|
|
10
10
|
export const WaitSchema = Type.Optional(Type.Boolean({
|
|
11
|
-
description: "Wait for
|
|
11
|
+
description: "Wait for results in this turn when they are needed for the next step. Defaults to false in TUI/RPC and true in print/JSON. Background results arrive after integration. Cancelling the parent stops unfinished runs.",
|
|
12
12
|
}));
|
|
13
13
|
|
|
14
14
|
/** In-turn wait for a new run or completed-run follow-up. Registration resolves it without a model-chosen
|
|
@@ -89,7 +89,9 @@ export async function awaitRunResults(
|
|
|
89
89
|
const settled = runtime.settledRuns.get(id);
|
|
90
90
|
if (settled) return `#${id} ${isFailedResult(settled) ? "failed" : "done"}`;
|
|
91
91
|
const live = monitor.findRun(id);
|
|
92
|
-
|
|
92
|
+
if (!live) return `#${id} …`;
|
|
93
|
+
const state = live.integrationStatus === "finalizing" ? "integrating" : live.status === "failed" ? "failed" : statusLabel(live.status);
|
|
94
|
+
return `#${id} ${state}`;
|
|
93
95
|
});
|
|
94
96
|
const text = `Waiting in-turn on ${runIds.length} run${runIds.length === 1 ? "" : "s"} · ${parts.join(", ")}`;
|
|
95
97
|
// The monitor notifies on every usage and activity change; this line
|
|
@@ -15,7 +15,7 @@ const COMPLETION_MAX_WAIT_MS = 1_000;
|
|
|
15
15
|
|
|
16
16
|
type TimerHandle = ReturnType<typeof setTimeout>;
|
|
17
17
|
|
|
18
|
-
|
|
18
|
+
interface CompletionBatcherOptions<T> {
|
|
19
19
|
emit: (items: T[]) => void;
|
|
20
20
|
}
|
|
21
21
|
|
|
@@ -119,7 +119,7 @@ export function perModelTotals(items: readonly CompletionMessageItem[]): string
|
|
|
119
119
|
/** Minimal shape of an active run, for the "others still running" footer. Kept
|
|
120
120
|
* decoupled from the monitor's RunView so this stays a pure, easily tested
|
|
121
121
|
* formatter; the caller maps its live runs into this shape. */
|
|
122
|
-
|
|
122
|
+
interface ActiveRunFoot {
|
|
123
123
|
id: number;
|
|
124
124
|
agent: string;
|
|
125
125
|
/** Optional content label (task-derived) shown next to the agent name. */
|
package/src/lifecycle/durable.ts
CHANGED
|
@@ -58,7 +58,7 @@ const RESULT_SUMMARY_MAX_CHARS = 4_000;
|
|
|
58
58
|
* that matters here survives a tolerance this wide. */
|
|
59
59
|
const BOOT_ID_TOLERANCE_MS = 60_000;
|
|
60
60
|
|
|
61
|
-
|
|
61
|
+
interface ThreadResultSummary {
|
|
62
62
|
agent: string;
|
|
63
63
|
task: string;
|
|
64
64
|
exitCode: number;
|
package/src/lifecycle/runtime.ts
CHANGED
|
@@ -27,7 +27,7 @@ import type { IsolationMode, WorktreeFinalization, WorktreeIsolation } from "../
|
|
|
27
27
|
|
|
28
28
|
export type ThreadState = "queued" | "running" | "interrupting" | "parked" | "completed" | "failed" | "stopped";
|
|
29
29
|
|
|
30
|
-
|
|
30
|
+
type ThreadLifecycleOperation = "stop" | "settle";
|
|
31
31
|
|
|
32
32
|
export interface SubagentThread {
|
|
33
33
|
/** Stable manifest identity; display ids are local to a Pi window. */
|
|
@@ -27,10 +27,10 @@ import {
|
|
|
27
27
|
type SubagentLiveEvent,
|
|
28
28
|
} from "../execution/spawn.ts";
|
|
29
29
|
import {
|
|
30
|
+
concurrencyAdmissionConflict,
|
|
30
31
|
persistThreadCheckpoint,
|
|
31
32
|
projectResultsRoot,
|
|
32
33
|
resolveDispatchModelRoute,
|
|
33
|
-
runInManagedRepositoryLane,
|
|
34
34
|
withWorktreeSystemPrompt,
|
|
35
35
|
type DispatchEnvironment,
|
|
36
36
|
type StartBackgroundInternal,
|
|
@@ -114,6 +114,10 @@ export function createBackgroundDispatcher(options: BackgroundDispatcherOptions)
|
|
|
114
114
|
return failedStartResult(agentName, task,
|
|
115
115
|
`Run #${owner.id} (${owner.agentName}) already owns this logical phase (${owner.state}). ${duplicateDispatchRemedy(owner)}`);
|
|
116
116
|
}
|
|
117
|
+
const capacityConflict = concurrencyAdmissionConflict(runtime, 1);
|
|
118
|
+
if (capacityConflict) {
|
|
119
|
+
return failedStartResult(agentName, task, `Subagent dispatch rejected: ${capacityConflict}`);
|
|
120
|
+
}
|
|
117
121
|
const projectRoot = getProjectRoot(runtime.configPath, originalCwd);
|
|
118
122
|
const sessionsRoot = join(projectRoot, "sessions");
|
|
119
123
|
const worktreesRoot = join(projectRoot, "worktrees");
|
|
@@ -179,7 +183,7 @@ export function createBackgroundDispatcher(options: BackgroundDispatcherOptions)
|
|
|
179
183
|
if (isolation === "shared") installCurrentLifecycle();
|
|
180
184
|
|
|
181
185
|
const onLive = makeLiveHandler(runId, generation);
|
|
182
|
-
const runGeneration = async (backgroundSignal: AbortSignal): Promise<void> => {
|
|
186
|
+
const runGeneration = async (backgroundSignal: AbortSignal, releaseSlot: () => void): Promise<void> => {
|
|
183
187
|
if (runtime.threads.get(runId)?.generation !== generation) return;
|
|
184
188
|
if (isolation === "worktree" && !worktree) {
|
|
185
189
|
let prepared: WorktreeIsolation | undefined;
|
|
@@ -255,6 +259,9 @@ export function createBackgroundDispatcher(options: BackgroundDispatcherOptions)
|
|
|
255
259
|
errorMessage,
|
|
256
260
|
dispatchFailed: true,
|
|
257
261
|
};
|
|
262
|
+
} finally {
|
|
263
|
+
// The child process has exited; Git integration no longer holds a concurrency slot.
|
|
264
|
+
releaseSlot();
|
|
258
265
|
}
|
|
259
266
|
|
|
260
267
|
// Stale work from a retired parent owns no publication or monitor updates.
|
|
@@ -451,10 +458,7 @@ export function installThreadLifecycle(thread: SubagentThread, deps: ThreadLifec
|
|
|
451
458
|
"finalizing",
|
|
452
459
|
worktreeGroupId(generationWorktree),
|
|
453
460
|
);
|
|
454
|
-
generationFinalization =
|
|
455
|
-
generationWorktree.originalRoot,
|
|
456
|
-
() => generationWorktree.finalize(),
|
|
457
|
-
);
|
|
461
|
+
generationFinalization = generationWorktree.finalize();
|
|
458
462
|
}
|
|
459
463
|
const finalization = await generationFinalization;
|
|
460
464
|
monitor.setIsolation(runId, "worktree", finalization.status, worktreeGroupId(generationWorktree));
|
|
@@ -1,8 +1,7 @@
|
|
|
1
1
|
/** Shared contracts and coordination primitives for logical sub-agent threads. */
|
|
2
2
|
|
|
3
3
|
import { utimesSync } from "node:fs";
|
|
4
|
-
import {
|
|
5
|
-
import { join, resolve } from "node:path";
|
|
4
|
+
import { join } from "node:path";
|
|
6
5
|
import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
|
|
7
6
|
import type { AgentConfig } from "../delegation/agents.ts";
|
|
8
7
|
import { BUILTIN_AGENT_NAMES, type AgentName, type SubagentsConfig, type ThinkingLevel } from "../configuration/config.ts";
|
|
@@ -16,8 +15,40 @@ import {
|
|
|
16
15
|
resolveThinkingLevel,
|
|
17
16
|
} from "../configuration/models.ts";
|
|
18
17
|
import type { SubagentRuntime, SubagentThread } from "./runtime.ts";
|
|
18
|
+
import { MAX_CONCURRENT_SUBAGENTS } from "../execution/background.ts";
|
|
19
19
|
import { getProjectRoot, type SingleResult } from "../execution/spawn.ts";
|
|
20
|
-
import {
|
|
20
|
+
import type { IsolationMode, WorktreeIsolation } from "../isolation/worktree.ts";
|
|
21
|
+
|
|
22
|
+
/** True while a logical thread holds one of the live concurrency slots.
|
|
23
|
+
* Settling runs (child finished, only Git integration remains), stopped runs,
|
|
24
|
+
* and restored parked records hold no live child process. */
|
|
25
|
+
function isConcurrencyActiveThread(
|
|
26
|
+
thread: Pick<SubagentThread, "state" | "retired" | "lifecycleOperation">,
|
|
27
|
+
): boolean {
|
|
28
|
+
if (thread.retired || thread.lifecycleOperation === "settle" || thread.lifecycleOperation === "stop") return false;
|
|
29
|
+
return thread.state === "queued" || thread.state === "running" || thread.state === "interrupting";
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
function activeConcurrencyThreads(runtime: Pick<SubagentRuntime, "threads">): SubagentThread[] {
|
|
33
|
+
return [...runtime.threads.values()].filter(isConcurrencyActiveThread);
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export function concurrencyAdmissionConflict(
|
|
37
|
+
runtime: Pick<SubagentRuntime, "threads">,
|
|
38
|
+
requestedCount: number,
|
|
39
|
+
): string | undefined {
|
|
40
|
+
if (requestedCount > MAX_CONCURRENT_SUBAGENTS) {
|
|
41
|
+
return `requested ${requestedCount} tasks, exceeding the maximum concurrency of ${MAX_CONCURRENT_SUBAGENTS}. Batch at most ${MAX_CONCURRENT_SUBAGENTS} independent, disjoint tasks at once; continue disjoint work in main and dispatch remaining phases after active runs finish.`;
|
|
42
|
+
}
|
|
43
|
+
const active = activeConcurrencyThreads(runtime);
|
|
44
|
+
const available = Math.max(0, MAX_CONCURRENT_SUBAGENTS - active.length);
|
|
45
|
+
if (requestedCount <= available) return undefined;
|
|
46
|
+
const activeIds = active.map((thread) => `#${thread.id}`).join(", ");
|
|
47
|
+
if (available === 0) {
|
|
48
|
+
return `concurrency limit of ${MAX_CONCURRENT_SUBAGENTS} active subagents is full (${activeIds} active). Do not duplicate their work; continue disjoint work in main until an active run finishes.`;
|
|
49
|
+
}
|
|
50
|
+
return `${active.length}/${MAX_CONCURRENT_SUBAGENTS} subagents are already active (${activeIds}), leaving ${available} free slot${available === 1 ? "" : "s"} for ${requestedCount} requested tasks. Dispatch at most ${available} independent task${available === 1 ? "" : "s"} now, or continue disjoint work in main until active runs finish.`;
|
|
51
|
+
}
|
|
21
52
|
|
|
22
53
|
/** Control operations must never wait forever on a settling generation: the
|
|
23
54
|
* queue task can legitimately spend minutes in worktree finalization (bounded
|
|
@@ -37,47 +68,6 @@ export function quiesced(promise: Promise<unknown>, timeoutMs: number = CONTROL_
|
|
|
37
68
|
]);
|
|
38
69
|
}
|
|
39
70
|
|
|
40
|
-
const managedRepositoryRootTails = new Map<string, Promise<void>>();
|
|
41
|
-
|
|
42
|
-
async function canonicalManagedRepositoryRoot(cwd: string): Promise<string> {
|
|
43
|
-
try {
|
|
44
|
-
// Repository identity does not depend on HEAD: empty repositories must
|
|
45
|
-
// serialize root and nested cwd requests under the same lane too.
|
|
46
|
-
return await resolveRepositoryRoot(cwd);
|
|
47
|
-
} catch {
|
|
48
|
-
try {
|
|
49
|
-
return await realpath(resolve(cwd));
|
|
50
|
-
} catch {
|
|
51
|
-
return resolve(cwd);
|
|
52
|
-
}
|
|
53
|
-
}
|
|
54
|
-
}
|
|
55
|
-
|
|
56
|
-
/** Serialize only worktree integration into the original checkout. */
|
|
57
|
-
export async function runInManagedRepositoryLane<T>(
|
|
58
|
-
cwd: string,
|
|
59
|
-
task: () => Promise<T>,
|
|
60
|
-
): Promise<T> {
|
|
61
|
-
const root = await canonicalManagedRepositoryRoot(cwd);
|
|
62
|
-
const key = process.platform === "win32" ? root.toLowerCase() : root;
|
|
63
|
-
const previous = managedRepositoryRootTails.get(key) ?? Promise.resolve();
|
|
64
|
-
let release!: () => void;
|
|
65
|
-
const gate = new Promise<void>((resolveGate) => {
|
|
66
|
-
release = resolveGate;
|
|
67
|
-
});
|
|
68
|
-
const tail = previous.catch(() => undefined).then(() => gate);
|
|
69
|
-
managedRepositoryRootTails.set(key, tail);
|
|
70
|
-
try {
|
|
71
|
-
await previous.catch(() => undefined);
|
|
72
|
-
return await task();
|
|
73
|
-
} finally {
|
|
74
|
-
release();
|
|
75
|
-
void tail.then(() => {
|
|
76
|
-
if (managedRepositoryRootTails.get(key) === tail) managedRepositoryRootTails.delete(key);
|
|
77
|
-
});
|
|
78
|
-
}
|
|
79
|
-
}
|
|
80
|
-
|
|
81
71
|
/** Best-effort recovery checkpoint. Interrupted work retains its artifacts;
|
|
82
72
|
* settled work drops the thread record. A failed write never stops the live run. */
|
|
83
73
|
export function persistThreadCheckpoint(
|
package/src/lifecycle/tools.ts
CHANGED
|
@@ -18,7 +18,7 @@ import { formatCompletionBlock } from "../presentation/format.ts";
|
|
|
18
18
|
import { emptyUsage } from "../execution/run-control.ts";
|
|
19
19
|
import { formatDuration, formatTaskSummary, monitor } from "../presentation/monitor.ts";
|
|
20
20
|
import type { SubagentRuntime, SubagentThread } from "./runtime.ts";
|
|
21
|
-
import { projectResultsRoot } from "./thread-shared.ts";
|
|
21
|
+
import { concurrencyAdmissionConflict, projectResultsRoot } from "./thread-shared.ts";
|
|
22
22
|
import { getResultError } from "../execution/spawn.ts";
|
|
23
23
|
|
|
24
24
|
function renderFirstLine(result: { content?: unknown }, label: string, theme: Theme): Text {
|
|
@@ -189,7 +189,7 @@ export function registerLookupTools(pi: ExtensionAPI, runtime: SubagentRuntime,
|
|
|
189
189
|
pi.registerTool({
|
|
190
190
|
name: "subagent_message",
|
|
191
191
|
label: "Subagent Message",
|
|
192
|
-
description: "Steer a running subagent, or continue a successfully completed run with a new bounded step in the same role and workspace. Steering waits for the child's RPC acknowledgement and reports queued or handled by an input hook; receipt is not proof of model execution, and status retains the latest acknowledgement. A continuation chooses its history with the context parameter.
|
|
192
|
+
description: "Steer a running subagent, or continue a successfully completed run with a new bounded step in the same role and workspace (within the 5-active-subagent limit). Steering waits for the child's RPC acknowledgement and reports queued or handled by an input hook; receipt is not proof of model execution, and status retains the latest acknowledgement. A continuation chooses its history with the context parameter. Omit wait so main continues disjoint work in parallel without duplicating leased scopes; use wait:true only when no disjoint main work remains (one-shot print/JSON sessions wait by default).",
|
|
193
193
|
exposure: "model-only",
|
|
194
194
|
executionMode: "parallel",
|
|
195
195
|
parameters: Type.Object({
|
|
@@ -226,6 +226,8 @@ export function registerLookupTools(pi: ExtensionAPI, runtime: SubagentRuntime,
|
|
|
226
226
|
: "messages require a running or successfully completed run. Results arrive automatically."}`);
|
|
227
227
|
}
|
|
228
228
|
if (!dispatchCore) return fail("Follow-up dispatch is unavailable in this process.");
|
|
229
|
+
const capacityConflict = concurrencyAdmissionConflict(runtime, 1);
|
|
230
|
+
if (capacityConflict) return fail(`Could not continue #${thread.id}: ${capacityConflict}`);
|
|
229
231
|
const context = params.context ?? "auto";
|
|
230
232
|
const sourceFile = context !== "summary" && thread.sessionDir && thread.sessionId
|
|
231
233
|
? findSessionFile(thread.sessionDir, thread.sessionId) : undefined;
|
|
@@ -235,7 +237,7 @@ export function registerLookupTools(pi: ExtensionAPI, runtime: SubagentRuntime,
|
|
|
235
237
|
let fallbackReason = context === "auto" && !sourceFile ? "Retained session is unavailable." : undefined;
|
|
236
238
|
let copyDir: string | undefined;
|
|
237
239
|
try {
|
|
238
|
-
|
|
240
|
+
const config = await loadConfig(runtime.configPath);
|
|
239
241
|
if (sourceFile) {
|
|
240
242
|
const root = join(getProjectRoot(runtime.configPath, thread.cwd), "sessions");
|
|
241
243
|
await mkdir(root, { recursive: true });
|
|
@@ -251,8 +253,13 @@ export function registerLookupTools(pi: ExtensionAPI, runtime: SubagentRuntime,
|
|
|
251
253
|
fallbackReason = "Retained session became unavailable before it could be copied.";
|
|
252
254
|
}
|
|
253
255
|
}
|
|
256
|
+
// Another dispatch can update the shared environment while the session
|
|
257
|
+
// is copied. Set this caller's context immediately before admission.
|
|
258
|
+
dispatchCore.setEnvironment({ ctx, config, agents: loadBuiltinAgents() });
|
|
254
259
|
if (_signal?.aborted) throw new Error("Follow-up cancelled before dispatch.");
|
|
255
|
-
if (thread.retired || thread.lifecycleOperation || thread.state !== "completed")
|
|
260
|
+
if (runtime.threads.get(thread.id) !== thread || thread.retired || thread.lifecycleOperation || thread.state !== "completed") {
|
|
261
|
+
throw new Error("The source run changed while the follow-up was prepared.");
|
|
262
|
+
}
|
|
256
263
|
const selectedContext = copyDir ? "session" : "summary";
|
|
257
264
|
const task = copyDir
|
|
258
265
|
? `Follow-up to run #${thread.id}:\n${params.message}`
|
|
@@ -280,7 +287,7 @@ export function registerLookupTools(pi: ExtensionAPI, runtime: SubagentRuntime,
|
|
|
280
287
|
};
|
|
281
288
|
}
|
|
282
289
|
return {
|
|
283
|
-
content: [{ type: "text" as const, text: `${receipt} started; results arrive automatically.
|
|
290
|
+
content: [{ type: "text" as const, text: `${receipt} started; results arrive automatically. Do not duplicate its scope; continue disjoint work in main, then use the result to finish the task.` }], details,
|
|
284
291
|
};
|
|
285
292
|
} catch (error) {
|
|
286
293
|
if (copyDir) await rm(copyDir, { recursive: true, force: true }).catch(() => undefined);
|
|
@@ -62,7 +62,7 @@ export function formatUsage(usage: UsageStats): string {
|
|
|
62
62
|
return [turns, formatUsageCompact(usage)].filter(Boolean).join(" ");
|
|
63
63
|
}
|
|
64
64
|
|
|
65
|
-
|
|
65
|
+
interface CompletionFormatOptions {
|
|
66
66
|
/** Project-scoped directory the full result is written to when the output
|
|
67
67
|
* is truncated: <projectRoot>/results. */
|
|
68
68
|
resultRoot?: string;
|
|
@@ -20,7 +20,7 @@ import type { IsolationMode, WorktreeFinalizationStatus } from "../isolation/wor
|
|
|
20
20
|
// ---------------------------------------------------------------------------
|
|
21
21
|
|
|
22
22
|
/** A queued run is preparing its child process; execution has no capacity wait. */
|
|
23
|
-
|
|
23
|
+
type RunStatus = "queued" | "running" | "interrupting" | "parked" | "done" | "failed";
|
|
24
24
|
|
|
25
25
|
export function isRunActiveStatus(status: RunStatus): boolean {
|
|
26
26
|
return status === "queued" || status === "running" || status === "interrupting";
|
|
@@ -29,7 +29,7 @@ export function isRunActiveStatus(status: RunStatus): boolean {
|
|
|
29
29
|
/** Durable integration projection of a worktree-isolated run: pending before
|
|
30
30
|
* settlement, finalizing while the patch is applied/cleaned up, then the
|
|
31
31
|
* terminal WorktreeFinalizationStatus. */
|
|
32
|
-
|
|
32
|
+
type RunIntegrationStatus = "pending" | "finalizing" | WorktreeFinalizationStatus;
|
|
33
33
|
|
|
34
34
|
export interface RunView {
|
|
35
35
|
id: number;
|