pi-goal-delegate 0.2.0 → 0.3.1

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/src/registry.ts CHANGED
@@ -23,6 +23,7 @@ import {
23
23
  isFailure,
24
24
  isTerminal,
25
25
  MAX_MAX_LIVE,
26
+ MAX_WAIT_MS,
26
27
  shortGoal,
27
28
  type ContainmentVerdict,
28
29
  type RunProgress,
@@ -101,6 +102,8 @@ export interface StartOptions {
101
102
  scope?: "session" | "workspace";
102
103
  isolated?: boolean;
103
104
  inlineSettleMs?: number;
105
+ /** Aborts only the inline wait; the admitted run continues in the background. */
106
+ signal?: AbortSignal;
104
107
  /** A command the parent runs to prove a `complete` verdict. */
105
108
  verify?: { command: string };
106
109
  /** A run id or child session to continue instead of starting cold. */
@@ -113,7 +116,7 @@ export interface StartOptions {
113
116
  /** Maximum absolute delegation depth for the new run tree. */
114
117
  maxDepth?: number;
115
118
  /** TUI hook: called when live progress changes. */
116
- onProgress?: (progress: RunProgress, status: RunStatus) => void;
119
+ onProgress?: (progress: RunProgress, status: RunStatus, runId: string) => void;
117
120
  }
118
121
 
119
122
  export interface AwaitOptions {
@@ -121,6 +124,13 @@ export interface AwaitOptions {
121
124
  mode?: "all" | "any";
122
125
  waitMs?: number;
123
126
  signal?: AbortSignal;
127
+ /**
128
+ * Whether this call reports the settles it returns.
129
+ *
130
+ * Reporting a settle and announcing it are one event or the other, never
131
+ * both, so the caller that is told is the caller that claims. Default true.
132
+ */
133
+ claim?: boolean;
124
134
  }
125
135
 
126
136
  export interface AwaitResult {
@@ -162,7 +172,6 @@ function combineContainment(outcomes: readonly RunOutcome[]): ContainmentVerdict
162
172
 
163
173
  const DELIVERY_WINDOW_MS = 150;
164
174
  const DEFAULT_WAIT_MS = 30_000;
165
- const MAX_WAIT_MS = 50_000;
166
175
  /** Retention runs at most this often, so a burst of settles is one scan. */
167
176
  const PRUNE_INTERVAL_MS = 5 * 60_000;
168
177
 
@@ -379,9 +388,10 @@ export class RunRegistry {
379
388
  sessionId: this.host.sessionId,
380
389
  isolated: options.isolated,
381
390
  inlineSettleMs: options.inlineSettleMs,
391
+ signal: options.signal,
382
392
  parentActiveTools: this.host.activeTools,
383
- onProgress: (progress, status) => {
384
- onProgress?.(progress, status);
393
+ onProgress: (progress, status, runId) => {
394
+ onProgress?.(progress, status, runId);
385
395
  },
386
396
  onSettle: (outcome) => this.onSettle(outcome),
387
397
  onAdmitted: (handle) => {
@@ -396,7 +406,10 @@ export class RunRegistry {
396
406
  };
397
407
  const handle = await startRun(request);
398
408
  this.handles.set(handle.runId, handle);
399
- if (handle.outcome?.settledInline) this.consume([handle.runId]);
409
+ // A codemode deadline can discard this nested return value even when the
410
+ // child settled while the wait was aborting. Leave that settle for the
411
+ // completion channel: a possible redelivery is recoverable, a lost one is not.
412
+ if (handle.outcome && !options.signal?.aborted) this.consume([handle.runId]);
400
413
  this.release([handle.runId]);
401
414
  return handle;
402
415
  }
@@ -635,7 +648,7 @@ export class RunRegistry {
635
648
  "",
636
649
  ...lines,
637
650
  "",
638
- `Call delegate_await({ runIds: [${runIds.map((runId) => JSON.stringify(runId)).join(", ")}] }) for the full outcome, or read the run record under ${delegateRoot()}.`,
651
+ `Call delegate_status({ runIds: [${runIds.map((runId) => JSON.stringify(runId)).join(", ")}] }) for the full outcome, or read the run record under ${delegateRoot()}.`,
639
652
  ].join("\n");
640
653
  }
641
654
  const summary = pending.map((outcome) => `${outcome.runId}:${outcome.status}`).join(", ");
@@ -699,6 +712,13 @@ export class RunRegistry {
699
712
  }
700
713
  }
701
714
 
715
+ /** The run ids that are still live, in start order. */
716
+ liveIds(): string[] {
717
+ return this.list()
718
+ .filter((handle) => !isTerminal(handle.status))
719
+ .map((handle) => handle.runId);
720
+ }
721
+
702
722
  /**
703
723
  * Wait for runs, bounded by waitMs. A wait never cancels a run.
704
724
  *
@@ -743,7 +763,10 @@ export class RunRegistry {
743
763
  const handle = this.handles.get(id);
744
764
  if (handle) stillRunning.push(liveOutcome(handle));
745
765
  }
746
- if (!options.signal?.aborted) this.consume(settledIds);
766
+ // Consume exactly what an active caller receives. An aborted codemode
767
+ // script discards nested return values, so its outcomes must go back to
768
+ // the completion channel even when the abort raced the settle.
769
+ if (options.claim !== false && !options.signal?.aborted) this.consume(settledIds);
747
770
  const result: AwaitResult = {
748
771
  settled: mode === "any" ? outcomes.length > 0 : outcomes.length === known.length,
749
772
  timedOutWaiting,
@@ -753,7 +776,7 @@ export class RunRegistry {
753
776
  };
754
777
  if (expired) {
755
778
  result.note =
756
- "The wait ended at waitMs; nothing was cancelled. A delegation takes minutes: end the turn and let the completion message wake you, or wait again.";
779
+ "The wait ended at waitMs; nothing was cancelled. Call delegate_status again with a larger waitMs (and a codemode timeout_ms above it), or yield the turn (via goal_wait if Goal mode is active) so the delegate-completion message wakes you.";
757
780
  } else if (aborted) {
758
781
  result.note = "The wait was cancelled; the delegation itself is untouched and still running.";
759
782
  }
@@ -15,15 +15,19 @@
15
15
  import { Value } from "typebox/value";
16
16
 
17
17
  /**
18
- * A local JSON pointer inside the schema document, or undefined when it misses.
18
+ * Whether a local JSON pointer inside the schema document resolves.
19
+ *
20
+ * The answer is a boolean because that is the only question the audit asks. The
21
+ * value a pointer names is a schema fragment of no fixed type, and handing it
22
+ * back would invite callers to interpret a document nothing has validated.
19
23
  *
20
24
  * The fragment of `#/a/b` is `/a/b`, not `a/b`: the leading slash is part of
21
25
  * the pointer, and treating the fragment as the pointer resolves every ref to
22
26
  * the empty top-level key.
23
27
  */
24
- function pointer(schema: unknown, fragment: string): unknown {
25
- if (fragment === "") return schema;
26
- if (!fragment.startsWith("/")) return undefined;
28
+ function resolves(schema: unknown, fragment: string): boolean {
29
+ if (fragment === "") return true;
30
+ if (!fragment.startsWith("/")) return false;
27
31
  let cursor: unknown = schema;
28
32
  for (const token of fragment.slice(1).split("/")) {
29
33
  let key: string;
@@ -32,17 +36,17 @@ function pointer(schema: unknown, fragment: string): unknown {
32
36
  } catch {
33
37
  // A malformed percent escape names no member of any document. It is an
34
38
  // unresolved pointer, not a crash inside the caller's argument check.
35
- return undefined;
39
+ return false;
36
40
  }
37
- if (typeof cursor !== "object" || cursor === null) return undefined;
41
+ if (typeof cursor !== "object" || cursor === null) return false;
38
42
  // Own properties only. A plain index read resolves `#/toString` through the
39
43
  // prototype chain, so the audit admitted a schema the validator rejects for
40
44
  // every value - the exact trap this audit exists to refuse.
41
- if (!Object.hasOwn(cursor, key)) return undefined;
45
+ if (!Object.hasOwn(cursor, key)) return false;
42
46
  cursor = (cursor as Record<string, unknown>)[key];
43
- if (cursor === undefined) return undefined;
47
+ if (cursor === undefined) return false;
44
48
  }
45
- return cursor;
49
+ return true;
46
50
  }
47
51
 
48
52
  /** `$ref` values this package cannot resolve, split by the reason. */
@@ -74,7 +78,7 @@ function auditRefs(schema: unknown): RefAudit {
74
78
  // `#` is the whole document; `#name` is an anchor, not a pointer, and
75
79
  // is left to the validator rather than judged here.
76
80
  const fragment = value.slice(1);
77
- if (fragment !== "" && fragment.startsWith("/") && pointer(schema, fragment) === undefined) dangling.add(value);
81
+ if (fragment !== "" && fragment.startsWith("/") && !resolves(schema, fragment)) dangling.add(value);
78
82
  continue;
79
83
  }
80
84
  visit(value);
@@ -119,9 +123,16 @@ export function auditResultSchema(schema: Record<string, unknown>): string | und
119
123
  * own error list, so the repair is one call away instead of a guess.
120
124
  */
121
125
  export function describeSchemaErrors(schema: Record<string, unknown>, value: unknown, limit = 4): string {
122
- let errors: Array<{ instancePath?: string; message?: string }>;
126
+ interface SchemaError {
127
+ instancePath?: string;
128
+ message?: string;
129
+ }
130
+ let errors: SchemaError[];
123
131
  try {
124
- errors = Value.Errors(schema as never, value) as unknown as Array<{ instancePath?: string; message?: string }>;
132
+ // SAFETY: the validator returns records described by its own public type;
133
+ // this function reads exactly two documented fields from each of them, and
134
+ // nothing else about the record is part of the contract here.
135
+ errors = Value.Errors(schema as never, value) as unknown as SchemaError[];
125
136
  } catch (error) {
126
137
  return `The schema itself could not be evaluated: ${String(error).slice(0, 300)}`;
127
138
  }
package/src/retention.ts CHANGED
@@ -223,62 +223,123 @@ function planRemovals(candidates: Candidate[], policy: RetentionPolicy, liveByte
223
223
  return removable;
224
224
  }
225
225
 
226
+ /** The plan one pass of the policy produces, before anything is deleted. */
227
+ interface Scan {
228
+ root: string;
229
+ policy: RetentionPolicy;
230
+ candidates: Candidate[];
231
+ live: string[];
232
+ liveBytes: number;
233
+ totalBytes: number;
234
+ removable: Set<string>;
235
+ }
236
+
226
237
  /**
227
- * Remove expired and surplus run records. Best effort: a directory that cannot
228
- * be read or removed stays, and the next pass tries again.
238
+ * Read the record root and compute what the policy would do.
239
+ *
240
+ * Shared by the prune and by the report, so "what the next prune removes" and
241
+ * "what this prune removed" cannot disagree: a caller that only reports is
242
+ * looking at the same computation the deleting pass runs.
229
243
  */
230
- export function pruneRunRecords(options: PruneOptions = {}): PruneResult {
244
+ function scan(options: PruneOptions): Scan {
231
245
  const now = options.now ?? Date.now();
232
- const policy = retentionPolicy();
233
- const keepRuns = Math.max(0, options.keepRuns ?? policy.keepRuns);
234
- const maxAgeDays = Math.max(0, options.maxAgeDays ?? policy.maxAgeDays);
235
- const maxBytes = Math.max(0, options.maxBytes ?? policy.maxBytes);
236
- const root = options.root ?? delegateRoot();
237
- const result: PruneResult = {
238
- scanned: 0,
239
- removed: [],
240
- live: [],
241
- kept: 0,
242
- bytesFreed: 0,
243
- bytesScanned: 0,
246
+ const read = retentionPolicy();
247
+ const policy: RetentionPolicy = {
248
+ keepRuns: Math.max(0, options.keepRuns ?? read.keepRuns),
249
+ maxAgeDays: Math.max(0, options.maxAgeDays ?? read.maxAgeDays),
250
+ maxBytes: Math.max(0, options.maxBytes ?? read.maxBytes),
244
251
  };
252
+ const root = options.root ?? delegateRoot();
253
+ const candidates: Candidate[] = [];
254
+ const live: string[] = [];
255
+ let liveBytes = 0;
245
256
 
246
257
  let names: string[];
247
258
  try {
248
259
  names = readdirSync(root);
249
260
  } catch {
250
- return result;
261
+ return { root, policy, candidates, live, liveBytes: 0, totalBytes: 0, removable: new Set() };
251
262
  }
252
263
 
253
- const candidates: Candidate[] = [];
254
- let liveBytes = 0;
255
264
  for (const name of names) {
256
265
  const record = isRunRecord(root, name);
257
266
  if (!record) continue;
258
- result.scanned += 1;
259
267
  const classified = classify(record, name, now, options.isLive);
260
268
  if (classified === "live") {
261
- result.live.push(name);
269
+ live.push(name);
262
270
  // A live record still occupies disk, so it counts toward the total even
263
271
  // though no rule may remove it.
264
272
  liveBytes += recordBytes(record.dir);
265
273
  continue;
266
274
  }
267
- result.bytesScanned += classified.bytes;
268
275
  candidates.push(classified);
269
276
  }
270
- result.bytesScanned += liveBytes;
271
277
 
272
278
  // Oldest first: the age rule, the count cap and the size cap all want that order.
273
279
  candidates.sort((left, right) => right.ageMs - left.ageMs);
274
- const removable = planRemovals(candidates, { keepRuns, maxAgeDays, maxBytes }, liveBytes);
280
+ const removable = planRemovals(candidates, policy, liveBytes);
281
+ const totalBytes = liveBytes + candidates.reduce((sum, candidate) => sum + candidate.bytes, 0);
282
+ return { root, policy, candidates, live, liveBytes, totalBytes, removable };
283
+ }
275
284
 
276
- for (const candidate of candidates) {
277
- if (!removable.has(candidate.runId)) {
285
+ export interface RetentionScan {
286
+ /** The record root that was read. */
287
+ root: string;
288
+ /** The policy the scan applied. */
289
+ policy: RetentionPolicy;
290
+ /** Run records this extension owns. */
291
+ total: number;
292
+ /** Run ids that can still produce a verdict, so no rule may remove them. */
293
+ live: string[];
294
+ /** Bytes held by every record. */
295
+ bytes: number;
296
+ /** Run ids the next prune would remove. */
297
+ removable: string[];
298
+ /** Age of the oldest record, or undefined when there is none. */
299
+ oldestAgeMs?: number;
300
+ }
301
+
302
+ /**
303
+ * What the next prune would do, without doing it.
304
+ *
305
+ * Retention used to be observable only through its own deletions: a session
306
+ * learned that a record was old enough by finding it gone. This answers the same
307
+ * question before the answer is permanent.
308
+ */
309
+ export function scanRetention(options: PruneOptions = {}): RetentionScan {
310
+ const plan = scan(options);
311
+ return {
312
+ root: plan.root,
313
+ policy: plan.policy,
314
+ total: plan.candidates.length + plan.live.length,
315
+ live: plan.live,
316
+ bytes: plan.totalBytes,
317
+ removable: plan.candidates.filter((candidate) => plan.removable.has(candidate.runId)).map((candidate) => candidate.runId),
318
+ // Candidates are ordered oldest first, so the head is the oldest.
319
+ oldestAgeMs: plan.candidates[0]?.ageMs,
320
+ };
321
+ }
322
+
323
+ /**
324
+ * Remove expired and surplus run records. Best effort: a directory that cannot
325
+ * be read or removed stays, and the next pass tries again.
326
+ */
327
+ export function pruneRunRecords(options: PruneOptions = {}): PruneResult {
328
+ const plan = scan(options);
329
+ const result: PruneResult = {
330
+ scanned: plan.candidates.length + plan.live.length,
331
+ removed: [],
332
+ live: plan.live,
333
+ kept: 0,
334
+ bytesFreed: 0,
335
+ bytesScanned: plan.totalBytes,
336
+ };
337
+ for (const candidate of plan.candidates) {
338
+ if (!plan.removable.has(candidate.runId)) {
278
339
  result.kept += 1;
279
340
  continue;
280
341
  }
281
- if (!releaseWorktree(root, candidate.dir)) {
342
+ if (!releaseWorktree(plan.root, candidate.dir)) {
282
343
  result.kept += 1;
283
344
  continue;
284
345
  }
package/src/run.ts CHANGED
@@ -24,6 +24,7 @@ import {
24
24
  formatDuration,
25
25
  formatUsage,
26
26
  isTerminal,
27
+ MAX_WAIT_MS,
27
28
  parentBudgetVerdict,
28
29
  shortGoal,
29
30
  verifiedStatus,
@@ -84,7 +85,7 @@ import {
84
85
  } from "./worktree.ts";
85
86
 
86
87
  const TICK_MS = 250;
87
- const INLINE_LIMIT_MS = 10_000;
88
+ const INLINE_LIMIT_MS = MAX_WAIT_MS;
88
89
  const DEFAULT_VERIFY_TIMEOUT_MS = 120_000;
89
90
 
90
91
  /** What the child writes at the moment it has a verdict. */
@@ -245,6 +246,8 @@ export interface StartRequest {
245
246
  worktree?: boolean;
246
247
  /** Bounded wait for an immediate settle. 0 returns the handle at once. */
247
248
  inlineSettleMs?: number;
249
+ /** Aborts only the inline wait; the admitted run continues in the background. */
250
+ signal?: AbortSignal;
248
251
  /**
249
252
  * Called once admission is real: spec on disk, supervisor spawned, watcher
250
253
  * running. A registry uses it to register the handle before the inline wait,
@@ -253,7 +256,7 @@ export interface StartRequest {
253
256
  onAdmitted?: (handle: RunHandle) => void;
254
257
  /** Tools active in the parent, used to keep codemode callable in the child. */
255
258
  parentActiveTools?: readonly string[];
256
- onProgress?: (progress: RunProgress, status: RunStatus) => void;
259
+ onProgress?: (progress: RunProgress, status: RunStatus, runId: string) => void;
257
260
  onSettle?: (outcome: RunOutcome) => void;
258
261
  }
259
262
 
@@ -311,7 +314,7 @@ interface Runtime {
311
314
  tick?: ReturnType<typeof setInterval>;
312
315
  deadline?: ReturnType<typeof setTimeout>;
313
316
  onSettle?: (outcome: RunOutcome) => void;
314
- onProgress?: (progress: RunProgress, status: RunStatus) => void;
317
+ onProgress?: (progress: RunProgress, status: RunStatus, runId: string) => void;
315
318
  resolveDone: (outcome: RunOutcome) => void;
316
319
  lastProgressAt: number;
317
320
  }
@@ -684,7 +687,7 @@ function watch(runtime: Runtime, handle: RunHandle, startOffset: number, sourceP
684
687
  ? "limit"
685
688
  : "running";
686
689
  handle.status = live;
687
- runtime.onProgress?.(progress, live);
690
+ runtime.onProgress?.(progress, live, handle.runId);
688
691
  }
689
692
  if (progress.noProgressReason && !runtime.killReason) {
690
693
  runtime.killDetail = progress.noProgressReason;
@@ -892,17 +895,23 @@ export async function startRun(request: StartRequest): Promise<RunHandle> {
892
895
  request.onAdmitted?.(handle);
893
896
 
894
897
  // The window is a deadline, not a timer that outlives it: when the run
895
- // settles first the timeout is cleared, so nothing keeps the process awake
896
- // for the rest of the budget.
898
+ // settles first or the caller aborts the wait, the timeout and listener are
899
+ // cleared while the child keeps running in its own process.
897
900
  const inlineSettleMs = Math.min(Math.max(0, request.inlineSettleMs ?? 1000), INLINE_LIMIT_MS);
898
- if (inlineSettleMs > 0) {
899
- let expired;
901
+ if (inlineSettleMs > 0 && !request.signal?.aborted) {
902
+ let expired: ReturnType<typeof setTimeout> | undefined;
903
+ let onAbort: (() => void) | undefined;
900
904
  const window = new Promise<false>((resolve) => {
901
905
  expired = setTimeout(() => resolve(false), inlineSettleMs);
906
+ if (request.signal) {
907
+ onAbort = () => resolve(false);
908
+ request.signal.addEventListener("abort", onAbort, { once: true });
909
+ }
902
910
  });
903
911
  const settled = await Promise.race([done.then(() => true), window]);
904
- clearTimeout(expired);
905
- if (settled && handle.outcome) handle.outcome.settledInline = true;
912
+ if (expired) clearTimeout(expired);
913
+ if (onAbort && request.signal) request.signal.removeEventListener("abort", onAbort);
914
+ if (settled && handle.outcome && !request.signal?.aborted) handle.outcome.settledInline = true;
906
915
  }
907
916
  return handle;
908
917
  }
@@ -1048,7 +1057,7 @@ export type AttachResult =
1048
1057
  export async function attachRun(
1049
1058
  runId: string,
1050
1059
  spec: RunSpec,
1051
- sink: { onSettle?: (outcome: RunOutcome) => void; onProgress?: (progress: RunProgress, status: RunStatus) => void },
1060
+ sink: { onSettle?: (outcome: RunOutcome) => void; onProgress?: (progress: RunProgress, status: RunStatus, runId: string) => void },
1052
1061
  meta?: RunMetaRecord,
1053
1062
  ): Promise<AttachResult> {
1054
1063
  const paths = runPaths(runId);
package/src/spawn.ts CHANGED
@@ -49,7 +49,7 @@ export function delegateRoot(): string {
49
49
  /**
50
50
  * Run ids are `dl_<time36>_<random hex>`. Anything else is not a record this
51
51
  * extension created, and it is never allowed to name a path: a run id arrives
52
- * from the model (`delegate_await`) and from a command line, so a value like
52
+ * from the model (`delegate_status`) and from a command line, so a value like
53
53
  * `../../etc` must be rejected before it is joined to the record root.
54
54
  */
55
55
  const RUN_ID = /^dl_[a-z0-9]+_[a-z0-9]+$/u;
package/src/verify.ts CHANGED
@@ -9,6 +9,14 @@
9
9
  * The command runs in the parent, in the child's own working directory, with
10
10
  * the parent's environment. Its exit status is the verdict; its output is kept
11
11
  * as bounded context for the human and the model.
12
+ *
13
+ * The command is a shell command line, by contract: `pnpm test --filter x` is
14
+ * what a caller writes, and a pipeline or a redirect is a legitimate gate. It is
15
+ * therefore spawned through a shell, which is exactly as much authority as the
16
+ * caller already has: `verify` is chosen by the same agent that could run the
17
+ * same string with the `bash` tool. It is not an injection boundary, and the
18
+ * only defence that would matter here - refusing shell syntax - would break the
19
+ * feature it defends.
12
20
  */
13
21
 
14
22
  import { spawn } from "node:child_process";
@@ -61,6 +69,11 @@ export function runVerification(request: VerifyRequest): Promise<VerificationRec
61
69
 
62
70
  let child;
63
71
  try {
72
+ // The shell is the contract, not an accident: see the module header. The
73
+ // command comes from the delegating agent, which already holds shell
74
+ // authority in this session, and `PI_DELEGATE_ENV_DROP` is what bounds
75
+ // what it can reach.
76
+ // nosemgrep: javascript.lang.security.audit.spawn-shell-true.spawn-shell-true
64
77
  child = spawn(request.command, [], {
65
78
  cwd: request.cwd,
66
79
  shell: true,