brl-subagent 2.5.2 → 2.7.0
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/AGENT.md +14 -11
- package/README.md +30 -6
- package/package.json +8 -5
- package/src/concurrency.ts +156 -44
- package/src/dispatch-line.ts +144 -0
- package/src/history.ts +13 -1
- package/src/index.ts +642 -743
- package/src/loader.ts +178 -0
- package/src/mode-prologue.ts +169 -0
- package/src/model-availability.ts +13 -1
- package/src/params.ts +252 -67
- package/src/prelude.ts +279 -3
- package/src/presets.ts +56 -148
- package/src/project-flags.ts +58 -0
- package/src/run-registry.ts +4 -1
- package/src/schema.ts +69 -51
- package/src/session-manager.ts +790 -91
- package/src/state.ts +29 -4
- package/src/store-permissions.ts +98 -0
- package/src/templates.ts +65 -121
- package/src/transcript.ts +5 -2
- package/src/transport-retry.ts +90 -0
- package/src/tui-format.ts +382 -4
- package/src/tui.ts +997 -867
- package/src/types.ts +54 -25
- package/src/validate.ts +41 -0
package/src/session-manager.ts
CHANGED
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
// Purpose: Background execution: SDK sessions (`createAgentSession`), agent records, timeouts, steering, and settle paths.
|
|
2
2
|
import { randomUUID } from 'crypto';
|
|
3
3
|
import { basename, dirname, join, resolve } from 'path';
|
|
4
|
-
import {
|
|
4
|
+
import { writeFileSync, readFileSync, readdirSync, existsSync, rmSync, statSync } from 'fs';
|
|
5
|
+
import type { Dirent } from 'fs';
|
|
5
6
|
import type { BackgroundAgent, AgentStatus, GitMode, RecoveryMode, SubagentResult, SubagentRun, ThinkingLevel, SubagentToolOptions, UsageStats, ErrorCategory } from './types';
|
|
6
7
|
import { EMPTY_USAGE, classifyError, classifyTerminalOutcome, isProviderError, coherentFailureReason, SUBAGENT_ABORTED_MESSAGE } from './types';
|
|
7
8
|
import { accumulateUsage } from './runner';
|
|
@@ -15,7 +16,9 @@ import { getCurrentBranch, getHeadState, restoreHead, createWorkBranch, captureD
|
|
|
15
16
|
import type { HeadState } from './git';
|
|
16
17
|
import { normalizeTimeout, DEFAULT_BACKGROUND_DEADLINE_MS } from './validate';
|
|
17
18
|
import { currentProcessOwner } from './recovery';
|
|
18
|
-
import { persistRunRecord } from './run-registry';
|
|
19
|
+
import { persistRunRecord, listInflightRuns, type InflightRun } from './run-registry';
|
|
20
|
+
import { isTransportRetryable } from './transport-retry';
|
|
21
|
+
import { ensureOwnerOnlyDir, repairOwnerOnlyFiles } from './store-permissions';
|
|
19
22
|
|
|
20
23
|
const log = createLogger('brl-subagent');
|
|
21
24
|
import type { ExtensionAPI, ExtensionContext } from '@earendil-works/pi-coding-agent';
|
|
@@ -75,7 +78,20 @@ export function __setStorageDir(dir: string): void {
|
|
|
75
78
|
function ensureStorageDir(): void {
|
|
76
79
|
// F6 (issue #29): records hold the full task/result conversation — the dir
|
|
77
80
|
// must be owner-only (0o700) so other local users cannot list the files.
|
|
78
|
-
|
|
81
|
+
// Issue #408: a create-only `mode` never repaired a pre-existing store, so
|
|
82
|
+
// this runs on EVERY use and chmods a wider directory back to 0o700.
|
|
83
|
+
ensureOwnerOnlyDir(STORAGE_DIR);
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/**
|
|
87
|
+
* The root that holds the per-run SDK session dirs. The dir mode is what denies
|
|
88
|
+
* other local users traversal; repairing it here keeps a pre-F6 `.pi` store
|
|
89
|
+
* from exposing every retained conversation beneath it.
|
|
90
|
+
*/
|
|
91
|
+
function ensureSessionsRoot(): string {
|
|
92
|
+
const root = join(STORAGE_DIR, SESSIONS_SUBDIR);
|
|
93
|
+
ensureOwnerOnlyDir(root);
|
|
94
|
+
return root;
|
|
79
95
|
}
|
|
80
96
|
|
|
81
97
|
// ---------------------------------------------------------------------------
|
|
@@ -95,9 +111,14 @@ function ensureStorageDir(): void {
|
|
|
95
111
|
// D5 measurement (one week of use):
|
|
96
112
|
// du -sh .pi/subagents/sessions
|
|
97
113
|
// find .pi/subagents/sessions -name '*.jsonl' | wc -l
|
|
98
|
-
// The expected steady state
|
|
99
|
-
//
|
|
100
|
-
//
|
|
114
|
+
// The expected steady state between runs is EMPTY, plus:
|
|
115
|
+
// - one dir per currently-interrupted run (kept by design, D3), and
|
|
116
|
+
// - up to RETAINED_MAX_DIRS transport-failed dirs bearing the retention
|
|
117
|
+
// marker (issue #404 — bounded by the settle-time sweep, see the #404
|
|
118
|
+
// block below).
|
|
119
|
+
// These two classes are the documented exceptions: a session dir whose name is
|
|
120
|
+
// NOT one of those is a prune-path regression. Judge by the marker file
|
|
121
|
+
// (`.transport-retained`), not by the raw count. There is no runtime metric.
|
|
101
122
|
// ---------------------------------------------------------------------------
|
|
102
123
|
|
|
103
124
|
/** Subdirectory of the agent-record store that holds per-run session dirs. */
|
|
@@ -113,6 +134,26 @@ export function backgroundSessionDir(id: string): string {
|
|
|
113
134
|
return join(STORAGE_DIR, SESSIONS_SUBDIR, id);
|
|
114
135
|
}
|
|
115
136
|
|
|
137
|
+
/**
|
|
138
|
+
* Issue #404: the ABSOLUTE path a retry preamble may name for a retained session.
|
|
139
|
+
* `backgroundSessionDir` is relative to the conductor's storage root (the default
|
|
140
|
+
* `.pi/subagents`); the retried child resolves paths against ITS OWN cwd, which can
|
|
141
|
+
* differ in worktree/branch mode — so the pointer must be resolved HERE, once.
|
|
142
|
+
*/
|
|
143
|
+
export function retainedSessionPointer(id: string): string {
|
|
144
|
+
return resolve(backgroundSessionDir(id));
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
/**
|
|
148
|
+
* TRUE when `dir` is shaped exactly like `<...>/sessions/<id>` — the one
|
|
149
|
+
* precondition every path that touches a session directory requires before it
|
|
150
|
+
* can delete or brand it.
|
|
151
|
+
*/
|
|
152
|
+
function isSessionDirFor(id: string, dir: string): boolean {
|
|
153
|
+
const target = resolve(dir);
|
|
154
|
+
return basename(target) === id && basename(dirname(target)) === SESSIONS_SUBDIR;
|
|
155
|
+
}
|
|
156
|
+
|
|
116
157
|
/**
|
|
117
158
|
* Remove ONE per-run session directory. Defensive by construction: the target
|
|
118
159
|
* must look like `<...>/sessions/<id>` (basename === id, parent basename ===
|
|
@@ -126,13 +167,12 @@ function pruneSessionDir(id: string, dir: string): void {
|
|
|
126
167
|
log.error(`Refusing to prune session dir for invalid id: ${id}`);
|
|
127
168
|
return;
|
|
128
169
|
}
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
log.error(`Refusing to prune session dir outside ${SESSIONS_SUBDIR}/: ${target}`);
|
|
170
|
+
if (!isSessionDirFor(id, dir)) {
|
|
171
|
+
log.error(`Refusing to prune session dir outside ${SESSIONS_SUBDIR}/: ${resolve(dir)}`);
|
|
132
172
|
return;
|
|
133
173
|
}
|
|
134
174
|
try {
|
|
135
|
-
rmSync(
|
|
175
|
+
rmSync(resolve(dir), { recursive: true, force: true });
|
|
136
176
|
} catch (err) {
|
|
137
177
|
// Pruning is hygiene — it must never break execution or a settle path.
|
|
138
178
|
log.warn(`Failed to prune session dir for ${id}`, {
|
|
@@ -162,6 +202,173 @@ export function pruneBackgroundSession(id: string): void {
|
|
|
162
202
|
pruneSessionDir(id, backgroundSessionDir(id));
|
|
163
203
|
}
|
|
164
204
|
|
|
205
|
+
// ---------------------------------------------------------------------------
|
|
206
|
+
// Issue #404: bounded retention of a transport-failed run's session.
|
|
207
|
+
//
|
|
208
|
+
// The #401 resume preamble named no artifact beyond the working tree and the
|
|
209
|
+
// bank, because the SDK session dir — the only place the conversation lives —
|
|
210
|
+
// was pruned on every terminal settle. A transport failure is the ONE class a
|
|
211
|
+
// retry re-dispatches automatically, so it is the one class whose session is
|
|
212
|
+
// worth keeping: the retry's child reads the tail of it to recover what attempt
|
|
213
|
+
// 1 had already worked out.
|
|
214
|
+
//
|
|
215
|
+
// Retention is an OPTIMIZATION; boundedness is the invariant. A retained dir is
|
|
216
|
+
// branded with RETAINED_MARKER, and the sweep at the same choke points enforces
|
|
217
|
+
// the caps below over MARKED dirs only — an interrupted run's dir (kept by
|
|
218
|
+
// design, unmarked) and the agent-record store are never candidates. Nothing in
|
|
219
|
+
// this block may throw into a settle path.
|
|
220
|
+
//
|
|
221
|
+
// Root-local, like the U3 D5 boundary above: the sweep walks the sessions root
|
|
222
|
+
// the settled run actually wrote to, so a dir retained under a previous
|
|
223
|
+
// STORAGE_DIR root is not reclaimed by a later settle under a new one.
|
|
224
|
+
// ---------------------------------------------------------------------------
|
|
225
|
+
|
|
226
|
+
/** Brand on a retained session dir — the sweep's only selection criterion. */
|
|
227
|
+
const RETAINED_MARKER = '.transport-retained';
|
|
228
|
+
/** Keep at most this many retained dirs (oldest marker mtime goes first). */
|
|
229
|
+
const RETAINED_MAX_DIRS = 5;
|
|
230
|
+
/** Keep the marked set under this total on-disk size. */
|
|
231
|
+
const RETAINED_MAX_TOTAL_BYTES = 50 * 1024 * 1024;
|
|
232
|
+
/** Drop a retained dir once its marker is older than this. */
|
|
233
|
+
const RETAINED_MAX_AGE_MS = 14 * 24 * 60 * 60 * 1000;
|
|
234
|
+
/**
|
|
235
|
+
* Below this size there is nothing worth a retention slot: a run that died on a
|
|
236
|
+
* connection error before its first assistant turn leaves a start-entry-only
|
|
237
|
+
* file (the SDK writes the header at create()), and pointing a retry at a
|
|
238
|
+
* contentless file is worse than not pointing at all.
|
|
239
|
+
*/
|
|
240
|
+
const RETAINED_MIN_BYTES = 2 * 1024;
|
|
241
|
+
|
|
242
|
+
/**
|
|
243
|
+
* Recursive on-disk size of `dir`. Unreadable entries count as zero and
|
|
244
|
+
* symlinks are never followed, so the walk cannot escape `dir`.
|
|
245
|
+
*/
|
|
246
|
+
function dirTotalBytes(dir: string): number {
|
|
247
|
+
let total = 0;
|
|
248
|
+
const stack = [dir];
|
|
249
|
+
while (stack.length > 0) {
|
|
250
|
+
const current = stack.pop()!;
|
|
251
|
+
let entries: Dirent[];
|
|
252
|
+
try {
|
|
253
|
+
entries = readdirSync(current, { withFileTypes: true });
|
|
254
|
+
} catch {
|
|
255
|
+
continue; // raced with a delete — size it as absent
|
|
256
|
+
}
|
|
257
|
+
for (const entry of entries) {
|
|
258
|
+
const child = join(current, entry.name);
|
|
259
|
+
if (entry.isDirectory()) {
|
|
260
|
+
stack.push(child);
|
|
261
|
+
} else if (entry.isFile()) {
|
|
262
|
+
try {
|
|
263
|
+
total += statSync(child).size;
|
|
264
|
+
} catch {
|
|
265
|
+
// vanished mid-walk — ignore
|
|
266
|
+
}
|
|
267
|
+
}
|
|
268
|
+
}
|
|
269
|
+
}
|
|
270
|
+
return total;
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
/**
|
|
274
|
+
* Enforce the #404 caps over the marked session dirs beside `currentDir`.
|
|
275
|
+
*
|
|
276
|
+
* `currentDir` is EXEMPT for the settle that just marked it. Without that, a
|
|
277
|
+
* single over-cap dir would be deleted at the instant it was retained — and the
|
|
278
|
+
* largest, most salvageable runs are exactly the ones that would lose. So one
|
|
279
|
+
* dir may overshoot by one; the NEXT settle reclaims it.
|
|
280
|
+
*
|
|
281
|
+
* Best-effort by construction: selection is guarded, and deletion goes through
|
|
282
|
+
* the validated, never-throwing `pruneSessionDir`.
|
|
283
|
+
*/
|
|
284
|
+
function sweepRetainedSessions(currentDir: string): void {
|
|
285
|
+
const current = resolve(currentDir);
|
|
286
|
+
const root = dirname(current);
|
|
287
|
+
if (basename(root) !== SESSIONS_SUBDIR) return; // never walk outside sessions/
|
|
288
|
+
let names: string[];
|
|
289
|
+
try {
|
|
290
|
+
names = readdirSync(root, { withFileTypes: true })
|
|
291
|
+
.filter((entry) => entry.isDirectory())
|
|
292
|
+
.map((entry) => entry.name);
|
|
293
|
+
} catch {
|
|
294
|
+
return; // root missing/unreadable — nothing to bound
|
|
295
|
+
}
|
|
296
|
+
const now = Date.now();
|
|
297
|
+
const retained: Array<{ dir: string; size: number; markedAt: number }> = [];
|
|
298
|
+
for (const name of names) {
|
|
299
|
+
// Only ids our own spawn can mint are sweepable; a foreign name is left for
|
|
300
|
+
// a human instead of being deleted on a guess.
|
|
301
|
+
try {
|
|
302
|
+
assertSafeAgentId(name);
|
|
303
|
+
} catch {
|
|
304
|
+
continue;
|
|
305
|
+
}
|
|
306
|
+
const dir = join(root, name);
|
|
307
|
+
const marker = join(dir, RETAINED_MARKER);
|
|
308
|
+
// UNMARKED ⇒ interrupted (D3), live, or foreign. Never a candidate.
|
|
309
|
+
if (!existsSync(marker)) continue;
|
|
310
|
+
try {
|
|
311
|
+
retained.push({ dir, size: dirTotalBytes(dir), markedAt: statSync(marker).mtimeMs });
|
|
312
|
+
} catch {
|
|
313
|
+
// marker disappeared between the check and the stat — re-read as unmarked
|
|
314
|
+
}
|
|
315
|
+
}
|
|
316
|
+
retained.sort((a, b) => a.markedAt - b.markedAt);
|
|
317
|
+
let count = retained.length;
|
|
318
|
+
let total = retained.reduce((sum, entry) => sum + entry.size, 0);
|
|
319
|
+
for (const entry of retained) {
|
|
320
|
+
if (entry.dir === current) continue; // this settle's own dir — see the doc comment
|
|
321
|
+
// Ages ascend with the sort, so the oldest candidate's age speaks for the rest.
|
|
322
|
+
const tooMany = count > RETAINED_MAX_DIRS;
|
|
323
|
+
const tooBig = total > RETAINED_MAX_TOTAL_BYTES;
|
|
324
|
+
const tooOld = now - entry.markedAt > RETAINED_MAX_AGE_MS;
|
|
325
|
+
if (!tooMany && !tooBig && !tooOld) break;
|
|
326
|
+
pruneSessionDir(basename(entry.dir), entry.dir);
|
|
327
|
+
count -= 1;
|
|
328
|
+
total -= entry.size;
|
|
329
|
+
}
|
|
330
|
+
}
|
|
331
|
+
|
|
332
|
+
/**
|
|
333
|
+
* Retain `dir` for the #401 resume preamble: brand it with the retention marker
|
|
334
|
+
* (its mtime is the recency source) and enforce the caps.
|
|
335
|
+
*
|
|
336
|
+
* Returns TRUE when the dir is now retained — the caller then SKIPS the prune —
|
|
337
|
+
* and FALSE when retention was skipped or failed, in which case the caller must
|
|
338
|
+
* prune as before. Fail-closed on purpose: retention is an optimization, while
|
|
339
|
+
* boundedness is the invariant, and a dir whose marker write failed would be
|
|
340
|
+
* invisible to the sweep forever.
|
|
341
|
+
*/
|
|
342
|
+
function retainSessionDir(id: string, dir: string): boolean {
|
|
343
|
+
try {
|
|
344
|
+
if (!isSessionDirFor(id, dir) || !existsSync(dir)) return false;
|
|
345
|
+
// Issue #408: a retained settle is the longest-lived session dir — repair
|
|
346
|
+
// the dir mode (the traversal boundary) and its files while it is cheap.
|
|
347
|
+
ensureOwnerOnlyDir(dir);
|
|
348
|
+
repairOwnerOnlyFiles(dir);
|
|
349
|
+
if (dirTotalBytes(dir) < RETAINED_MIN_BYTES) return false;
|
|
350
|
+
writeFileSync(join(dir, RETAINED_MARKER), `${new Date().toISOString()}\n`, {
|
|
351
|
+
encoding: 'utf-8',
|
|
352
|
+
mode: 0o600,
|
|
353
|
+
});
|
|
354
|
+
} catch (err) {
|
|
355
|
+
log.warn(`Not retaining session dir for ${id} (marker write failed)`, {
|
|
356
|
+
error: err instanceof Error ? err.message : String(err),
|
|
357
|
+
});
|
|
358
|
+
return false;
|
|
359
|
+
}
|
|
360
|
+
try {
|
|
361
|
+
sweepRetainedSessions(dir);
|
|
362
|
+
} catch (err) {
|
|
363
|
+
// The sweep guards its own steps; this is belt-and-braces so a settle can
|
|
364
|
+
// never be broken by hygiene.
|
|
365
|
+
log.warn(`Retained-session sweep failed for ${id}`, {
|
|
366
|
+
error: err instanceof Error ? err.message : String(err),
|
|
367
|
+
});
|
|
368
|
+
}
|
|
369
|
+
return true;
|
|
370
|
+
}
|
|
371
|
+
|
|
165
372
|
/**
|
|
166
373
|
* Persist agent record to disk
|
|
167
374
|
*/
|
|
@@ -257,6 +464,455 @@ export function listPersistedAgents(): BackgroundAgent[] {
|
|
|
257
464
|
return records;
|
|
258
465
|
}
|
|
259
466
|
|
|
467
|
+
// ---------------------------------------------------------------------------
|
|
468
|
+
// Issue #396: retry lineage for `get_subagent_result`.
|
|
469
|
+
//
|
|
470
|
+
// A run id is not necessarily the id of the run that actually finished it: the
|
|
471
|
+
// background transport auto-retry (#365) re-dispatches the same logical task as
|
|
472
|
+
// `attempt: 2`, and a manual `retryRunId` can mint attempt 3 whose `resumeOf`
|
|
473
|
+
// points at attempt 2. The durable agent store therefore has to be consulted
|
|
474
|
+
// before "not found" or a terminal source status is reported as final.
|
|
475
|
+
//
|
|
476
|
+
// Two properties drive the implementation:
|
|
477
|
+
//
|
|
478
|
+
// 1. ID FORM — notices render the first 8 hex characters of a UUID, while
|
|
479
|
+
// `resumeOf`/record ids are full UUIDs. Resolve a unique 8-hex prefix
|
|
480
|
+
// before either the record read or the lineage match; an ambiguous prefix
|
|
481
|
+
// is refused explicitly rather than guessed.
|
|
482
|
+
// 2. COST — the agent store is large and never pruned (measured 2026-10:
|
|
483
|
+
// ~1160 records / ~116 MB on the live store; a full parse is ~0.5 s per
|
|
484
|
+
// tool call, and a synthetic 100 KB-payload fixture of the same shape
|
|
485
|
+
// measures ~225 MB). This reader
|
|
486
|
+
// stats first, keeps only records inside a 7-day mtime window, caps the
|
|
487
|
+
// number read at `RETRY_SCAN_CAP`, and extracts just the identity fields
|
|
488
|
+
// with a top-level scanner instead of JSON-parsing result.messages.
|
|
489
|
+
//
|
|
490
|
+
// Deliberately NOT `listPersistedAgents()`: that sweep full-parses every
|
|
491
|
+
// record, and its "production has no caller" comment documents that decision.
|
|
492
|
+
// ---------------------------------------------------------------------------
|
|
493
|
+
|
|
494
|
+
/** How far back the lineage reader looks (mtime of the record file). */
|
|
495
|
+
export const RETRY_SCAN_WINDOW_MS = 7 * 24 * 60 * 60 * 1000;
|
|
496
|
+
|
|
497
|
+
/** Upper bound on records read for one lineage answer. */
|
|
498
|
+
const RETRY_SCAN_CAP = 200;
|
|
499
|
+
|
|
500
|
+
/** The scan window in whole days (the user-facing caveat derives from it). */
|
|
501
|
+
export const RETRY_SCAN_WINDOW_DAYS = RETRY_SCAN_WINDOW_MS / (24 * 60 * 60 * 1000);
|
|
502
|
+
|
|
503
|
+
/** The short form rendered by notices: the first 8 hex characters of a UUID. */
|
|
504
|
+
const SHORT_AGENT_ID_RE = /^[0-9a-f]{8}$/i;
|
|
505
|
+
|
|
506
|
+
const RETRY_IDENTITY_KEYS: ReadonlySet<string> = new Set([
|
|
507
|
+
'id',
|
|
508
|
+
'dispatchId',
|
|
509
|
+
'resumeOf',
|
|
510
|
+
'attempt',
|
|
511
|
+
'status',
|
|
512
|
+
'startedAt',
|
|
513
|
+
]);
|
|
514
|
+
|
|
515
|
+
const AGENT_STATUSES: ReadonlySet<string> = new Set([
|
|
516
|
+
'pending',
|
|
517
|
+
'running',
|
|
518
|
+
'steered',
|
|
519
|
+
'completed',
|
|
520
|
+
'failed',
|
|
521
|
+
'stopped',
|
|
522
|
+
]);
|
|
523
|
+
|
|
524
|
+
/** One record's lineage-relevant fields — never its result/transcript. */
|
|
525
|
+
export interface RetryRecordIdentity {
|
|
526
|
+
id: string;
|
|
527
|
+
dispatchId?: string;
|
|
528
|
+
resumeOf?: string;
|
|
529
|
+
attempt: number;
|
|
530
|
+
status: AgentStatus;
|
|
531
|
+
/** Epoch milliseconds (agent records store ms; registry ISO is normalised). */
|
|
532
|
+
startedAt: number;
|
|
533
|
+
}
|
|
534
|
+
|
|
535
|
+
export type AgentIdResolution =
|
|
536
|
+
| { kind: 'resolved'; id: string }
|
|
537
|
+
| { kind: 'ambiguous'; matches: string[] }
|
|
538
|
+
| { kind: 'unresolved'; id: string };
|
|
539
|
+
|
|
540
|
+
export interface RetryLineage {
|
|
541
|
+
id: string;
|
|
542
|
+
/** Every known attempt of the logical dispatch, ordered by attempt/start. */
|
|
543
|
+
family: RetryRecordIdentity[];
|
|
544
|
+
/** The requested id's own record, when it exists. */
|
|
545
|
+
found: RetryRecordIdentity | null;
|
|
546
|
+
/** The newest attempt in the family. */
|
|
547
|
+
latest: RetryRecordIdentity | null;
|
|
548
|
+
/** Registry entries that name the id itself or a member of its family. */
|
|
549
|
+
inflight: InflightRun[];
|
|
550
|
+
}
|
|
551
|
+
|
|
552
|
+
function isSafeAgentId(id: string): boolean {
|
|
553
|
+
try {
|
|
554
|
+
assertSafeAgentId(id);
|
|
555
|
+
return true;
|
|
556
|
+
} catch {
|
|
557
|
+
return false;
|
|
558
|
+
}
|
|
559
|
+
}
|
|
560
|
+
|
|
561
|
+
export function isTerminalAgentStatus(status: AgentStatus): boolean {
|
|
562
|
+
return status === 'completed' || status === 'failed' || status === 'stopped';
|
|
563
|
+
}
|
|
564
|
+
|
|
565
|
+
function isAgentStatus(value: unknown): value is AgentStatus {
|
|
566
|
+
return typeof value === 'string' && AGENT_STATUSES.has(value);
|
|
567
|
+
}
|
|
568
|
+
|
|
569
|
+
function normalizeStartedAt(value: unknown): number | null {
|
|
570
|
+
if (typeof value === 'number' && Number.isFinite(value)) return value;
|
|
571
|
+
if (typeof value === 'string') {
|
|
572
|
+
const parsed = Date.parse(value);
|
|
573
|
+
if (Number.isFinite(parsed)) return parsed;
|
|
574
|
+
}
|
|
575
|
+
return null;
|
|
576
|
+
}
|
|
577
|
+
|
|
578
|
+
function safeListInflightRuns(): InflightRun[] {
|
|
579
|
+
try {
|
|
580
|
+
return listInflightRuns();
|
|
581
|
+
} catch {
|
|
582
|
+
return [];
|
|
583
|
+
}
|
|
584
|
+
}
|
|
585
|
+
|
|
586
|
+
/**
|
|
587
|
+
* Resolve the tool's id parameter before any record lookup. A full UUID passes
|
|
588
|
+
* through; a unique 8-hex prefix resolves to its full id; multiple matches are
|
|
589
|
+
* returned as `ambiguous` (fail closed); anything else stays unresolved and
|
|
590
|
+
* follows today's not-found path.
|
|
591
|
+
*
|
|
592
|
+
* Candidates come from live records, the agent store's file names, and the
|
|
593
|
+
* in-flight registry — every surface on which an id can currently exist.
|
|
594
|
+
*/
|
|
595
|
+
export function resolveAgentId(raw: string): AgentIdResolution {
|
|
596
|
+
if (isSafeAgentId(raw)) return { kind: 'resolved', id: raw };
|
|
597
|
+
if (!SHORT_AGENT_ID_RE.test(raw)) return { kind: 'unresolved', id: raw };
|
|
598
|
+
|
|
599
|
+
const needle = raw.toLowerCase();
|
|
600
|
+
const matches = new Set<string>();
|
|
601
|
+
|
|
602
|
+
for (const id of agents.keys()) {
|
|
603
|
+
if (id.toLowerCase().startsWith(needle)) matches.add(id);
|
|
604
|
+
}
|
|
605
|
+
|
|
606
|
+
try {
|
|
607
|
+
if (existsSync(STORAGE_DIR)) {
|
|
608
|
+
for (const file of readdirSync(STORAGE_DIR)) {
|
|
609
|
+
if (!file.endsWith('.json')) continue;
|
|
610
|
+
const id = file.slice(0, -'.json'.length);
|
|
611
|
+
if (isSafeAgentId(id) && id.toLowerCase().startsWith(needle)) matches.add(id);
|
|
612
|
+
}
|
|
613
|
+
}
|
|
614
|
+
} catch {
|
|
615
|
+
// An unreadable store is not a prefix match — fall through to the registry.
|
|
616
|
+
}
|
|
617
|
+
|
|
618
|
+
for (const run of safeListInflightRuns()) {
|
|
619
|
+
if (run.id.toLowerCase().startsWith(needle)) matches.add(run.id);
|
|
620
|
+
}
|
|
621
|
+
|
|
622
|
+
const ids = [...matches].sort();
|
|
623
|
+
if (ids.length === 1) return { kind: 'resolved', id: ids[0] };
|
|
624
|
+
if (ids.length > 1) return { kind: 'ambiguous', matches: ids };
|
|
625
|
+
return { kind: 'unresolved', id: raw };
|
|
626
|
+
}
|
|
627
|
+
|
|
628
|
+
// ---------------------------------------------------------------------------
|
|
629
|
+
// Shallow JSON identity reader
|
|
630
|
+
// ---------------------------------------------------------------------------
|
|
631
|
+
|
|
632
|
+
type JsonScalar = string | number | boolean | null;
|
|
633
|
+
|
|
634
|
+
function skipWhitespace(text: string, index: number): number {
|
|
635
|
+
let i = index;
|
|
636
|
+
while (i < text.length && /\s/.test(text[i])) i += 1;
|
|
637
|
+
return i;
|
|
638
|
+
}
|
|
639
|
+
|
|
640
|
+
/** Read one JSON string starting at `start` (which must be `"`). */
|
|
641
|
+
function readJsonStringAt(text: string, start: number): { value: string; end: number } {
|
|
642
|
+
let i = start + 1;
|
|
643
|
+
let escaped = false;
|
|
644
|
+
while (i < text.length) {
|
|
645
|
+
const char = text[i];
|
|
646
|
+
if (escaped) {
|
|
647
|
+
escaped = false;
|
|
648
|
+
i += 1;
|
|
649
|
+
continue;
|
|
650
|
+
}
|
|
651
|
+
if (char === '\\') {
|
|
652
|
+
escaped = true;
|
|
653
|
+
i += 1;
|
|
654
|
+
continue;
|
|
655
|
+
}
|
|
656
|
+
if (char === '"') {
|
|
657
|
+
const raw = text.slice(start, i + 1);
|
|
658
|
+
i += 1;
|
|
659
|
+
try {
|
|
660
|
+
return { value: JSON.parse(raw) as string, end: i };
|
|
661
|
+
} catch {
|
|
662
|
+
return { value: raw.slice(1, -1), end: i };
|
|
663
|
+
}
|
|
664
|
+
}
|
|
665
|
+
i += 1;
|
|
666
|
+
}
|
|
667
|
+
return { value: text.slice(start + 1), end: i };
|
|
668
|
+
}
|
|
669
|
+
|
|
670
|
+
/** Skip one JSON value (scalar, object, or array) without parsing it. */
|
|
671
|
+
function skipJsonValue(text: string, start: number): number {
|
|
672
|
+
if (text[start] === '"') return readJsonStringAt(text, start).end;
|
|
673
|
+
if (text[start] === '{' || text[start] === '[') {
|
|
674
|
+
let depth = 0;
|
|
675
|
+
let inString = false;
|
|
676
|
+
let escaped = false;
|
|
677
|
+
for (let i = start; i < text.length; i += 1) {
|
|
678
|
+
const char = text[i];
|
|
679
|
+
if (inString) {
|
|
680
|
+
if (escaped) escaped = false;
|
|
681
|
+
else if (char === '\\') escaped = true;
|
|
682
|
+
else if (char === '"') inString = false;
|
|
683
|
+
continue;
|
|
684
|
+
}
|
|
685
|
+
if (char === '"') inString = true;
|
|
686
|
+
else if (char === '{' || char === '[') depth += 1;
|
|
687
|
+
else if (char === '}' || char === ']') {
|
|
688
|
+
depth -= 1;
|
|
689
|
+
if (depth === 0) return i + 1;
|
|
690
|
+
}
|
|
691
|
+
}
|
|
692
|
+
return text.length;
|
|
693
|
+
}
|
|
694
|
+
let i = start;
|
|
695
|
+
while (i < text.length && text[i] !== ',' && text[i] !== '}') i += 1;
|
|
696
|
+
return i;
|
|
697
|
+
}
|
|
698
|
+
|
|
699
|
+
function parseJsonScalar(raw: string): JsonScalar {
|
|
700
|
+
if (raw === 'true') return true;
|
|
701
|
+
if (raw === 'false') return false;
|
|
702
|
+
if (raw === 'null') return null;
|
|
703
|
+
if (raw !== '' && Number.isFinite(Number(raw))) return Number(raw);
|
|
704
|
+
return raw;
|
|
705
|
+
}
|
|
706
|
+
|
|
707
|
+
/**
|
|
708
|
+
* Extract top-level scalar fields from a record's JSON text. Nested values
|
|
709
|
+
* (notably `result.messages` and `finalOutput`) are skipped, not parsed — the
|
|
710
|
+
* reader only ever touches the six identity keys.
|
|
711
|
+
*/
|
|
712
|
+
function scanTopLevelScalars(text: string, wanted: ReadonlySet<string>): Map<string, JsonScalar> {
|
|
713
|
+
const out = new Map<string, JsonScalar>();
|
|
714
|
+
let i = skipWhitespace(text, 0);
|
|
715
|
+
if (text[i] !== '{') return out;
|
|
716
|
+
i += 1;
|
|
717
|
+
|
|
718
|
+
while (i < text.length) {
|
|
719
|
+
i = skipWhitespace(text, i);
|
|
720
|
+
if (i >= text.length) break;
|
|
721
|
+
const char = text[i];
|
|
722
|
+
if (char === '}') break;
|
|
723
|
+
if (char === ',') {
|
|
724
|
+
i += 1;
|
|
725
|
+
continue;
|
|
726
|
+
}
|
|
727
|
+
if (char !== '"') {
|
|
728
|
+
// Malformed object: make progress rather than looping forever.
|
|
729
|
+
i += 1;
|
|
730
|
+
continue;
|
|
731
|
+
}
|
|
732
|
+
|
|
733
|
+
const keyStart = i;
|
|
734
|
+
const key = readJsonStringAt(text, i);
|
|
735
|
+
i = skipWhitespace(text, key.end);
|
|
736
|
+
if (text[i] !== ':') break;
|
|
737
|
+
i = skipWhitespace(text, i + 1);
|
|
738
|
+
if (i >= text.length) break;
|
|
739
|
+
|
|
740
|
+
if (wanted.has(key.value)) {
|
|
741
|
+
const valueStart = text[i];
|
|
742
|
+
if (valueStart === '"') {
|
|
743
|
+
const value = readJsonStringAt(text, i);
|
|
744
|
+
out.set(key.value, value.value);
|
|
745
|
+
i = value.end;
|
|
746
|
+
} else if (valueStart === '{' || valueStart === '[') {
|
|
747
|
+
i = skipJsonValue(text, i);
|
|
748
|
+
} else {
|
|
749
|
+
let end = i;
|
|
750
|
+
while (end < text.length && text[end] !== ',' && text[end] !== '}') end += 1;
|
|
751
|
+
out.set(key.value, parseJsonScalar(text.slice(i, end).trim()));
|
|
752
|
+
i = end;
|
|
753
|
+
}
|
|
754
|
+
} else {
|
|
755
|
+
i = skipJsonValue(text, i);
|
|
756
|
+
}
|
|
757
|
+
|
|
758
|
+
if (i <= keyStart) break;
|
|
759
|
+
}
|
|
760
|
+
|
|
761
|
+
return out;
|
|
762
|
+
}
|
|
763
|
+
|
|
764
|
+
/** Read one agent record's identity fields; null when malformed/incomplete. */
|
|
765
|
+
function readAgentIdentity(file: string): RetryRecordIdentity | null {
|
|
766
|
+
let text: string;
|
|
767
|
+
try {
|
|
768
|
+
text = readFileSync(file, 'utf-8');
|
|
769
|
+
} catch {
|
|
770
|
+
return null;
|
|
771
|
+
}
|
|
772
|
+
|
|
773
|
+
const fields = scanTopLevelScalars(text, RETRY_IDENTITY_KEYS);
|
|
774
|
+
const embeddedId = fields.get('id');
|
|
775
|
+
const id = typeof embeddedId === 'string' ? embeddedId : basename(file, '.json');
|
|
776
|
+
if (!isSafeAgentId(id)) return null;
|
|
777
|
+
|
|
778
|
+
const status = fields.get('status');
|
|
779
|
+
if (!isAgentStatus(status)) return null;
|
|
780
|
+
|
|
781
|
+
const startedAt = normalizeStartedAt(fields.get('startedAt'));
|
|
782
|
+
if (startedAt === null) return null;
|
|
783
|
+
|
|
784
|
+
const attemptValue = fields.get('attempt');
|
|
785
|
+
const attempt =
|
|
786
|
+
typeof attemptValue === 'number' && Number.isFinite(attemptValue) && attemptValue > 0
|
|
787
|
+
? Math.floor(attemptValue)
|
|
788
|
+
: 1;
|
|
789
|
+
|
|
790
|
+
const dispatchId = fields.get('dispatchId');
|
|
791
|
+
const resumeOf = fields.get('resumeOf');
|
|
792
|
+
return {
|
|
793
|
+
id,
|
|
794
|
+
status,
|
|
795
|
+
startedAt,
|
|
796
|
+
attempt,
|
|
797
|
+
...(typeof dispatchId === 'string' ? { dispatchId } : {}),
|
|
798
|
+
...(typeof resumeOf === 'string' ? { resumeOf } : {}),
|
|
799
|
+
};
|
|
800
|
+
}
|
|
801
|
+
|
|
802
|
+
/**
|
|
803
|
+
* The bounded store read: stat every record (cheap), keep the ones inside the
|
|
804
|
+
* mtime window, sort newest-first, cap at `RETRY_SCAN_CAP`, then read only the
|
|
805
|
+
* surviving files' identity fields. Corrupt/unsafe records are skipped.
|
|
806
|
+
*/
|
|
807
|
+
function readRecentAgentIdentities(): RetryRecordIdentity[] {
|
|
808
|
+
let files: string[];
|
|
809
|
+
try {
|
|
810
|
+
if (!existsSync(STORAGE_DIR)) return [];
|
|
811
|
+
files = readdirSync(STORAGE_DIR);
|
|
812
|
+
} catch {
|
|
813
|
+
return [];
|
|
814
|
+
}
|
|
815
|
+
|
|
816
|
+
const cutoff = Date.now() - RETRY_SCAN_WINDOW_MS;
|
|
817
|
+
const recent: Array<{ file: string; mtime: number }> = [];
|
|
818
|
+
for (const file of files) {
|
|
819
|
+
if (!file.endsWith('.json')) continue;
|
|
820
|
+
const id = file.slice(0, -'.json'.length);
|
|
821
|
+
if (!isSafeAgentId(id)) continue;
|
|
822
|
+
const fullPath = join(STORAGE_DIR, file);
|
|
823
|
+
try {
|
|
824
|
+
const stat = statSync(fullPath);
|
|
825
|
+
if (stat.mtimeMs >= cutoff) recent.push({ file: fullPath, mtime: stat.mtimeMs });
|
|
826
|
+
} catch {
|
|
827
|
+
// Vanished between readdir and stat — not a lineage candidate.
|
|
828
|
+
}
|
|
829
|
+
}
|
|
830
|
+
|
|
831
|
+
recent.sort((a, b) => b.mtime - a.mtime);
|
|
832
|
+
const records: RetryRecordIdentity[] = [];
|
|
833
|
+
for (const entry of recent.slice(0, RETRY_SCAN_CAP)) {
|
|
834
|
+
const record = readAgentIdentity(entry.file);
|
|
835
|
+
if (record) records.push(record);
|
|
836
|
+
}
|
|
837
|
+
return records;
|
|
838
|
+
}
|
|
839
|
+
|
|
840
|
+
function identityFromAgent(agent: BackgroundAgent): RetryRecordIdentity | null {
|
|
841
|
+
const startedAt = normalizeStartedAt(agent.startedAt);
|
|
842
|
+
if (startedAt === null) return null;
|
|
843
|
+
return {
|
|
844
|
+
id: agent.id,
|
|
845
|
+
status: agent.status,
|
|
846
|
+
startedAt,
|
|
847
|
+
attempt: agent.attempt ?? 1,
|
|
848
|
+
...(agent.dispatchId ? { dispatchId: agent.dispatchId } : {}),
|
|
849
|
+
...(agent.resumeOf ? { resumeOf: agent.resumeOf } : {}),
|
|
850
|
+
};
|
|
851
|
+
}
|
|
852
|
+
|
|
853
|
+
function identityFromRegistry(run: InflightRun): RetryRecordIdentity | null {
|
|
854
|
+
const startedAt = normalizeStartedAt(run.startedAt);
|
|
855
|
+
if (startedAt === null) return null;
|
|
856
|
+
return {
|
|
857
|
+
id: run.id,
|
|
858
|
+
status: 'running',
|
|
859
|
+
startedAt,
|
|
860
|
+
attempt: run.attempt ?? 1,
|
|
861
|
+
...(run.dispatchId ? { dispatchId: run.dispatchId } : {}),
|
|
862
|
+
};
|
|
863
|
+
}
|
|
864
|
+
|
|
865
|
+
/**
|
|
866
|
+
* Find the logical dispatch family for `id`.
|
|
867
|
+
*
|
|
868
|
+
* Family membership is `dispatchId` (inherited by every attempt, including a
|
|
869
|
+
* manual attempt 3 whose `resumeOf` names attempt 2). Records without a
|
|
870
|
+
* `dispatchId` fall back to direct `resumeOf` matching. The registry is folded
|
|
871
|
+
* in so an in-flight retry is visible without a store record.
|
|
872
|
+
*/
|
|
873
|
+
export function findRetryLineage(id: string, source?: BackgroundAgent | null): RetryLineage {
|
|
874
|
+
const empty: RetryLineage = { id, family: [], found: null, latest: null, inflight: [] };
|
|
875
|
+
if (!isSafeAgentId(id)) return empty;
|
|
876
|
+
|
|
877
|
+
const byId = new Map<string, RetryRecordIdentity>();
|
|
878
|
+
for (const record of readRecentAgentIdentities()) byId.set(record.id, record);
|
|
879
|
+
|
|
880
|
+
const sourceIdentity = source && source.id === id ? identityFromAgent(source) : null;
|
|
881
|
+
if (sourceIdentity) byId.set(id, sourceIdentity);
|
|
882
|
+
|
|
883
|
+
const registry = safeListInflightRuns();
|
|
884
|
+
for (const run of registry) {
|
|
885
|
+
const identity = identityFromRegistry(run);
|
|
886
|
+
// A persisted record is authoritative over the registry's "running" view.
|
|
887
|
+
if (identity && !byId.has(identity.id)) byId.set(identity.id, identity);
|
|
888
|
+
}
|
|
889
|
+
|
|
890
|
+
const all = [...byId.values()];
|
|
891
|
+
const found = byId.get(id) ?? sourceIdentity;
|
|
892
|
+
// Newest-first so the dispatch chosen for an unknown id comes from its most
|
|
893
|
+
// recent direct descendant, not from readdir order.
|
|
894
|
+
const direct = all
|
|
895
|
+
.filter((record) => record.resumeOf === id && record.id !== id)
|
|
896
|
+
.sort((a, b) => b.attempt - a.attempt || b.startedAt - a.startedAt);
|
|
897
|
+
const familyDispatch = found?.dispatchId ?? direct[0]?.dispatchId;
|
|
898
|
+
|
|
899
|
+
const members = familyDispatch
|
|
900
|
+
? all.filter((record) => record.dispatchId === familyDispatch)
|
|
901
|
+
: [...(found ? [found] : []), ...direct];
|
|
902
|
+
|
|
903
|
+
const family = [...new Map(members.map((record) => [record.id, record])).values()];
|
|
904
|
+
family.sort(
|
|
905
|
+
(a, b) => a.attempt - b.attempt || a.startedAt - b.startedAt || a.id.localeCompare(b.id),
|
|
906
|
+
);
|
|
907
|
+
|
|
908
|
+
const latest = family.length > 0 ? family[family.length - 1] : null;
|
|
909
|
+
const inflight = registry.filter(
|
|
910
|
+
(run) => run.id === id || (familyDispatch !== undefined && run.dispatchId === familyDispatch),
|
|
911
|
+
);
|
|
912
|
+
|
|
913
|
+
return { id, family, found, latest, inflight };
|
|
914
|
+
}
|
|
915
|
+
|
|
260
916
|
/**
|
|
261
917
|
* Option B U1 (D3): read-modify-write the interrupted mark onto a persisted
|
|
262
918
|
* agent record. Idempotent: an already-marked record is returned unchanged.
|
|
@@ -481,6 +1137,10 @@ export async function spawnBackgroundSession(
|
|
|
481
1137
|
model?: string;
|
|
482
1138
|
thinkingLevel?: ThinkingLevel;
|
|
483
1139
|
systemPrompt?: string;
|
|
1140
|
+
/** Issue #411: conductor-authored resume context for an auto-retry,
|
|
1141
|
+
* appended to the system prompt as a `<resume-context>` section —
|
|
1142
|
+
* never inside the `<task>` fence. */
|
|
1143
|
+
resumeContext?: string;
|
|
484
1144
|
cwd?: string;
|
|
485
1145
|
toolOptions?: SubagentToolOptions;
|
|
486
1146
|
/** Per-agent deadline in ms — the session is aborted when exceeded (issue #28 W3). */
|
|
@@ -537,6 +1197,11 @@ export async function spawnBackgroundSession(
|
|
|
537
1197
|
// inspection, no U4 resume) and the SDK default (`~/.pi/agent/sessions/<cwd-key>/`,
|
|
538
1198
|
// passed as `undefined`) would scatter our runs into the global store. The
|
|
539
1199
|
// directory lives beside the agent record: `.pi/subagents/sessions/<id>/`.
|
|
1200
|
+
//
|
|
1201
|
+
// Issue #408: create the sessions root owner-only BEFORE the SDK sees it —
|
|
1202
|
+
// its `mkdirSync` (and ours) applies `mode` only on CREATE, so a pre-existing
|
|
1203
|
+
// 0o755 root would otherwise stay traversable.
|
|
1204
|
+
ensureSessionsRoot();
|
|
540
1205
|
const sessionManager = SessionManager.create(effectiveCwd, backgroundSessionDir(id));
|
|
541
1206
|
// Capture the exact path the SDK will write. The settle path derives the
|
|
542
1207
|
// prune target from THIS (not from a freshly-computed STORAGE_DIR path) so a
|
|
@@ -570,9 +1235,16 @@ export async function spawnBackgroundSession(
|
|
|
570
1235
|
// plant a newline-named dir + symlink leaf. Not exploitable realistically;
|
|
571
1236
|
// do not "simplify" the frame (e.g. dropping the "/" marker) without
|
|
572
1237
|
// re-verifying this property.
|
|
573
|
-
|
|
574
|
-
|
|
575
|
-
|
|
1238
|
+
// Issue #411: the appendSystemPrompt entries are built as an ordered array —
|
|
1239
|
+
// <system-prompt> first, then <resume-context> — so an auto-retry's resume
|
|
1240
|
+
// preamble rides the system-prompt side and never the <task> fence.
|
|
1241
|
+
const sections: string[] = [];
|
|
1242
|
+
if (params.systemPrompt?.trim()) {
|
|
1243
|
+
sections.push(`\n<system-prompt>\n${params.systemPrompt}\n</system-prompt>\n`);
|
|
1244
|
+
}
|
|
1245
|
+
if (params.resumeContext?.trim()) {
|
|
1246
|
+
sections.push(`\n<resume-context>\n${params.resumeContext.trim()}\n</resume-context>\n`);
|
|
1247
|
+
}
|
|
576
1248
|
//
|
|
577
1249
|
// F25: ALWAYS build our own loader (even without a systemPrompt). If
|
|
578
1250
|
// resourceLoader is undefined, createAgentSession constructs its own
|
|
@@ -589,7 +1261,7 @@ export async function spawnBackgroundSession(
|
|
|
589
1261
|
cwd: effectiveCwd,
|
|
590
1262
|
agentDir,
|
|
591
1263
|
settingsManager,
|
|
592
|
-
...(
|
|
1264
|
+
...(sections.length ? { appendSystemPrompt: sections } : {}),
|
|
593
1265
|
noExtensions: true,
|
|
594
1266
|
noSkills: true,
|
|
595
1267
|
});
|
|
@@ -618,6 +1290,15 @@ export async function spawnBackgroundSession(
|
|
|
618
1290
|
...(params.toolOptions?.noBuiltinTools ? { noTools: 'builtin' as const } : {}),
|
|
619
1291
|
});
|
|
620
1292
|
|
|
1293
|
+
// Issue #408: the SDK's `SessionManager.create` made the per-run dir with the
|
|
1294
|
+
// process default mode (0o755). THE DIR MODE IS THE CONFIDENTIALITY BOUNDARY
|
|
1295
|
+
// — no traversal means the session files inside are unreachable by other
|
|
1296
|
+
// local users; the file repair below is defense-in-depth. Best-effort: a
|
|
1297
|
+
// permission failure here must never break a spawn.
|
|
1298
|
+
const spawnedSessionDir = sessionFile ? dirname(sessionFile) : backgroundSessionDir(id);
|
|
1299
|
+
ensureOwnerOnlyDir(spawnedSessionDir);
|
|
1300
|
+
repairOwnerOnlyFiles(spawnedSessionDir);
|
|
1301
|
+
|
|
621
1302
|
// Set session name
|
|
622
1303
|
session.setSessionName(`background-${id.slice(0, 8)}`);
|
|
623
1304
|
|
|
@@ -691,10 +1372,11 @@ export async function spawnBackgroundSession(
|
|
|
691
1372
|
// run — git-setup refusal, a synchronous prompt throw, the .then completed /
|
|
692
1373
|
// provider-failed / aborted branches, the .catch stopped / failed branches and
|
|
693
1374
|
// the markTerminalBestEffort catch-all ALL land here exactly once (the
|
|
694
|
-
// runFinalized guard).
|
|
695
|
-
// index.ts poller crash notices are NOT settlements (they flip
|
|
696
|
-
// UI state and leave the run/agent record to this settle); an
|
|
697
|
-
// (U1 boot-scan mark) never reaches this function and KEEPS its
|
|
1375
|
+
// runFinalized guard). The session-dir decision below therefore covers every
|
|
1376
|
+
// settle path. The index.ts poller crash notices are NOT settlements (they flip
|
|
1377
|
+
// only the live UI state and leave the run/agent record to this settle); an
|
|
1378
|
+
// interrupted run (U1 boot-scan mark) never reaches this function and KEEPS its
|
|
1379
|
+
// file (D3).
|
|
698
1380
|
let runFinalized = false;
|
|
699
1381
|
const finalizeRunEntry = (
|
|
700
1382
|
status: "done" | "failed",
|
|
@@ -703,21 +1385,17 @@ export async function spawnBackgroundSession(
|
|
|
703
1385
|
): void => {
|
|
704
1386
|
if (runFinalized) return;
|
|
705
1387
|
runFinalized = true;
|
|
706
|
-
// U2 (D2): drop the persisted session now that the run is terminal. Done
|
|
707
|
-
// FIRST (before the run-entry write below) so a persist throw cannot leave
|
|
708
|
-
// a terminal run's session file behind. Interrupted runs keep theirs.
|
|
709
|
-
if (!agent.interruptedAt) {
|
|
710
|
-
pruneSessionDir(
|
|
711
|
-
id,
|
|
712
|
-
agent._sessionFile ? dirname(agent._sessionFile) : backgroundSessionDir(id),
|
|
713
|
-
);
|
|
714
|
-
}
|
|
715
1388
|
const usage = agent.result?.usage ?? EMPTY_USAGE;
|
|
716
1389
|
const finalOutput = agent.finalOutput ?? "";
|
|
717
1390
|
// Issue #179 (D1/D2): the classifier's explicit category wins (it knows the
|
|
718
1391
|
// terminal stopReason); otherwise fall back to the legacy message-based
|
|
719
1392
|
// classification (refused spawns, sync throws, preflight rejections, the
|
|
720
1393
|
// catch-all) so no failure is ever left uncategorized.
|
|
1394
|
+
//
|
|
1395
|
+
// Issue #404: HOISTED above the session-dir decision below — the retention
|
|
1396
|
+
// gate must read the same category/value the run record is about to get, and
|
|
1397
|
+
// that decision has to happen before the record write (see the invariant
|
|
1398
|
+
// note there). `classifyError` is pure and total, so hoisting costs nothing.
|
|
721
1399
|
const errorCategory =
|
|
722
1400
|
status === "failed"
|
|
723
1401
|
? terminal?.errorCategory ??
|
|
@@ -731,6 +1409,32 @@ export async function spawnBackgroundSession(
|
|
|
731
1409
|
})
|
|
732
1410
|
: undefined)
|
|
733
1411
|
: undefined;
|
|
1412
|
+
// U2 (D2) prune + #404 retention. THE INVARIANT: the prune/mark decision
|
|
1413
|
+
// precedes the run-record write, and everything above it is pure — so no
|
|
1414
|
+
// throw between the decision and the write can leave a terminal run's session
|
|
1415
|
+
// dir behind. Interrupted runs keep theirs (D3) and are never marked.
|
|
1416
|
+
//
|
|
1417
|
+
// The retention gate is the auto-retry predicate itself (#365/#401): only a
|
|
1418
|
+
// run that will be re-dispatched has a reader for the retained session, and
|
|
1419
|
+
// it is built from the values this record is about to carry, so the reader
|
|
1420
|
+
// and the retainer can never disagree.
|
|
1421
|
+
if (!agent.interruptedAt) {
|
|
1422
|
+
// The CAPTURED dir — tests swap STORAGE_DIR per case, and a mid-run change
|
|
1423
|
+
// of root must never mis-target the delete or the marker.
|
|
1424
|
+
const sessionDir = agent._sessionFile ? dirname(agent._sessionFile) : backgroundSessionDir(id);
|
|
1425
|
+
const retained = isTransportRetryable({
|
|
1426
|
+
status,
|
|
1427
|
+
errorCategory,
|
|
1428
|
+
errorMessage: error,
|
|
1429
|
+
attempt: run.attempt,
|
|
1430
|
+
originalParams: run.originalParams,
|
|
1431
|
+
});
|
|
1432
|
+
// Marker write failure => prune: retention is an optimization, boundedness
|
|
1433
|
+
// is the invariant (an unmarked retained dir would escape the sweep).
|
|
1434
|
+
if (!retained || !retainSessionDir(id, sessionDir)) {
|
|
1435
|
+
pruneSessionDir(id, sessionDir);
|
|
1436
|
+
}
|
|
1437
|
+
}
|
|
734
1438
|
// Issue #187: capture the RAW terminal reason BEFORE coercion. `finalTurnError`
|
|
735
1439
|
// means "the final turn was a PROVIDER error" (isProviderError); deriving it
|
|
736
1440
|
// from the COERCED reason would turn a missing/success reason into 'error' and
|
|
@@ -1005,6 +1709,52 @@ export async function spawnBackgroundSession(
|
|
|
1005
1709
|
return info;
|
|
1006
1710
|
};
|
|
1007
1711
|
|
|
1712
|
+
// Issue #376 (audit D8): the aborted settle path is reached from BOTH
|
|
1713
|
+
// handlers — the .then (probe contract: an abort RESOLVES the prompt) and the
|
|
1714
|
+
// .catch (the prompt rejects while the agent is already 'stopped'). Both must
|
|
1715
|
+
// record the same partial-work result and the same retryable failure, so they
|
|
1716
|
+
// share one helper.
|
|
1717
|
+
// - `gitInfo` is caller-captured: cleanupWorkBranch is once-per-run
|
|
1718
|
+
// (idempotent), and the .catch failed path reuses that same capture.
|
|
1719
|
+
// - `stopReason` is caller-supplied: the .then can narrow it from the last
|
|
1720
|
+
// assistant message; the .catch has no message to read.
|
|
1721
|
+
const finalizeAbortedRun = (
|
|
1722
|
+
gitInfo: { gitBranch?: string; gitDiff?: string },
|
|
1723
|
+
stopReason: string,
|
|
1724
|
+
): void => {
|
|
1725
|
+
// W4/M1: capture whatever the branch produced before discarding it — an
|
|
1726
|
+
// aborted background agent's partial work is still worth reviewing, and
|
|
1727
|
+
// must be RECORDED, not just captured-and-deleted.
|
|
1728
|
+
if (gitInfo.gitBranch) {
|
|
1729
|
+
agent.result = {
|
|
1730
|
+
...(agent.result ?? {}),
|
|
1731
|
+
exitCode: 1,
|
|
1732
|
+
messages: [],
|
|
1733
|
+
stderr: '',
|
|
1734
|
+
usage: agent.result?.usage ?? EMPTY_USAGE,
|
|
1735
|
+
stopReason: 'aborted',
|
|
1736
|
+
gitBranch: gitInfo.gitBranch,
|
|
1737
|
+
gitDiff: gitInfo.gitDiff,
|
|
1738
|
+
} as SubagentResult;
|
|
1739
|
+
agents.set(id, agent);
|
|
1740
|
+
persistAgent(agent);
|
|
1741
|
+
}
|
|
1742
|
+
// Issue #98: aborts/timeouts are retryable failures (retry schema:
|
|
1743
|
+
// timeout/abort counts as failure) — finalize the run entry.
|
|
1744
|
+
// Issue #122: a timed-out run burned tokens — record the real usage
|
|
1745
|
+
// (the git-diff block above must not leave the empty fallback).
|
|
1746
|
+
recordSessionUsage();
|
|
1747
|
+
// Issue #120 (Track 1): agent.error carries the reason when the stop was a
|
|
1748
|
+
// deadline timeout ('Timed out after Xms' → 'timeout'); a user cancel
|
|
1749
|
+
// (stop_subagent) sets no error, so fall back to the honest user-abort
|
|
1750
|
+
// stamp (→ 'aborted') instead of the old ambiguous 'Aborted or timed out'.
|
|
1751
|
+
finalizeRunEntry('failed', agent.error ?? SUBAGENT_ABORTED_MESSAGE, { stopReason });
|
|
1752
|
+
// Issue #31: capture the final output while the session is still live,
|
|
1753
|
+
// then release the ref on the terminal path (memory retention; the poller
|
|
1754
|
+
// treats a nulled ref on a terminal agent as expected).
|
|
1755
|
+
captureAndReleaseSession();
|
|
1756
|
+
};
|
|
1757
|
+
|
|
1008
1758
|
// Issue #53: the settle handlers (.then/.catch below) run in promise
|
|
1009
1759
|
// callbacks — a throw from any step (fs failure, deleted transcript, emit
|
|
1010
1760
|
// error) would escape as an uncaughtException and kill the whole pi
|
|
@@ -1142,43 +1892,14 @@ export async function spawnBackgroundSession(
|
|
|
1142
1892
|
updateAgentStatus(id, 'stopped');
|
|
1143
1893
|
transcript.completeTranscript(id, 'stopped');
|
|
1144
1894
|
}
|
|
1145
|
-
// W4/M1
|
|
1146
|
-
//
|
|
1147
|
-
|
|
1148
|
-
|
|
1149
|
-
|
|
1150
|
-
|
|
1151
|
-
|
|
1152
|
-
|
|
1153
|
-
messages: [],
|
|
1154
|
-
stderr: '',
|
|
1155
|
-
usage: agent.result?.usage ?? EMPTY_USAGE,
|
|
1156
|
-
stopReason: 'aborted',
|
|
1157
|
-
gitBranch: gitInfo.gitBranch,
|
|
1158
|
-
gitDiff: gitInfo.gitDiff,
|
|
1159
|
-
} as SubagentResult;
|
|
1160
|
-
agents.set(id, agent);
|
|
1161
|
-
persistAgent(agent);
|
|
1162
|
-
}
|
|
1163
|
-
// Issue #98: aborts/timeouts are retryable failures (retry schema:
|
|
1164
|
-
// timeout/abort counts as failure) — finalize the run entry.
|
|
1165
|
-
// Issue #122: a timed-out run burned tokens — record the real usage
|
|
1166
|
-
// (the git-diff block above must not leave the empty fallback).
|
|
1167
|
-
// Issue #120 (Track 1): agent.error carries the reason when the stop was
|
|
1168
|
-
// a deadline timeout ('Timed out after Xms' → 'timeout'); a user cancel
|
|
1169
|
-
// (stop_subagent) sets no error, so fall back to the honest user-abort
|
|
1170
|
-
// stamp (→ 'aborted') instead of the old ambiguous 'Aborted or timed out'.
|
|
1171
|
-
recordSessionUsage();
|
|
1172
|
-
finalizeRunEntry('failed', agent.error ?? SUBAGENT_ABORTED_MESSAGE, {
|
|
1173
|
-
stopReason:
|
|
1174
|
-
terminalStopReason && terminalStopReason !== 'stop'
|
|
1175
|
-
? terminalStopReason
|
|
1176
|
-
: 'aborted',
|
|
1177
|
-
});
|
|
1178
|
-
// Issue #31: capture the final output while the session is still
|
|
1179
|
-
// live, then release the ref on the terminal path (memory retention;
|
|
1180
|
-
// the poller treats a nulled ref on a terminal agent as expected).
|
|
1181
|
-
captureAndReleaseSession();
|
|
1895
|
+
// W4/M1 + #98/#122/#120/#31: the same aborted settle as the .catch
|
|
1896
|
+
// stopped branch (issue #376/D8 — one helper, no second copy).
|
|
1897
|
+
finalizeAbortedRun(
|
|
1898
|
+
cleanupWorkBranch(),
|
|
1899
|
+
terminalStopReason && terminalStopReason !== 'stop'
|
|
1900
|
+
? terminalStopReason
|
|
1901
|
+
: 'aborted',
|
|
1902
|
+
);
|
|
1182
1903
|
return;
|
|
1183
1904
|
}
|
|
1184
1905
|
// Issue #179 (D1/D2): prompt() RESOLVED — but a resolved prompt is NOT
|
|
@@ -1283,33 +2004,11 @@ export async function spawnBackgroundSession(
|
|
|
1283
2004
|
// model resolution, invalid task). Abort never rejects (probe contract).
|
|
1284
2005
|
if (agent.status === 'stopped') {
|
|
1285
2006
|
// M1: record the partial work even on the stopped path.
|
|
1286
|
-
|
|
1287
|
-
|
|
1288
|
-
|
|
1289
|
-
|
|
1290
|
-
|
|
1291
|
-
stderr: '',
|
|
1292
|
-
usage: agent.result?.usage ?? EMPTY_USAGE,
|
|
1293
|
-
stopReason: 'aborted',
|
|
1294
|
-
gitBranch: gitInfo.gitBranch,
|
|
1295
|
-
gitDiff: gitInfo.gitDiff,
|
|
1296
|
-
} as SubagentResult;
|
|
1297
|
-
agents.set(id, agent);
|
|
1298
|
-
persistAgent(agent);
|
|
1299
|
-
}
|
|
1300
|
-
// Issue #98: the stopped path is a retryable failure too — finalize
|
|
1301
|
-
// the run entry alongside the agent record flip.
|
|
1302
|
-
// Issue #122: a stopped/timed-out run burned tokens too — record the
|
|
1303
|
-
// real usage (same aborted path semantics as the .then branch).
|
|
1304
|
-
// Issue #120 (Track 1): same honest fallback — a deadline timeout keeps
|
|
1305
|
-
// agent.error ('Timed out...' → 'timeout'); a user cancel has no error
|
|
1306
|
-
// and stamps 'Subagent aborted by user' (→ 'aborted').
|
|
1307
|
-
recordSessionUsage();
|
|
1308
|
-
finalizeRunEntry('failed', agent.error ?? SUBAGENT_ABORTED_MESSAGE, {
|
|
1309
|
-
stopReason: 'aborted',
|
|
1310
|
-
});
|
|
1311
|
-
// Issue #31: the stopped path is terminal too — capture + release.
|
|
1312
|
-
captureAndReleaseSession();
|
|
2007
|
+
// Issue #376 (D8): identical to the .then aborted branch — the work-branch
|
|
2008
|
+
// capture above is reused (cleanupWorkBranch is once-per-run) and there is
|
|
2009
|
+
// no last assistant message here to narrow the reason from.
|
|
2010
|
+
finalizeAbortedRun(gitInfo, 'aborted');
|
|
2011
|
+
// Issue #31: the stopped path is terminal too — its transcript note.
|
|
1313
2012
|
transcript.completeTranscript(id, 'stopped');
|
|
1314
2013
|
return;
|
|
1315
2014
|
}
|