pi-better-subagents 0.26.0 → 0.26.2

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.
@@ -0,0 +1,161 @@
1
+ /** Declared child dependency closure. Reading a contract never initializes its extension. */
2
+ import { readFileSync, existsSync, statSync, realpathSync } from 'node:fs';
3
+ import { dirname, join, resolve, isAbsolute } from 'node:path';
4
+ import { createRequire } from 'node:module';
5
+ import { pathToFileURL, fileURLToPath } from 'node:url';
6
+ import { createHash } from 'node:crypto';
7
+ import { BUILTIN_PROVIDER_EXTENSIONS, providerOf } from './extensions.mjs';
8
+
9
+ export function packageRoot(path) {
10
+ let dir = statSync(path).isDirectory() ? path : dirname(path);
11
+ while (!existsSync(join(dir, 'package.json'))) {
12
+ const parent = dirname(dir);
13
+ if (parent === dir) return undefined;
14
+ dir = parent;
15
+ }
16
+ return realpathSync(dir);
17
+ }
18
+
19
+ /** Search the declaring package's dependencies first, then the caller's installed roots. */
20
+ export function installedPackage(name, roots) {
21
+ for (const root of roots.filter(Boolean)) {
22
+ let dir = root;
23
+ while (true) {
24
+ const candidate = join(dir, 'node_modules', name);
25
+ if (existsSync(join(candidate, 'package.json'))) return realpathSync(candidate);
26
+ const parent = dirname(dir);
27
+ if (parent === dir) break;
28
+ dir = parent;
29
+ }
30
+ }
31
+ }
32
+
33
+ export async function loadContract(path) {
34
+ // Use the host's TS loader, with fresh module state for every declaration read.
35
+ const sdkRequire = createRequire(fileURLToPath(import.meta.resolve('@earendil-works/pi-coding-agent')));
36
+ const { createJiti } = await import(pathToFileURL(sdkRequire.resolve('jiti')).href);
37
+ return createJiti(import.meta.url, { tryNative: false, fsCache: false, moduleCache: false })
38
+ .import(path, { default: true });
39
+ }
40
+
41
+ function strings(value, label) {
42
+ if (!Array.isArray(value) || value.some(x => typeof x !== 'string' || !x.trim()))
43
+ throw new Error(`Invalid child declaration: ${label} must be an array of nonempty strings.`);
44
+ return value;
45
+ }
46
+ export function validateRequirements(value) {
47
+ if (!value || typeof value !== 'object') throw new Error('Invalid childRequirements result.');
48
+ strings(value.providers, 'providers');
49
+ if (!Array.isArray(value.modelGroups)) throw new Error('Invalid childRequirements modelGroups.');
50
+ for (const group of value.modelGroups) {
51
+ if (!group || typeof group.provider !== 'string' || !group.provider.trim()) throw new Error('Invalid model group provider.');
52
+ strings(group.ids, 'modelGroups.ids');
53
+ if (group.prefix !== undefined && (typeof group.prefix !== 'string' || !group.prefix)) throw new Error('Invalid model group prefix.');
54
+ if (!group.ids.length && !group.prefix) throw new Error('Empty child model group.');
55
+ }
56
+ return value;
57
+ }
58
+
59
+ export function fingerprint(path) {
60
+ return existsSync(path) ? createHash('sha256').update(readFileSync(path)).digest('hex') : null;
61
+ }
62
+
63
+ // Credential refresh and catalog caches are runtime state, not dependency configuration.
64
+ const CONFIG_INPUTS = ['settings.json', 'harness-settings.json', 'model-router.json', 'models.json'];
65
+ export function configSnapshot(directories) {
66
+ return directories.map(dir => ({ dir, files: CONFIG_INPUTS.map(name => ({ name, hash: fingerprint(join(dir, name)) })) }));
67
+ }
68
+
69
+ export async function resolveChildClosure({ resolution, model, virtual = false, config = {}, resolvePath,
70
+ load = loadContract, configPaths = [] }) {
71
+ const result = { ...resolution, specs: [], reasons: { ...resolution.reasons }, paths: {}, declarations: [],
72
+ providers: [], modelGroups: [], fingerprints: configPaths.map(path => ({ path, hash: fingerprint(path) })) };
73
+ if (resolution.mode !== 'isolated') {
74
+ if (virtual) throw new Error(`Virtual model ${model} requires isolated mode with a declared supplier; ${resolution.mode} mode is unsupported.`);
75
+ return { ...result, specs: resolution.specs, paths: Object.fromEntries(resolution.specs.map(spec => {
76
+ const path = resolvePath(spec);
77
+ if (!path) throw new Error(`Child dependency ${spec} is not installed.`);
78
+ return [spec, path];
79
+ })) };
80
+ }
81
+ const providerMap = { ...BUILTIN_PROVIDER_EXTENSIONS, ...(config.providerExtensions ?? {}) };
82
+ const active = [], done = new Set();
83
+ let ownsVirtual = false;
84
+ const visit = async (spec, from) => {
85
+ const path = resolvePath(spec, from);
86
+ if (!path) throw new Error(`Child dependency ${spec}${from ? ` required by ${from}` : ''} is not installed.`);
87
+ const root = packageRoot(path);
88
+ const identity = root ?? realpathSync(path);
89
+ if (active.includes(identity)) throw new Error(`Child dependency cycle: ${[...active, identity].join(' -> ')}`);
90
+ if (done.has(identity)) return;
91
+ active.push(identity);
92
+ // Two packages may declare the same relative spec against different roots.
93
+ const key = result.paths[spec] && result.paths[spec] !== path ? path : spec;
94
+ result.specs.push(key); result.paths[key] = path;
95
+ if (root) {
96
+ const manifestPath = join(root, 'package.json');
97
+ const manifest = JSON.parse(readFileSync(manifestPath, 'utf8'));
98
+ result.fingerprints.push({ path: manifestPath, hash: fingerprint(manifestPath) });
99
+ const declaration = manifest.pi ?? {};
100
+ for (const dependency of strings(declaration.childDependencies ?? [], 'pi.childDependencies')) await visit(dependency, root);
101
+ if (declaration.childRequirements !== undefined) {
102
+ if (typeof declaration.childRequirements !== 'string' || isAbsolute(declaration.childRequirements)) throw new Error(`Invalid childRequirements path in ${root}`);
103
+ const entry = resolve(root, declaration.childRequirements);
104
+ if (!entry.startsWith(root + '/')) throw new Error(`childRequirements escapes ${root}`);
105
+ const fn = await load(entry);
106
+ if (typeof fn !== 'function') throw new Error(`childRequirements in ${root} has no default function.`);
107
+ const requirements = await fn({ model });
108
+ result.fingerprints.push({ path: entry, hash: fingerprint(entry) });
109
+ result.declarations.push({ entry, requirements: requirements ?? null });
110
+ if (requirements !== undefined) {
111
+ validateRequirements(requirements);
112
+ if ((resolution.reasons[spec] ?? []).includes(`provider:${providerOf(model)}`)) ownsVirtual = true;
113
+ result.providers.push(...requirements.providers);
114
+ result.modelGroups.push(...requirements.modelGroups);
115
+ for (const provider of requirements.providers) {
116
+ const mapped = providerMap[provider];
117
+ for (const supplier of typeof mapped === 'string' ? [mapped] : mapped ?? []) await visit(supplier, root);
118
+ }
119
+ }
120
+ }
121
+ }
122
+ active.pop(); done.add(identity);
123
+ };
124
+ for (const spec of resolution.specs) await visit(spec);
125
+ if (virtual && !ownsVirtual) throw new Error(`Virtual model ${model} has no mapped supplier with a childRequirements contract for this selection.`);
126
+ result.providers = [...new Set(result.providers)];
127
+ return result;
128
+ }
129
+
130
+ /** Both passes start with declared roots; expanded specs retain their declaring context only inside a traversal. */
131
+ export async function resolveChildLaunch(options, trustedPaths = []) {
132
+ const resolution = await resolveChildClosure(options);
133
+ const fullResolution = await resolveChildClosure({ ...options, resolution: {
134
+ ...options.resolution, specs: [...options.resolution.specs, ...new Set(trustedPaths)],
135
+ } });
136
+ return { resolution, fullResolution };
137
+ }
138
+
139
+ /** Validate actual child registration, never the parent's catalog. Groups require one physical candidate. */
140
+ export async function checkChildPreflight(plan, { registry, tools, model }, load = loadContract) {
141
+ if (plan.configSnapshot && JSON.stringify(configSnapshot(plan.configSnapshot.map(item => item.dir))) !== JSON.stringify(plan.configSnapshot))
142
+ throw new Error('Child configuration drift: agent or project JSON configuration changed. Launch again.');
143
+ for (const item of plan.fingerprints) if (fingerprint(item.path) !== item.hash)
144
+ throw new Error(`Child configuration/declaration drift: ${item.path}. Launch again with current configuration.`);
145
+ for (const declaration of plan.declarations) {
146
+ const fn = await load(declaration.entry);
147
+ const current = await fn({ model: plan.model });
148
+ if (JSON.stringify(current ?? null) !== JSON.stringify(declaration.requirements))
149
+ throw new Error(`Child requirements changed: ${declaration.entry}. Launch again.`);
150
+ }
151
+ if (plan.model && (!model || `${model.provider}/${model.id}` !== plan.model)) throw new Error(`Selected child model ${plan.model} is missing or changed.`);
152
+ const available = registry.getAvailable();
153
+ if (plan.model && !available.some(m => `${m.provider}/${m.id}` === plan.model))
154
+ throw new Error(`Selected child model ${plan.model} is not available; check its provider and credentials.`);
155
+ for (const provider of plan.providers) if (!available.some(m => m.provider === provider && m.api !== 'pi-virtual'))
156
+ throw new Error(`Child requires available provider ${provider}; check its extension and credentials.`);
157
+ for (const group of plan.modelGroups) if (!available.some(m => m.provider === group.provider && m.api !== 'pi-virtual' &&
158
+ (group.ids.includes(m.id) || (group.prefix && m.id.startsWith(group.prefix)))))
159
+ throw new Error(`Child has no available candidate for ${group.provider}: ${group.ids.join(', ')}${group.prefix ? ` (prefix ${group.prefix})` : ''}. Check extension, models and credentials.`);
160
+ for (const tool of plan.tools) if (!tools.includes(tool)) throw new Error(`Child requested tool ${tool} is unavailable.`);
161
+ }
@@ -0,0 +1,22 @@
1
+ /** Mandatory child check. Hook errors alone are nonfatal in Pi, so explicitly exit on failure. */
2
+ import { readFileSync } from 'node:fs';
3
+ import { checkChildPreflight } from './child-dependencies.mjs';
4
+ export const PREFLIGHT_ENV = 'PI_SUBAGENT_PREFLIGHT';
5
+ export default function childPreflight(pi) {
6
+ const fail = error => {
7
+ process.stderr.write(`Subagent child preflight failed: ${error instanceof Error ? error.message : String(error)}\n`);
8
+ process.exit(1);
9
+ };
10
+ let plan;
11
+ try { plan = JSON.parse(readFileSync(process.env[PREFLIGHT_ENV], 'utf8')); } catch (error) { fail(error); }
12
+ // The task guard activates its adapters on session_start. Check after every
13
+ // startup handler has finished, before the first request (and subsequent runs).
14
+ const check = async (ctx, tools) => {
15
+ try {
16
+ await checkChildPreflight({ ...plan, tools }, { registry: ctx.modelRegistry,
17
+ tools: pi.getActiveTools(), model: ctx.model });
18
+ } catch (error) { fail(error); }
19
+ };
20
+ pi.on('session_start', async (_event, ctx) => check(ctx, []));
21
+ pi.on('before_agent_start', async (_event, ctx) => check(ctx, plan.tools));
22
+ }
@@ -0,0 +1,57 @@
1
+ /** Validate preflight before CLI discovery can downgrade import errors, then
2
+ * execute the selected launcher with its own interpreter and SDK.
3
+ */
4
+ import { spawn } from 'node:child_process';
5
+ import { accessSync, constants, statSync } from 'node:fs';
6
+ import { delimiter, resolve } from 'node:path';
7
+ import { fileURLToPath } from 'node:url';
8
+ import './child-preflight.mjs';
9
+
10
+ try {
11
+ const [binary, ...args] = process.argv.slice(2);
12
+ const launcherArgs = ['--extension', fileURLToPath(new URL('./child-preflight.mjs', import.meta.url)), ...args];
13
+ if (process.platform !== 'win32' && typeof process.execve === 'function') {
14
+ // execve does not search PATH. Resolve only executable files; let spawn
15
+ // report lookup errors below rather than invoking Node's fatal execve error.
16
+ const candidates = binary.includes('/') ? [binary]
17
+ : (process.env.PATH ?? '/usr/bin:/bin').split(delimiter).map(dir => resolve(dir, binary));
18
+ const executable = candidates.find(candidate => {
19
+ try { accessSync(candidate, constants.X_OK); return statSync(candidate).isFile(); }
20
+ catch { return false; }
21
+ });
22
+ if (executable) {
23
+ // Replace the bootstrap so the recorded launch PID is the launcher's PID.
24
+ // The executable retains its own shebang/interpreter and exact arguments.
25
+ process.execve(resolve(executable), [binary, ...launcherArgs], process.env);
26
+ }
27
+ }
28
+ // Older Node/platforms retain supervision and signal forwarding. Stay in the
29
+ // bootstrap's process group so group termination reaches all descendants.
30
+ const child = spawn(binary, launcherArgs, {
31
+ stdio: 'inherit', env: process.env, detached: false,
32
+ });
33
+ const forwards = new Map(['SIGINT', 'SIGTERM', 'SIGHUP', 'SIGQUIT'].map(signal => {
34
+ const forward = () => child.kill(signal);
35
+ process.on(signal, forward);
36
+ return [signal, forward];
37
+ }));
38
+ const cleanup = () => {
39
+ for (const [signal, forward] of forwards) process.off(signal, forward);
40
+ process.off('exit', stopChild);
41
+ };
42
+ const stopChild = () => { if (child.exitCode === null && child.signalCode === null) child.kill('SIGKILL'); };
43
+ process.on('exit', stopChild);
44
+ child.on('error', error => {
45
+ cleanup();
46
+ process.stderr.write(`Subagent bootstrap failed: ${error.message}\n`);
47
+ process.exitCode = 1;
48
+ });
49
+ child.on('exit', (code, signal) => {
50
+ cleanup();
51
+ if (signal) process.kill(process.pid, signal);
52
+ else process.exitCode = code ?? 1;
53
+ });
54
+ } catch (error) {
55
+ process.stderr.write(`Subagent bootstrap failed: ${error instanceof Error ? error.message : String(error)}\n`);
56
+ process.exit(1);
57
+ }
package/cleanup.ts CHANGED
@@ -9,12 +9,15 @@ import {
9
9
  } from "node:fs";
10
10
  import { join, relative, sep } from "node:path";
11
11
  import {
12
+ ABANDONED_LAUNCH_GRACE_MS,
13
+ abandonedLaunchRecord,
12
14
  baseDir,
13
15
  listMetas,
14
16
  observeArchivePublication,
15
17
  ownedByThisParent,
16
18
  orphanedTaskRuntimeProvenance,
17
19
  processStartToken,
20
+ purgeAbandonedLaunch,
18
21
  readMeta,
19
22
  removeMetaArtifacts,
20
23
  removeRunDirectory,
@@ -82,6 +85,14 @@ export interface DailyCleanupResult {
82
85
  dateKey: string;
83
86
  removedRunDirs: number;
84
87
  removedSessionPaths: number;
88
+ /** Launch attempts that never produced a run, reclaimed on this pass. */
89
+ removedAbandonedLaunches: number;
90
+ errors: string[];
91
+ }
92
+
93
+ /** Outcome of the launch-debris sweep alone (unit-testable, no daily marker). */
94
+ export interface AbandonedLaunchSweepResult {
95
+ removed: string[];
85
96
  errors: string[];
86
97
  }
87
98
 
@@ -715,12 +726,57 @@ function cleanSessionTree(
715
726
  return removed;
716
727
  }
717
728
 
729
+ /**
730
+ * Reclaim launch attempts that never produced a supervised run (#623).
731
+ *
732
+ * A launch that throws while preparing (or a pi that dies in that window) can
733
+ * leave a run directory with only `prompt.md` and a sandbox `control/` dir: no
734
+ * `meta.json`, no `output.log`. Such a directory is unreadable run evidence
735
+ * forever and skews `subagent_list` counts, so it is reclaimed once it is older
736
+ * than {@link ABANDONED_LAUNCH_GRACE_MS}. The grace is the only guard needed:
737
+ * launch preparation is synchronous and short, and a directory with a log is
738
+ * never debris (the child may have started and its output is real evidence).
739
+ *
740
+ * Age alone is not an ownership proof: `purgeAbandonedLaunch` re-classifies and
741
+ * removes under the run's metadata lock, and a launch claim owned by a live
742
+ * process makes the record not-debris at any age, so a preparer that is paused
743
+ * past the grace is preserved and the sweep never deletes a live attempt's
744
+ * artifacts (#623 R1). A record a writer retained is left for the next sweep
745
+ * with an error so the retention stays visible.
746
+ *
747
+ * Runs before the daily marker in {@link runDailyCleanupOnce}, so every launch
748
+ * reclaims earlier debris instead of waiting for the next day's sweep.
749
+ * Best-effort; never throws into its caller.
750
+ */
751
+ export function sweepAbandonedLaunches(options: { now?: number; graceMs?: number } = {}): AbandonedLaunchSweepResult {
752
+ const now = options.now ?? Date.now();
753
+ const grace = Number.isFinite(options.graceMs) && options.graceMs! >= 0 ? options.graceMs! : ABANDONED_LAUNCH_GRACE_MS;
754
+ const cutoff = now - grace;
755
+ let ids: string[];
756
+ try {
757
+ ids = readdirSync(join(baseDir(), "runs"));
758
+ } catch {
759
+ return { removed: [], errors: [] };
760
+ }
761
+ const removed: string[] = [];
762
+ const errors: string[] = [];
763
+ for (const id of ids) {
764
+ const attempt = abandonedLaunchRecord(id);
765
+ if (!attempt || attempt.mtimeMs >= cutoff) continue;
766
+ const purge = purgeAbandonedLaunch(id);
767
+ if (purge === "purged") removed.push(id);
768
+ else if (purge === "retained") errors.push(`${runDir(id)}: abandoned launch record could not be removed (in use, or its lock is unavailable)`);
769
+ }
770
+ return { removed, errors };
771
+ }
772
+
718
773
  export function runDailyCleanupOnce(options: DailyCleanupOptions = {}): DailyCleanupResult {
719
774
  const now = options.now ?? Date.now();
775
+ const abandoned = sweepAbandonedLaunches({ now });
720
776
  const dateKey = localDateKey(now);
721
777
  const state = readCleanupState();
722
778
  if (state.lastLocalDate === dateKey) {
723
- return { ran: false, dateKey, removedRunDirs: 0, removedSessionPaths: 0, errors: [] };
779
+ return { ran: false, dateKey, removedRunDirs: 0, removedSessionPaths: 0, removedAbandonedLaunches: abandoned.removed.length, errors: [...abandoned.errors] };
724
780
  }
725
781
 
726
782
  const errors: string[] = [];
@@ -761,7 +817,7 @@ export function runDailyCleanupOnce(options: DailyCleanupOptions = {}): DailyCle
761
817
  errors.push(`${cleanupStatePath()}: ${err instanceof Error ? err.message : String(err)}`);
762
818
  }
763
819
 
764
- return { ran: true, dateKey, removedRunDirs, removedSessionPaths, errors };
820
+ return { ran: true, dateKey, removedRunDirs, removedSessionPaths, removedAbandonedLaunches: abandoned.removed.length, errors: [...abandoned.errors, ...errors] };
765
821
  }
766
822
 
767
823
  /** Bytes held under one run directory. Best-effort; unreadable entries count 0. */
package/config.ts CHANGED
@@ -13,6 +13,7 @@ import { fileURLToPath } from "node:url";
13
13
  import { dirname, join } from "node:path";
14
14
  import { homedir } from "node:os";
15
15
  import { SELF_SPEC } from "./extensions.ts";
16
+ import { installedPackage } from "./child-dependencies.mjs";
16
17
  import { isDelegationMode, type DelegationMode } from "./delegation.ts";
17
18
  import type { TimingSettings } from "./timing.ts";
18
19
  import { harnessSettingsPath, readHarnessSetting, updateHarnessSetting } from "./shared-harness-settings.ts";
@@ -222,10 +223,13 @@ function piAgentDir(): string {
222
223
  * a missing dependency instead of silently launching a child without it.
223
224
  * (`-e` accepts either a package directory or an entrypoint file — verified.)
224
225
  */
225
- export function resolveExtensionPath(spec: string): string | undefined {
226
+ export function resolveExtensionPath(spec: string, declaringRoot?: string): string | undefined {
226
227
  if (spec === SELF_SPEC) return selfDir();
227
228
  const path = spec.startsWith("npm:")
228
- ? join(piAgentDir(), "npm", "node_modules", spec.slice(4))
229
- : spec;
230
- return existsSync(path) ? path : undefined;
229
+ ? (declaringRoot && installedPackage(spec.slice(4), [declaringRoot])) ?? (existsSync(join(piAgentDir(), "npm", "node_modules", spec.slice(4)))
230
+ ? join(piAgentDir(), "npm", "node_modules", spec.slice(4))
231
+ : installedPackage(spec.slice(4), [declaringRoot, join(piAgentDir(), "npm"), selfDir(),
232
+ join(piAgentDir(), "npm", "node_modules", "pi-better-harness")]))
233
+ : declaringRoot && !spec.startsWith("/") ? join(declaringRoot, spec) : spec;
234
+ return path && existsSync(path) ? path : undefined;
231
235
  }
package/continuation.ts CHANGED
@@ -1,11 +1,17 @@
1
1
  /**
2
- * Completed-subagent continuation.
2
+ * Subagent continuation.
3
3
  *
4
4
  * A subagent attempt is one detached `pi -p` process; its conversation is a
5
5
  * saved native session JSONL that outlives the process. Continuation keeps the
6
6
  * conversation and allocates a NEW attempt, so old logs, results, callback
7
7
  * markers, and timing records stay intact under their own run id.
8
8
  *
9
+ * A completed attempt and an interrupted attempt stopped by `subagent_stop`
10
+ * (status `killed`) are both continuable: stopping ends an execution, not the
11
+ * saved conversation or the uncommitted workspace it leaves behind. The stopped
12
+ * attempt is never rewritten; the next attempt keeps `rootRunId` and records
13
+ * `resumedFrom`, so the interruption and its recovery stay distinguishable.
14
+ *
9
15
  * This module owns the four seams that decision needs and that the rest of the
10
16
  * package must not duplicate:
11
17
  *
@@ -25,8 +31,8 @@
25
31
  *
26
32
  * Foreground-session ownership is provenance, not an authorization boundary:
27
33
  * Pi sessions are ordinary files on disk, so any foreground session that can
28
- * name a completed attempt with a verifiable saved conversation, workspace, and
29
- * launch recipe may continue it (or release its optional retention). The new
34
+ * name a continuable attempt with a verifiable saved conversation, workspace,
35
+ * and launch recipe may continue it (or release its optional retention). The new
30
36
  * attempt records the INVOKING foreground as its callback origin and its
31
37
  * permission admission is re-resolved from the current profile, so continuing
32
38
  * transfers the run to the caller instead of borrowing the original owner's
@@ -417,7 +423,7 @@ export function markRetentionReleased(
417
423
  * True when `origin` is the foreground session recorded on the run.
418
424
  *
419
425
  * This is a provenance/labelling helper, deliberately NOT an admission gate: a
420
- * different foreground session may continue a completed attempt (see the
426
+ * different foreground session may continue a continuable attempt (see the
421
427
  * module header). Callers that need to route a notification use it to decide
422
428
  * which foreground a run belongs to, not to deny an operation.
423
429
  */
@@ -451,7 +457,42 @@ function isActiveAttempt(meta: RunMeta): boolean {
451
457
  }
452
458
 
453
459
  /**
454
- * Validate one completed attempt for continuation and return the exact
460
+ * Terminal statuses whose saved conversation may be reopened by a new attempt.
461
+ * A stopped (`killed`) run is an interrupted execution, not a destroyed
462
+ * conversation; other terminal outcomes keep their existing refusal.
463
+ */
464
+ const CONTINUABLE_STATUSES: ReadonlySet<RunStatus> = new Set(["completed", "killed"]);
465
+
466
+ /**
467
+ * A recorded writer that may still be appending to the conversation.
468
+ *
469
+ * A fresh launch opens a brand-new session and takes no lease, so a killed
470
+ * attempt can be recorded terminal while its child is still alive (for example
471
+ * SIGTERM is pending behind SIGSTOP). In that state no lease blocks the next
472
+ * writer. Check the prior attempt explicitly — the active-sibling scan excludes
473
+ * it — plus every same-conversation attempt that is not known to have exited.
474
+ * `completed`/`failed` attempts are omitted because their compact durable
475
+ * records drop the process-start identity, so a recycled pid could otherwise
476
+ * block an unrelated conversation. `recordedWriterLive` applies the same pid
477
+ * and start-token evidence the conversation lease uses.
478
+ */
479
+ function findLiveConversationWriter(
480
+ prior: RunMeta,
481
+ others: readonly RunMeta[],
482
+ probe?: LeaseProbe,
483
+ ): RunMeta | undefined {
484
+ const candidates = [
485
+ prior,
486
+ ...others.filter((meta) => meta.sessionId === prior.sessionId
487
+ && meta.id !== prior.id
488
+ && meta.status !== "completed"
489
+ && meta.status !== "failed"),
490
+ ];
491
+ return candidates.find((meta) => recordedWriterLive(meta, probe));
492
+ }
493
+
494
+ /**
495
+ * Validate one continuable attempt for continuation and return the exact
455
496
  * conversation plus frozen recipe to relaunch. Every refusal is fail-closed:
456
497
  * nothing is spawned and no history is created or replaced.
457
498
  */
@@ -460,6 +501,8 @@ export function planContinuation(options: {
460
501
  prior: RunMeta | undefined;
461
502
  origin: RunCallbackOrigin | undefined;
462
503
  others: readonly RunMeta[];
504
+ /** Process-identity seam for the recorded-writer check. */
505
+ probe?: LeaseProbe;
463
506
  }): ContinuationPlan {
464
507
  const { id, prior, origin, others } = options;
465
508
  if (!prior) throw refusal(id, "no such run id.");
@@ -469,8 +512,8 @@ export function planContinuation(options: {
469
512
  // and recipe are the thing being continued, and Pi sessions are shared
470
513
  // on-disk state rather than a per-foreground boundary.
471
514
  if (!origin?.sessionId) throw refusal(id, "the active foreground session identity is unavailable.");
472
- if (prior.status !== "completed") {
473
- throw refusal(id, `its status is ${prior.status}; only a completed run can be continued. Stop or launch a new run instead.`);
515
+ if (!CONTINUABLE_STATUSES.has(prior.status)) {
516
+ throw refusal(id, `its status is ${prior.status}; only a completed or stopped run can be continued. Stop a running attempt or launch a new run instead.`);
474
517
  }
475
518
  const recipe = prior.recipe;
476
519
  if (!recipe || recipe.version !== 1) throw refusal(id, "it was launched before continuation support, so no launch recipe was saved.");
@@ -480,6 +523,14 @@ export function planContinuation(options: {
480
523
  const active = others.find((meta) => meta.sessionId === prior.sessionId && meta.id !== prior.id && isActiveAttempt(meta));
481
524
  if (active) throw refusal(id, `attempt ${active.id} is still active in the same conversation; stop it first.`);
482
525
 
526
+ // A killed record means stop was requested, not that the writer exited. A
527
+ // fresh launch has no lease, so this check is the only admission barrier
528
+ // while the prior child can still append to the saved conversation.
529
+ const writer = findLiveConversationWriter(prior, others, options.probe);
530
+ if (writer) {
531
+ throw refusal(id, `attempt ${writer.id} is still active and may still be writing the conversation (pid ${writer.pid}); wait for it to exit before continuing.`);
532
+ }
533
+
483
534
  let workspaceIsDir = false;
484
535
  try { workspaceIsDir = statSync(recipe.cwd).isDirectory(); } catch { workspaceIsDir = false; }
485
536
  if (!workspaceIsDir) throw refusal(id, `its workspace ${recipe.cwd} is missing.`);
package/docs/usage.md CHANGED
@@ -99,10 +99,10 @@ thresholds continue to take precedence for subagent health.
99
99
  | `subagent_spawn` | never | Launch a task in a background subagent; returns a run id at once. Params: `prompt`, `name`, `model`, `tools` (allowlist), `exclude_tools`, `sandbox`, `sandbox_dir`, `callback`, `clean`, `cwd`, `git_clone_workspace`, `approve`, `allow_nested`, optional `session_id` or `session_name` (continue a saved conversation), and the [timing](#run-timing-deadline-ceiling-stuck) overrides `deadline_minutes`, `grace_minutes`, `max_minutes`, `stuck_minutes`. |
100
100
  | `subagent_spawn_batch` | never | Launch several independent subagents at once. Each job becomes a normal run. Params: `batchName`, `shared` (options applied to every job), `jobs[]` (each needs `prompt`; optional per-job `session_id` or `session_name` continues a saved conversation), `onCapacity` (`reject` or `launch-available`). |
101
101
  | `subagent_settings` | never | Read-only effective settings and capacity snapshot. No parameters. Returns `delegationMode`, `maxConcurrent`, per-setting `sources` (`session` or `config`), a stable settings `revision`, `runningCount`, `pendingCount`, `occupiedSlots`, and `availableSlots`. The limit is a ceiling, not a target; spawn admission rechecks live capacity. |
102
- | `subagent_list` | never | Compact list for the current folder and descendants across foreground sessions (default 10 rows / 1 KiB page). Each row includes `session_id`. Params: `all` (machine-global search), `limit` (default 10, max 100), `cursor`, `max_bytes` (max 4 KiB), `status` (`running`, `completed`, `failed`, `killed`, `exited`, durable `orphaned`, `lost`). Incident counts are compact; no spend/tool histories. |
103
- | `subagent_output` | never | Bounded current-session excerpt (default 1 KiB / 10 lines). Params: `id`, `lines` (`tail_lines` is a deprecated alias), `cursor` (a returned `nextCursor`, `statusCursor`, or `incidentCursor`), `max_bytes` (max 4 KiB; raw 16 KiB default, 64 KiB max), `mode` (`raw` pages retained log bytes), `include` (`["cost"]`, `["tools"]`, or both: opt-in spend and tool-count lines), `all` (foreign-session id). Missing/unreadable logs are gaps, not empty healthy output. |
104
- | `subagent_result` | never | Finished-run answer for the current session (2048-byte page). Params: `id`, `cursor` (a returned `nextCursor` continues the answer; `statusCursor` / `incidentCursor` also accepted), `max_bytes` (maximum 8192 bytes), `lines` (optional line cap per answer page), `mode` (`raw`), `include` (`["cost"]`, `["tools"]`, or both), `all` (foreign-session id). Failures and exceptional lifecycle facts come before progress; no tool-name histories. TUI folding is display-only. |
105
- | `subagent_stop` | never | SIGTERM a running run's process group. |
102
+ | `subagent_list` | never | Compact list for the current folder and descendants across foreground sessions (default 10 rows / 1 KiB page). Each row includes `session_id`. Params: `all` (machine-global search), `limit` (default 10, max 100), `cursor`, `max_bytes` (max 4 KiB), `status` (`running`, `completed`, `failed`, `killed`, `exited`, durable `orphaned`, `lost`). Incident counts are compact; no spend/tool histories. Abandoned launch records are reported separately and are never counted as runs. |
103
+ | `subagent_output` | never | Bounded current-session excerpt (default 1 KiB / 10 lines). Params: `id`, `lines` (`tail_lines` is a deprecated alias), `cursor` (a returned `nextCursor`, `statusCursor`, or `incidentCursor`), `max_bytes` (max 4 KiB; raw 16 KiB default, 64 KiB max), `mode` (`raw` pages retained log bytes), `tail` (raw mode: start from the newest retained byte and page backwards; the final step returns an append-ready cursor), `include` (`["cost"]`, `["tools"]`, or both: opt-in spend and tool-count lines), `all` (foreign-session id). Missing/unreadable logs are gaps, not empty healthy output. |
104
+ | `subagent_result` | never | Finished-run answer for the current session (2048-byte page). Params: `id`, `cursor` (a returned `nextCursor` continues the answer; `statusCursor` / `incidentCursor` also accepted), `max_bytes` (maximum 8192 bytes), `lines` (optional line cap per answer page), `mode` (`raw`), `tail` (raw mode: newest bytes first), `include` (`["cost"]`, `["tools"]`, or both), `all` (foreign-session id). Failures and exceptional lifecycle facts come before progress; no tool-name histories. TUI folding is display-only. |
105
+ | `subagent_stop` | never | SIGTERM a running run's process group. The run is terminal, so its completion callback (one per run id) reports `killed`. An abandoned launch record (see below) is removed instead of stopped, and a run a concurrent launch owns is preserved. |
106
106
 
107
107
  ## Finding a saved conversation
108
108
 
@@ -136,6 +136,16 @@ Each attempt gets a new run id, log, timing record, and capacity slot while the
136
136
  native session id and history stay the same. The launch recipe preserves the
137
137
  worker's role, tools, model, and workspace, including uncommitted changes.
138
138
 
139
+ A run stopped with `subagent_stop` (status `killed`) can be continued the same
140
+ way. Stopping ends that execution, not the saved conversation or its
141
+ uncommitted workspace: the next attempt reopens the same history and records
142
+ `resumedFrom`, while the stopped attempt's status, log, and result stay as they
143
+ were. A run that ended `failed` or `lost` is still refused; this path recovers
144
+ interrupted work, it does not retry a failed run. The stopped child must also
145
+ have exited: if the stop signal has not taken effect yet (for example the
146
+ process was suspended), continuation is refused until that recorded child exits.
147
+ The saved history and workspace stay intact while the stop settles.
148
+
139
149
  `session_name` is an exact display-name match within the current folder and its
140
150
  descendants. Several attempts of the same conversation count once. If several
141
151
  conversations share the name, spawn reports matching session ids and refuses to
@@ -244,10 +254,15 @@ may be fractional. A job's own number (including `0`) wins over `shared`.
244
254
  sandbox command time limit can bound individual commands. With the run ceiling off, a steer stuck behind a
245
255
  hung tool call is never delivered, the deadline stop stays held, and the run
246
256
  is never stopped by that deadline. Opt into a ceiling to bound the whole run.
247
- - The parent reads at most the last 32 MiB of a child log after `/reload`. If
248
- the log is larger and the running tool call started before that window, the
249
- parent cannot see the call, so the hold is lost and grace counts from when
250
- the steer was sent. The child can be stopped mid-call.
257
+ - The parent reads at most the last 32 MiB of a child log after `/reload`. It
258
+ also records the call it last saw open in the run's metadata on each
259
+ supervision tick, so a reload normally keeps the hold and the not-stuck
260
+ accounting even when the call's start is outside that window. The record is
261
+ written by the tick, so a call that started less than one tick (15 s) before
262
+ the reload is not covered; and a record whose call ended while the window was
263
+ lost keeps the hold, and keeps the run from being reported stuck, until the
264
+ next observed tool call starts. Opt into a ceiling when the run needs a hard
265
+ wall-clock bound.
251
266
  - The child confirms delivery by matching the steer's exact text in its
252
267
  conversation. If another extension rewrites user input (an input-transform
253
268
  hook), the text no longer matches, no receipt is written, and grace silently
@@ -266,7 +281,9 @@ harness remembers up to 4096 distinct calls per run as fixed-size hashes of the
266
281
  name and normalized arguments; past that the oldest is forgotten, so a call from
267
282
  long ago counts again. Time the child spends waiting on a running tool call does not count toward the
268
283
  stuck window, so a child in the middle of a 20-minute test run is waiting, not
269
- stuck. A hanging command can be bounded by the sandbox command time limit; the run
284
+ stuck — including after `/reload`: the call the parent saw open is stored in the
285
+ run's metadata, so a bounded log read that no longer contains its start does not
286
+ turn it into "no progress". A hanging command can be bounded by the sandbox command time limit; the run
270
287
  ceiling separately bounds the whole run.
271
288
  The other stuck signal is the existing escalation: the same operation failing
272
289
  three times wakes the parent once as an `Action required` incident
@@ -327,6 +344,14 @@ given.
327
344
  pending records retryable, and `/reload` recovers records explicitly marked
328
345
  pending. `callback:false` sends no model message; read the durable result later
329
346
  with `subagent_result`.
347
+ - **One completion per run.** A run's ordinary notification is identified by
348
+ its run id, so a terminal run is reported once even if its status wording
349
+ changes (failure notes, observation gaps) between queueing and delivery.
350
+ Stopped runs are terminal too: `subagent_stop`, a navigator Close, the reload
351
+ drain, or cleanup that finalizes an orphaned run from its log records the same
352
+ pending completion, so the caller receives one `killed`/`completed`/`failed`
353
+ row instead of discovering the outcome by polling `subagent_list()`. A run
354
+ stopped while the session is shutting down is recovered by the next session.
330
355
  - **Optional busy steering.** In `/harness-settings`, set **Completions while
331
356
  busy** to **Steer active run** to receive ordinary completions during
332
357
  foreground work. Changes autosave to the current session branch and apply
@@ -778,6 +803,48 @@ state. Session shutdown disposes open navigator timers.
778
803
 
779
804
  The live widget, concurrency cap, and supervision ticker track this Pi process's runs. `subagent_list` searches the current folder and its descendants across foreground sessions; `all:true` searches globally. Rows show the attempt id and the native `session_id`, so a listed conversation can be continued explicitly. Results are newest first, with 10 rows / 1 KiB by default. Use `limit` (max 100), `max_bytes` (max 4 KiB), and `status` filters as needed. Cursors are bound to the local folder or global scope and cannot be replayed from a different folder. Id-based `subagent_result` and `subagent_output` keep their current-session scope; use `all:true` to read another session's run evidence. Unknown ownership remains an explicit gap for those evidence tools. Saved conversation discovery and continuation do not require the original foreground session to exist.
780
805
 
806
+ ## Abandoned launch records
807
+
808
+ A launch creates and claims its run directory, writes `prompt.md`, and prepares
809
+ the sandbox `control/` dir before the child starts and `meta.json` is committed. When that
810
+ preparation fails — or Pi dies inside that window — only those artifacts remain:
811
+ no metadata (nothing was committed) and no `output.log` (the log is created at
812
+ spawn and removed when the spawn itself fails). A launch failure now removes
813
+ them, so this state cannot be created anew.
814
+
815
+ A directory in that state that is left by an older version or a crashed process
816
+ is an **abandoned launch record**, not a run. It has no owner, status, log or
817
+ result, and can never gain any, so `subagent_list` reports it separately as not
818
+ run evidence and does not count it:
819
+
820
+ ```text
821
+ 1 abandoned launch record(s), not run evidence and not counted: the launch
822
+ stopped before any child started (prompt written, no metadata, no log): sa_…
823
+ Cleanup reclaims them after 1 hour; remove one now with subagent_stop <id>.
824
+ ```
825
+
826
+ Every launch's hygiene pass (`runDailyCleanupOnce`, alongside the daily and size
827
+ sweeps) reclaims abandoned launch records older than one hour, or immediately
828
+ with `subagent_stop <id>`. Only the attempt's own run directory, its per-run
829
+ session directory, and a clone workspace it owned are removed.
830
+
831
+ Cleanup never deletes a live attempt. A launch claims its run directory
832
+ (`.launch-attempt.json`: pid + process start identity) before it prepares
833
+ anything, and removes the claim when `meta.json` becomes the record. A record
834
+ whose claim is owned by a live process is not debris at any age, and the purge
835
+ re-classifies under the same per-run metadata lock a launch publishes under, so a
836
+ launch that commits metadata while a purge waits is preserved. In that case
837
+ `subagent_stop` reports `Preserved …` and removes nothing:
838
+
839
+ ```text
840
+ Preserved sa_…: a concurrent launch published this run (running), so nothing
841
+ was removed. Call subagent_stop again to stop the run.
842
+ ```
843
+
844
+ A directory that has a log is deliberately **not** treated as debris either: a
845
+ child may have started and its output is real evidence, so it stays an explicit
846
+ unreadable-record gap until normal retention reclaims it.
847
+
781
848
  ## Supervision health (`orphaned` / `lost`)
782
849
 
783
850
  While a current-parent run is `running` or `orphaned`, a periodic health tick
package/extensions.mjs CHANGED
@@ -47,6 +47,7 @@ export const SELF_SPEC = "self";
47
47
  * replace these per provider (an empty list disables the built-in entry).
48
48
  */
49
49
  export const BUILTIN_PROVIDER_EXTENSIONS = {
50
+ "router": "npm:pi-better-model-router",
50
51
  "ollama-cloud": "npm:pi-ollama-cloud",
51
52
  };
52
53
 
package/finalization.ts CHANGED
@@ -144,7 +144,7 @@ export function buildSubagentResultText(id: string): string | null {
144
144
  /** Optional paging/raw evidence for the registered result tool. */
145
145
  export function buildSubagentResultPayload(
146
146
  id: string,
147
- request?: { cursor?: string; maxBytes?: unknown; mode?: unknown; all?: unknown },
147
+ request?: { cursor?: string; maxBytes?: unknown; mode?: unknown; all?: unknown; lines?: unknown; include?: unknown; history?: unknown; tail?: unknown },
148
148
  healthLine = "",
149
149
  scopeKey = `parent:${process.pid}`,
150
150
  ): string | null {