apex-code 0.0.4 → 0.0.6

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.
Files changed (48) hide show
  1. package/CHANGELOG.md +14 -1
  2. package/dist/cli/agent-lifecycle.d.ts +24 -0
  3. package/dist/cli/agent-lifecycle.d.ts.map +1 -0
  4. package/dist/cli/agent-lifecycle.js +126 -0
  5. package/dist/cli/agent-lifecycle.js.map +1 -0
  6. package/dist/cli/args.d.ts +13 -0
  7. package/dist/cli/args.d.ts.map +1 -1
  8. package/dist/cli/args.js +80 -0
  9. package/dist/cli/args.js.map +1 -1
  10. package/dist/core/agent-session.d.ts +160 -0
  11. package/dist/core/agent-session.d.ts.map +1 -1
  12. package/dist/core/agent-session.js +265 -0
  13. package/dist/core/agent-session.js.map +1 -1
  14. package/dist/core/delegation/runtime.d.ts +682 -1
  15. package/dist/core/delegation/runtime.d.ts.map +1 -1
  16. package/dist/core/delegation/runtime.js +1339 -66
  17. package/dist/core/delegation/runtime.js.map +1 -1
  18. package/dist/core/sdk.d.ts +61 -3
  19. package/dist/core/sdk.d.ts.map +1 -1
  20. package/dist/core/sdk.js +316 -22
  21. package/dist/core/sdk.js.map +1 -1
  22. package/dist/core/tools/delegate.d.ts +8 -0
  23. package/dist/core/tools/delegate.d.ts.map +1 -1
  24. package/dist/core/tools/delegate.js +33 -3
  25. package/dist/core/tools/delegate.js.map +1 -1
  26. package/dist/core/workspace/git-observer.d.ts +16 -0
  27. package/dist/core/workspace/git-observer.d.ts.map +1 -1
  28. package/dist/core/workspace/git-observer.js +8 -1
  29. package/dist/core/workspace/git-observer.js.map +1 -1
  30. package/dist/core/workspace/git-worktree-owner.d.ts +89 -0
  31. package/dist/core/workspace/git-worktree-owner.d.ts.map +1 -0
  32. package/dist/core/workspace/git-worktree-owner.js +240 -0
  33. package/dist/core/workspace/git-worktree-owner.js.map +1 -0
  34. package/dist/main.d.ts.map +1 -1
  35. package/dist/main.js +20 -0
  36. package/dist/main.js.map +1 -1
  37. package/dist/modes/acp/server.d.ts +43 -1
  38. package/dist/modes/acp/server.d.ts.map +1 -1
  39. package/dist/modes/acp/server.js +78 -0
  40. package/dist/modes/acp/server.js.map +1 -1
  41. package/dist/modes/rpc/rpc-mode.d.ts.map +1 -1
  42. package/dist/modes/rpc/rpc-mode.js +38 -0
  43. package/dist/modes/rpc/rpc-mode.js.map +1 -1
  44. package/dist/modes/rpc/rpc-types.d.ts +110 -0
  45. package/dist/modes/rpc/rpc-types.d.ts.map +1 -1
  46. package/dist/modes/rpc/rpc-types.js.map +1 -1
  47. package/npm-shrinkwrap.json +5 -5
  48. package/package.json +2 -2
@@ -12,6 +12,8 @@
12
12
  * `AgentSession`/`createAgentSession` and therefore free of the import cycle that
13
13
  * would create (`sdk.ts` already imports `agent-session.ts`).
14
14
  */
15
+ import type { AgentRunBudgetUsage } from "apex-code-agent-core";
16
+ import { type SessionEntry } from "../session-manager.ts";
15
17
  import type { Capability } from "../tools/contract.ts";
16
18
  /** A delegatable agent's static configuration. Markdown + frontmatter in production (`agents.ts`); a plain object in tests. */
17
19
  export interface AgentDefinition {
@@ -26,12 +28,110 @@ export interface AgentDefinition {
26
28
  /** Resolve an agent type to its definition, or `undefined` if unknown. Production implements this over markdown/frontmatter (`agents.ts`); tests inject plain functions with the same shape. */
27
29
  export type AgentDefinitionResolver = (agentType: string) => AgentDefinition | undefined;
28
30
  /** A running or completed child, as far as the runtime needs to know. */
31
+ export type ChildSessionStatus = "idle" | "running" | "interrupted" | "closed";
32
+ /** Terminal outcome of a child's latest settled turn. */
33
+ export type ChildTurnOutcome = "completed" | "failed" | "interrupted";
34
+ /**
35
+ * Token and cost totals for one child run, rolled up from the child's OWN
36
+ * session transcript (the session-file reading seam; never a second transcript
37
+ * cache). The numbers are summed exactly as the provider reported them -- cost
38
+ * is provider-reported, so cache reads are NOT re-priced, re-counted, or
39
+ * double-counted; an entry without usage counts as zero.
40
+ */
41
+ export interface ChildRunUsageTotals {
42
+ inputTokens: number;
43
+ outputTokens: number;
44
+ cacheReadTokens: number;
45
+ cacheWriteTokens: number;
46
+ totalTokens: number;
47
+ cost: {
48
+ input: number;
49
+ output: number;
50
+ cacheRead: number;
51
+ cacheWrite: number;
52
+ total: number;
53
+ };
54
+ /** Wall-clock time (ms) the rollup was computed at. */
55
+ asOf: number;
56
+ /** Usage-bearing transcript entries examined (assistant messages, compaction, branch summaries), including those without usage. */
57
+ entriesCounted: number;
58
+ }
59
+ /** The output and terminal outcome of a child's latest settled turn, as reported by its own handle. */
60
+ export interface ChildTurnResult {
61
+ output: string;
62
+ outcome: ChildTurnOutcome;
63
+ }
64
+ /** Terminal outcome of one attempt on a child run. `cancelled` is recorded only by an explicit interrupt-with-reason. */
65
+ export type ChildRunAttemptOutcome = "completed" | "failed" | "interrupted" | "cancelled";
66
+ /**
67
+ * One launch-or-resume epoch of a child run (spec 2026-09-09, "Child
68
+ * lifecycle"): a launch is attempt 1; a resume closes the prior attempt with
69
+ * its terminal outcome and opens a new one. A live run's follow-ups and
70
+ * steering stay inside the active attempt. `usage` snapshots the child's own
71
+ * budget controller when its session exposes one (optional on the handle).
72
+ * `tokensAtEnd` snapshots the run-level usage/cost rollup (see
73
+ * `ChildRunUsageTotals`) at the attempt's settlement: these are
74
+ * CUMULATIVE-AT-END snapshots of the child's whole transcript, never per-attempt
75
+ * deltas -- range attribution between attempts is not attempted because turns
76
+ * that settled after the last persisted boundary are re-run on resume, so the
77
+ * transcript alone cannot attribute usage to an epoch.
78
+ */
79
+ export interface ChildRunAttempt {
80
+ id: string;
81
+ startedAt: number;
82
+ endedAt?: number;
83
+ outcome?: ChildRunAttemptOutcome;
84
+ error?: string;
85
+ usage?: AgentRunBudgetUsage;
86
+ tokensAtEnd?: ChildRunUsageTotals;
87
+ }
29
88
  export interface ChildSessionHandle {
89
+ readonly status: ChildSessionStatus;
30
90
  /** Run the task to completion and return the child's final output text. */
31
91
  run(task: string): Promise<{
32
92
  output: string;
33
93
  }>;
34
- /** Release the child's resources. Always called, including after a failed run. */
94
+ /**
95
+ * The latest settled turn's output and terminal outcome, derived by this handle
96
+ * from the actual prompt resolution; `undefined` before any turn settles. This --
97
+ * not the registry's stored first-turn promise -- is the source of truth for
98
+ * background retrieval after `sendInput`/`followUp`/resume.
99
+ */
100
+ latestResult(): ChildTurnResult | undefined;
101
+ wait(): Promise<void>;
102
+ interrupt(): void;
103
+ close(): void;
104
+ sendInput(input: string): Promise<void>;
105
+ followUp(input: string): Promise<void>;
106
+ /**
107
+ * Point-in-time snapshot of the child's own run budget counters, when its
108
+ * session exposes a controller. Optional: handles whose child session does
109
+ * not surface a controller simply omit it, and every consumer treats
110
+ * attempt/status usage as optional.
111
+ */
112
+ usage?(): AgentRunBudgetUsage | undefined;
113
+ /**
114
+ * Read-only view of the child's own session entries, when the handle can
115
+ * reach its (possibly in-memory) session manager. Optional: fixture handles
116
+ * need not expose it, and the usage rollup consults it only when the child
117
+ * has no resolvable transcript file (an in-memory child never persisted
118
+ * one). Without this seam AND a transcript file, the run's usage totals are
119
+ * simply unreportable (`undefined`), never guessed.
120
+ */
121
+ sessionEntries?(): readonly SessionEntry[] | undefined;
122
+ /**
123
+ * The derived policy this handle's child was built with (populated by the
124
+ * sdk's `buildChildSession` from the request's admission projection and its
125
+ * own construction values). Optional: fixture handles may omit it, and the
126
+ * runtime relays it onto the child-run record when present.
127
+ */
128
+ policy?: ChildRunPolicySnapshot;
129
+ /**
130
+ * True when the OS-containment supervisor marker check passed at this
131
+ * handle's construction. Optional for the same reason as `policy`.
132
+ */
133
+ sandboxEnforced?: boolean;
134
+ /** Release the child's resources. Called when the child or owning parent is closed. */
35
135
  dispose(): void;
36
136
  }
37
137
  export interface BuildChildSessionRequest {
@@ -39,12 +139,110 @@ export interface BuildChildSessionRequest {
39
139
  definition: AgentDefinition;
40
140
  /** The child's tool allowlist, already ceiling-checked -- exactly `definition.tools`, never narrowed. */
41
141
  toolNames: string[];
142
+ /**
143
+ * The admitted capability set from the shared admission projection
144
+ * (`resolveAdmittedDefinition`). Consumers use it to describe the child;
145
+ * they must never re-derive it (ADR 0010).
146
+ */
147
+ capabilities: ReadonlySet<Capability>;
42
148
  /** The child's own recursion depth (the parent's depth + 1), for the runtime constructing it to record on the child's session header (task 5.3). */
43
149
  depth: number;
44
150
  /** Stable id used for the child session and its artifact directory. */
45
151
  sessionId: string;
46
152
  /** Per-child artifact root, created before the child session is constructed. */
47
153
  artifactDir?: string;
154
+ workspace?: ChildWorkspaceRequest;
155
+ /**
156
+ * Reattachment marker (restart reconstruction): when set, `buildChildSession`
157
+ * opens this existing child session transcript instead of creating a new
158
+ * session. The path must be the child's own session file under its recorded
159
+ * artifact directory. Every other field keeps its fresh-delegation meaning,
160
+ * so permission/model/tool wiring has exactly one construction path.
161
+ */
162
+ reattachSessionPath?: string;
163
+ /**
164
+ * Optional wall-time cap for the child's OWN run budget (spec 2026-09-09,
165
+ * timeouts): forwarded as `maxWallTimeMs` so the existing AgentRunBudget
166
+ * wall-time gate enforces it mid-run. The launch also records
167
+ * `deadlineMs = Date.now() + timeoutMs` on the record for lazy observation.
168
+ */
169
+ timeoutMs?: number;
170
+ }
171
+ /** The workspace authority requested by a child. Paths are advisory claims,
172
+ * never a replacement for the path-permission or sandbox enforcement. */
173
+ export interface ChildWorkspaceRequest {
174
+ isolation: "shared-read" | "worktree";
175
+ ownedPaths: readonly string[];
176
+ /**
177
+ * The resolved isolation root a workspace owner prepared for this child
178
+ * (worktree isolation): absent on the raw request, present on what
179
+ * `prepare()` returns, and the cwd the child session runs in.
180
+ */
181
+ root?: string;
182
+ }
183
+ /**
184
+ * Lifecycle state of a worktree-isolated child's workspace, persisted on the
185
+ * record (spec 2026-09-09, "Workspace states and explicit recovery"). Absent
186
+ * means "active" -- legacy records predate the field and a live worktree is
187
+ * active by definition. Release outcomes write "released" / "retained-dirty" /
188
+ * "retained-failed"; observing a vanished root at resume writes "missing".
189
+ * Explicit recovery (`recoverWorkspace`) verifies and writes "active".
190
+ */
191
+ export type ChildWorkspaceState = "active" | "released" | "retained-dirty" | "retained-failed" | "missing";
192
+ /** Success payload of explicit workspace recovery (`recoverChildWorkspace`). */
193
+ export interface ChildWorkspaceRecoveryResult {
194
+ /** Always "active": the workspace was verified and reactivated. */
195
+ workspaceState: ChildWorkspaceState;
196
+ /** The verified worktree holds uncommitted or untracked work. */
197
+ dirty: boolean;
198
+ }
199
+ /**
200
+ * Real isolation and cleanup for a child's requested workspace authority (spec
201
+ * 2026-09-09, "Parallel work and ownership"): the workspace subsystem owns git;
202
+ * delegation only negotiates the request and refuses worktree isolation when no
203
+ * owner is available. `prepare()` runs only for `isolation: "worktree"` -- a
204
+ * shared-read delegation never touches an owner and never invokes git -- and
205
+ * the request it returns (with `root` set) is what `buildChildSession` receives.
206
+ */
207
+ /**
208
+ * Terminal outcome of releasing a child workspace (worktree). A kept tree is
209
+ * never destroyed silently: "dirty" means uncommitted/untracked child work
210
+ * was preserved; "failed" means the remove failed for another reason and the
211
+ * tree was left in place.
212
+ */
213
+ export type WorkspaceReleaseOutcome = {
214
+ removed: true;
215
+ } | {
216
+ removed: false;
217
+ kept: "dirty" | "failed";
218
+ dir: string;
219
+ error?: string;
220
+ };
221
+ export interface ChildWorkspaceOwner {
222
+ prepare(request: ChildWorkspaceRequest & {
223
+ sessionId: string;
224
+ }): Promise<ChildWorkspaceRequest>;
225
+ /**
226
+ * Release the child's workspace, reporting what happened instead of
227
+ * throwing. `options.force` is the caller's explicit escape hatch to
228
+ * force-remove a dirty tree; without it a dirty tree must be kept.
229
+ */
230
+ release(sessionId: string, options?: {
231
+ force?: boolean;
232
+ }): Promise<WorkspaceReleaseOutcome> | WorkspaceReleaseOutcome;
233
+ /**
234
+ * Read-only verification that a recorded worktree root is still this
235
+ * owner's worktree for the session in the CURRENT workspace: layout,
236
+ * administrative entry, and checked-out branch. Never creates, checks out,
237
+ * resets, or force-removes anything; a failed check throws with the check
238
+ * named. Optional: owners that cannot verify simply never support explicit
239
+ * recovery, and `recoverWorkspace` refuses rather than guessing.
240
+ */
241
+ verify?(sessionId: string, root: string): Promise<{
242
+ dirty: boolean;
243
+ }> | {
244
+ dirty: boolean;
245
+ };
48
246
  }
49
247
  export interface DelegationRuntimeOptions {
50
248
  resolveAgent: AgentDefinitionResolver;
@@ -56,9 +254,105 @@ export interface DelegationRuntimeOptions {
56
254
  getDelegationDepth: () => number;
57
255
  /** Delegation is refused once `getDelegationDepth() >= maxDelegationDepth` -- assigned by the runtime, not by the tool, so the bound applies to any future delegation entry point. */
58
256
  maxDelegationDepth: number;
257
+ /**
258
+ * Maximum simultaneously-active child runs this runtime admits (spec
259
+ * 2026-09-09, "Shared budgets", concurrency cap). Checked at admission --
260
+ * before any child session is built -- and refused with an actionable error
261
+ * naming the limit. An admitted run holds one slot until terminal settlement
262
+ * (completed/failed/interrupted), close, registry disposal, or launch
263
+ * failure. `undefined` (default) is unlimited.
264
+ */
265
+ maxConcurrentChildren?: number;
59
266
  /** Parent session directory. When supplied, child artifacts are rooted beneath it. */
60
267
  getParentSessionDir?: () => string;
268
+ /**
269
+ * Parent session id. When supplied, child-run records carry
270
+ * `parentSessionId`, tying the durable record (and every protocol payload
271
+ * derived from it) to the parent session's own identity.
272
+ */
273
+ getParentSessionId?: () => string;
61
274
  buildChildSession: (request: BuildChildSessionRequest) => Promise<ChildSessionHandle>;
275
+ childRunRegistry?: ChildRunRegistry;
276
+ /** Durable session owner. Records are appended to the parent session's existing log. */
277
+ persistChildRun?: (record: ChildRunRecord) => void;
278
+ /** Optional workspace owner. It is responsible for real isolation and cleanup. */
279
+ workspaceOwner?: ChildWorkspaceOwner;
280
+ }
281
+ /**
282
+ * Compact, derivable snapshot of the derived policy a child session was built
283
+ * with (spec 2026-09-09, "Derive, do not reconstruct"). Populated at child
284
+ * construction from the values actually used -- never re-derived by consumers.
285
+ * `capabilities` come from the delegation runtime's single admission projection
286
+ * (`resolveAdmittedDefinition`), so no surface ever re-classifies authority
287
+ * (ADR 0010). Persisted on `ChildRunRecord` and surfaced through status/wait
288
+ * payloads; legacy records without it load unchanged.
289
+ */
290
+ export interface ChildRunPolicySnapshot {
291
+ /** The child's tool allowlist, exactly as construction received it (ceiling-checked `definition.tools`). */
292
+ tools: string[];
293
+ /** The admitted capability set from the same admission projection that gated the launch. */
294
+ capabilities: string[];
295
+ /** The sandbox contract string the child was constructed under ("required" | "external" | "none"). */
296
+ sandbox: string;
297
+ /** The delegation depth bound in force for this child's own delegations. */
298
+ maxDelegationDepth: number;
299
+ /** The child's resolved model id (its definition's model, or the parent's current model). */
300
+ model?: string;
301
+ /** The child Agent's budget scope; children are built session-scoped so follow-ups continue one controller. */
302
+ budgetScope: "prompt" | "session";
303
+ /** Whether the child answers to the tree's shared aggregate ceiling (present only when explicitly configured at the root). */
304
+ aggregateBudget: boolean;
305
+ }
306
+ export interface ChildRunRecord {
307
+ handleId: string;
308
+ agentType: string;
309
+ sessionId?: string;
310
+ task?: string;
311
+ parentSessionId?: string;
312
+ artifactDir?: string;
313
+ /** The derived policy this child was built with, persisted so session readers describe the child without re-deriving it. Optional: legacy records predate the field. */
314
+ policy?: ChildRunPolicySnapshot;
315
+ /**
316
+ * True when the SDK's OS-containment supervisor marker check passed for the
317
+ * parent session (always the case under the "required" contract, which
318
+ * refuses construction without it). Absent on legacy records; false means
319
+ * the contract is "external"/"none" (or no supervisor marker was present)
320
+ * and the SDK already allowed the run.
321
+ */
322
+ sandboxEnforced?: boolean;
323
+ workspace?: ChildWorkspaceRequest;
324
+ /**
325
+ * Workspace lifecycle state for worktree-isolated records (see
326
+ * `ChildWorkspaceState`). Written by release outcomes, by resume-time
327
+ * observation of a vanished root ("missing"), and by explicit recovery
328
+ * ("active"). Absent -- on legacy records and shared-read runs -- means
329
+ * "active"; the field only ever appears for worktree isolation.
330
+ */
331
+ workspaceState?: ChildWorkspaceState;
332
+ depth?: number;
333
+ latestResult?: {
334
+ output: string;
335
+ outcome: ChildTurnOutcome;
336
+ };
337
+ status: "created" | "running" | "completed" | "failed" | "interrupted" | "closed";
338
+ updatedAt: number;
339
+ /**
340
+ * Attempt epochs (launch = attempt 1; resume opens a new one). Optional on
341
+ * the wire: legacy records predate the field and are synthesized on load --
342
+ * one attempt derived from the record's status/updatedAt -- so every
343
+ * in-memory record carries at least one.
344
+ */
345
+ attempts?: ChildRunAttempt[];
346
+ activeAttemptId?: string;
347
+ /** Caller-supplied spawn dedupe key; a restarted parent rebuilds the key->handle map from records. */
348
+ idempotencyKey?: string;
349
+ /** Wall-clock deadline recorded at launch (`Date.now() + timeoutMs`); observed lazily by status/list. */
350
+ deadlineMs?: number;
351
+ /** Explicit cancellation, recorded when the run is interrupted with a reason. */
352
+ cancelled?: {
353
+ reason: string;
354
+ at: number;
355
+ };
62
356
  }
63
357
  export interface DelegationResult {
64
358
  agentType: string;
@@ -66,6 +360,380 @@ export interface DelegationResult {
66
360
  output: string;
67
361
  /** Present for background work; pass this handle to retrieveDelegationResult. */
68
362
  handleId?: string;
363
+ /**
364
+ * Terminal outcome of the latest settled turn. Present on registry retrieval
365
+ * once any turn has settled; the foreground result of the initial run omits it.
366
+ */
367
+ outcome?: ChildTurnOutcome;
368
+ }
369
+ /**
370
+ * Non-blocking status snapshot of one child run (`agent/status`,
371
+ * `AgentSession.childRunStatus`). Built from the record/entry alone -- never by
372
+ * awaiting a turn -- so a caller can poll without blocking on the child.
373
+ */
374
+ export interface ChildRunStatus {
375
+ handleId: string;
376
+ agentType: string;
377
+ task: string;
378
+ status: ChildSessionStatus;
379
+ /** The active attempt's identity and its latest outcome, if any turn has settled (or a cancellation was recorded). */
380
+ attempt: {
381
+ id: string;
382
+ outcome?: ChildRunAttemptOutcome;
383
+ };
384
+ /** Total attempt epochs, including closed ones. */
385
+ attempts: number;
386
+ /** The latest settled turn, as persisted for retrieval. */
387
+ lastResult?: {
388
+ output: string;
389
+ outcome: ChildTurnOutcome;
390
+ };
391
+ /** Present when the run was interrupted with an explicit reason. */
392
+ cancelled?: {
393
+ reason: string;
394
+ at: number;
395
+ };
396
+ /** Wall-clock launch deadline (present when the spawn carried timeoutMs). */
397
+ deadlineMs?: number;
398
+ /** Snapshot of the child's own budget controller, when its handle exposes one. */
399
+ usage?: AgentRunBudgetUsage;
400
+ /**
401
+ * Cumulative token totals rolled up from the child's own session transcript
402
+ * (or its in-memory entries when no transcript exists), flattened from
403
+ * `ChildRunUsageTotals`. Present beside `cost` whenever a rollup is
404
+ * reachable; omitted -- never zero-filled -- when nothing is reachable.
405
+ */
406
+ tokens?: {
407
+ inputTokens: number;
408
+ outputTokens: number;
409
+ cacheReadTokens: number;
410
+ cacheWriteTokens: number;
411
+ totalTokens: number;
412
+ };
413
+ /** Provider-reported cost totals corresponding to `tokens`. Absent whenever `tokens` is. */
414
+ cost?: {
415
+ input: number;
416
+ output: number;
417
+ cacheRead: number;
418
+ cacheWrite: number;
419
+ total: number;
420
+ };
421
+ /** The run's negotiated workspace authority (isolation plus a prepared root, when a workspace owner provided one). */
422
+ workspace?: {
423
+ isolation: "shared-read" | "worktree";
424
+ root?: string;
425
+ };
426
+ /**
427
+ * Workspace lifecycle state (worktree-isolated runs only). Present whenever
428
+ * the workspace is worktree-isolated: the record's persisted state, or
429
+ * "active" while the entry is live and unretained.
430
+ */
431
+ workspaceState?: ChildWorkspaceState;
432
+ /** The child's per-run artifact directory, when the child is file-backed. */
433
+ artifactDir?: string;
434
+ /**
435
+ * The child's transcript path, resolved lazily from its artifact directory
436
+ * per SessionManager's `<timestamp>_<sessionId>.jsonl` naming. Absent when
437
+ * the child is in-memory or has not persisted a transcript yet; resolution
438
+ * never throws.
439
+ */
440
+ sessionFile?: string;
441
+ /** The parent session id the run belongs to, when the runtime supplies one. */
442
+ parentSessionId?: string;
443
+ /** The derived policy the child was built with; absent on legacy records and fixture handles that never carried one. */
444
+ policy?: ChildRunPolicySnapshot;
445
+ /** True when the OS-containment supervisor marker check passed for the parent session; absent on legacy records. */
446
+ sandboxEnforced?: boolean;
447
+ }
448
+ /** The registry's record of a handle's latest settled turn. */
449
+ type LatestTurnSettlement = {
450
+ outcome: "completed";
451
+ output: string;
452
+ } | {
453
+ outcome: "interrupted";
454
+ output: string;
455
+ } | {
456
+ outcome: "failed";
457
+ error: unknown;
458
+ };
459
+ interface BackgroundDelegation {
460
+ agentType: string;
461
+ task: string;
462
+ promise: Promise<DelegationResult>;
463
+ child?: ChildSessionHandle;
464
+ closed?: boolean;
465
+ /** The latest settled turn; `undefined` until the first settlement is recorded. */
466
+ latest?: LatestTurnSettlement;
467
+ /** The turn whose settlement has not been observed through retrieval yet, if any. */
468
+ pending?: Promise<unknown>;
469
+ /** Durable fields, persisted on every save so a restart can reattach the child session. */
470
+ artifactDir?: string;
471
+ workspace?: ChildWorkspaceRequest;
472
+ depth?: number;
473
+ /** Record linkage persisted with every save (policy snapshot, sandbox flag, parent session id). */
474
+ policy?: ChildRunPolicySnapshot;
475
+ sandboxEnforced?: boolean;
476
+ parentSessionId?: string;
477
+ /** Attempt epochs (spec 2026-09-09, "Child lifecycle"). `register()` supplies attempt 1 when the caller did not. */
478
+ attempts?: ChildRunAttempt[];
479
+ activeAttemptId?: string;
480
+ idempotencyKey?: string;
481
+ deadlineMs?: number;
482
+ cancelled?: {
483
+ reason: string;
484
+ at: number;
485
+ };
486
+ }
487
+ /** Default follow-up prompt for resuming an interrupted child run. */
488
+ export declare const RESUME_CHILD_PROMPT = "Resume the interrupted task and continue from the existing session.";
489
+ export declare class ChildRunRegistry {
490
+ private readonly entries;
491
+ private readonly workspaceClaims;
492
+ private readonly children;
493
+ /**
494
+ * Session ids whose workspace this registry must release on close/dispose
495
+ * (spec 2026-09-09, "Parallel work and ownership"): populated by
496
+ * `trackWorkspace()` when a worktree-isolated delegation is prepared, and
497
+ * drained exactly once per session id by `releaseWorkspaceOnce()`.
498
+ */
499
+ private readonly trackedWorkspaces;
500
+ /** Session ids whose workspace release has already started -- release runs once, never twice. */
501
+ private readonly releasedWorkspaces;
502
+ /** Last release outcome per session id, surfaced through `workspaceReleaseOutcome()`. */
503
+ private readonly workspaceReleaseOutcomes;
504
+ private workspaceOwner?;
505
+ private disposed;
506
+ private persist?;
507
+ private records;
508
+ /**
509
+ * Spawn dedupe keys -> handle ids (spec 2026-09-09, idempotent spawn). A
510
+ * second spawn with a known key returns the existing handle and never builds
511
+ * a second child. Populated at launch and rebuilt from persisted records on
512
+ * `restore()`, so a restarted parent dedupes too.
513
+ */
514
+ private readonly idempotencyKeys;
515
+ /**
516
+ * Handle ids currently holding a concurrency slot (spec 2026-09-09,
517
+ * "Shared budgets"). Admission takes one slot per child run BEFORE any child
518
+ * session is built; the slot is released on terminal settlement
519
+ * (completed/failed/interrupted), close, registry disposal, or launch
520
+ * failure. Keyed by handle id, so release is idempotent.
521
+ */
522
+ private readonly heldRunSlots;
523
+ /**
524
+ * The delegation runtime this registry runs under, attached by the session
525
+ * that owns it (sdk wiring) or by the first `runDelegation` call. Historical
526
+ * resume reattaches through the SAME `buildChildSession` seam a live
527
+ * delegation uses; without an attached runtime, historical records are still
528
+ * listed and their persisted output retrievable, but they cannot reattach.
529
+ */
530
+ private runtimeOptions?;
531
+ /**
532
+ * Last-computed usage totals per handle id, keyed by what makes them stale
533
+ * (the transcript file's size+mtime, or the in-memory entry count+last id).
534
+ * The transcript file itself stays the one source: on every read the key is
535
+ * re-derived and a mismatch recomputes from the file -- this cache never
536
+ * becomes a second transcript.
537
+ */
538
+ private readonly usageCache;
539
+ /** First attach wins: a registry is owned by one session's runtime. */
540
+ setRuntimeOptions(options: DelegationRuntimeOptions): void;
541
+ setPersistence(persist: (record: ChildRunRecord) => void): void;
542
+ /** Load validated historical records. This never constructs or starts a child. */
543
+ restore(records: readonly ChildRunRecord[]): void;
544
+ /** The handle a spawn dedupe key already maps to, if any. */
545
+ handleForIdempotencyKey(key: string): string | undefined;
546
+ /** True when `id` is known only as a persisted record -- no live entry in this process. */
547
+ isHistorical(id: string): boolean;
548
+ /**
549
+ * Resolve a historical record's child session file. Verified against
550
+ * SessionManager's naming (`<timestamp>_<sessionId>.jsonl` inside the
551
+ * per-child artifact directory, which IS the child's session dir): the
552
+ * timestamp prefix is not recorded, so the directory is scanned for the file
553
+ * whose name ends in `_<sessionId>.jsonl`. Returns the validated triple so
554
+ * the reattachment request carries checked values, not optional record fields.
555
+ */
556
+ private resolveHistoricalSession;
557
+ /**
558
+ * Reattach a persisted child run to its existing child session and continue
559
+ * it with one turn (restart reconstruction). The child session file recorded
560
+ * under the run's artifact directory is reopened through the same
561
+ * `buildChildSession` seam a live delegation uses (reattachment marker), and
562
+ * the run then behaves like any live entry: settlement is observed and
563
+ * persisted, and wait/retrieve/sendInput work on the same handle id.
564
+ *
565
+ * Never-file-backed (in-memory) children, records whose artifact directory or
566
+ * session file is gone, closed runs, and runs whose recorded worktree was
567
+ * released all refuse with an actionable error; nothing is reconstructed
568
+ * from nothing.
569
+ */
570
+ resumeHistorical(id: string, input?: string): Promise<ChildSessionStatus>;
571
+ /**
572
+ * Gate a worktree-isolated historical resume on the workspace's persisted
573
+ * state (spec 2026-09-09, "Workspace states and explicit recovery"). A
574
+ * vanished root classifies the record "missing" (persisted) and refuses; a
575
+ * retained (dirty/failed) root refuses, naming the persisted state and
576
+ * pointing at explicit recovery. Legacy records and recovered ("active")
577
+ * workspaces pass. Read-only: nothing is recreated, checked out, or reset.
578
+ */
579
+ private rejectUnresumableWorktree;
580
+ /**
581
+ * Explicitly verify and reactivate a retained child worktree (spec
582
+ * 2026-09-09, "Workspace states and explicit recovery"). Read-only
583
+ * inspection only -- the workspace owner's verification reads the
584
+ * administrative entry and the checked-out branch and never creates,
585
+ * checks out, resets, or force-removes anything -- and on success the
586
+ * record's workspace state becomes "active" (persisted) so the child can be
587
+ * resumed in the SAME worktree. Automatic recreation stays out of scope by
588
+ * design: every failed check refuses with an actionable error naming the
589
+ * failed check, and the workspace state stays unverified.
590
+ */
591
+ recoverWorkspace(id: string): Promise<ChildWorkspaceRecoveryResult>;
592
+ /**
593
+ * The owner consulted when a tracked child's lifecycle ends. Optional:
594
+ * without one, close/dispose still clean claims but release nothing.
595
+ */
596
+ setWorkspaceOwner(owner: ChildWorkspaceOwner | undefined): void;
597
+ /** Record that a child session's workspace (worktree) must be released when its lifecycle ends. */
598
+ trackWorkspace(sessionId: string): void;
599
+ /**
600
+ * Release a tracked child's workspace through the owner, once per session
601
+ * id. Best effort: a missing owner is tolerated and an owner failure never
602
+ * propagates -- cleanup must never break close or dispose. The outcome is
603
+ * stored per session id (`workspaceReleaseOutcome()`), and a kept tree is
604
+ * warned about loudly so silent data loss cannot hide behind best-effort
605
+ * cleanup.
606
+ */
607
+ private releaseWorkspaceOnce;
608
+ /**
609
+ * Classify a finished release on the record (spec 2026-09-09, "Workspace
610
+ * states and explicit recovery"): removed -> "released", kept dirty ->
611
+ * "retained-dirty", kept failed -> "retained-failed". Only worktree-isolated
612
+ * records carry the state. The classified record persists immediately -- even
613
+ * though release is fire-and-forget -- so a restarted parent sees the
614
+ * classification and can refuse or recover accordingly.
615
+ */
616
+ private recordWorkspaceState;
617
+ /** The stored outcome of this session id's workspace release, if it has run. */
618
+ workspaceReleaseOutcome(sessionId: string): WorkspaceReleaseOutcome | undefined;
619
+ /** Awaitable variant for the delegation failure path, which must release before the throw surfaces. */
620
+ releaseWorkspaceNow(sessionId: string): Promise<void>;
621
+ releaseWorkspace(sessionId: string): void;
622
+ activeWorkspaceClaims(): string[];
623
+ claimWorkspace(sessionId: string, paths: string[]): void;
624
+ private save;
625
+ /**
626
+ * Record a turn settlement from the child handle's own report, falling back to
627
+ * the settlement value for handles that did not report. The latest settlement
628
+ * wins; retrieval serves it instead of the stored first-turn promise.
629
+ */
630
+ private recordCompletion;
631
+ private recordFailure;
632
+ /**
633
+ * Stamp the active attempt with the settled turn's outcome. A cancellation
634
+ * recorded on the entry wins for an interrupted settlement: the attempt
635
+ * stays `cancelled` instead of downgrading to plain `interrupted`. Attempt
636
+ * usage snapshots from the child's own controller where its handle exposes
637
+ * one; handles without a controller leave usage unset. `tokensAtEnd`
638
+ * snapshots the run-level token/cost rollup at settlement time (a
639
+ * cumulative-at-end snapshot of the whole transcript -- see
640
+ * `ChildRunAttempt`); when nothing is reachable it stays unset.
641
+ */
642
+ private stampAttemptSettlement;
643
+ /** Persist the settlement's status. A closed run's terminal status is never overwritten by late settlement. */
644
+ private persistSettlement;
645
+ assertOpen(): void;
646
+ /** The configured child-run concurrency limit, if any. */
647
+ private concurrencyLimit;
648
+ /**
649
+ * Concurrency admission (spec 2026-09-09, "Shared budgets"): refuse with an
650
+ * actionable error naming the limit BEFORE any child session is built when
651
+ * every slot is occupied. An admitted run holds one slot until terminal
652
+ * settlement, close, dispose, or a launch failure releases it.
653
+ */
654
+ admitChildRun(handleId: string): void;
655
+ /** Release a run's concurrency slot. Idempotent. */
656
+ releaseChildRunSlot(handleId: string): void;
657
+ own(child: ChildSessionHandle): void;
658
+ release(child: ChildSessionHandle): void;
659
+ register(id: string, entry: BackgroundDelegation): void;
660
+ retrieve(id: string, expected?: string): Promise<DelegationResult>;
661
+ private latestDelegationResult;
662
+ /**
663
+ * One entry per child run -- live entries first, then historical records --
664
+ * each as `{handleId, agentType, task, status, attemptCount}`. Backward
665
+ * compatible: fields were only ever added. Observing the list lazily
666
+ * interrupts a live running child whose wall-clock deadline has passed.
667
+ */
668
+ list(): {
669
+ handleId: string;
670
+ agentType: string;
671
+ task: string;
672
+ status: ChildSessionStatus;
673
+ attemptCount: number;
674
+ }[];
675
+ /**
676
+ * Non-blocking status snapshot for one handle (spec 2026-09-09, pollable
677
+ * status): built from the live entry or the persisted record alone, never by
678
+ * awaiting a turn. Unknown ids still error. Observing the status lazily
679
+ * interrupts a live running child whose wall-clock deadline has passed, so a
680
+ * timed-out run is reported (and stopped) at observation time.
681
+ */
682
+ status(id: string): ChildRunStatus;
683
+ /**
684
+ * The run's token/cost totals, rolled up on demand from the child's OWN
685
+ * session transcript (the session-file reading seam) -- or from the handle's
686
+ * in-memory session entries when no transcript file exists. Reads lazily and
687
+ * caches only the last-computed totals, keyed by transcript size/mtime or
688
+ * entry count, so the cache can never become a second transcript.
689
+ * `undefined` -- never zero-filled, never a throw -- when nothing is
690
+ * reachable: an in-memory child without a reachable transcript, or a
691
+ * historical record whose transcript is gone. Unknown ids error like
692
+ * `status`.
693
+ */
694
+ usageTotals(id: string): ChildRunUsageTotals | undefined;
695
+ /**
696
+ * One rollup read for both live entries and historical records: a
697
+ * resolvable transcript file wins (the persisted transcript is the source of
698
+ * truth, including after restart); the handle's in-memory session entries
699
+ * cover an in-memory child whose transcript was never written.
700
+ */
701
+ private usageTotalsFor;
702
+ /** The status payload's flattened view of the rollup, omitted when unreachable. */
703
+ private static usageSummaryOf;
704
+ private statusFromEntry;
705
+ private statusFromRecord;
706
+ /**
707
+ * Lazy deadline observation (spec 2026-09-09, timeouts): a live RUNNING child
708
+ * past its recorded wall-clock deadline is interrupted at observation time.
709
+ * The interrupt carries no reason -- a wall-time timeout is not a user
710
+ * cancellation -- so the attempt settles `interrupted`, and the child's own
711
+ * budget gate names "wall-time" in the settlement error path when the run's
712
+ * turn was refused for time. Historical records have no live child to
713
+ * interrupt and are left untouched.
714
+ */
715
+ private observeDeadlines;
716
+ private child;
717
+ wait(id: string): Promise<DelegationResult>;
718
+ sendInput(id: string, input: string): Promise<void>;
719
+ /**
720
+ * Interrupt a live child. An optional reason turns the interrupt into an
721
+ * explicit cancellation: `{reason, at}` is persisted on the record
722
+ * immediately and the active attempt is marked `cancelled`; without a
723
+ * reason the attempt settles plain `interrupted` at the turn's settlement.
724
+ */
725
+ interrupt(id: string, reason?: string): void;
726
+ /**
727
+ * Close a live run's active attempt with its latest settled outcome and open
728
+ * a new one for the resuming turn (spec 2026-09-09, "Child lifecycle"):
729
+ * `AgentSession.resumeChildRun` calls this on the live path before
730
+ * `sendInput` so a resume is a distinct attempt epoch, while ordinary
731
+ * follow-ups on a live run stay inside the active attempt.
732
+ */
733
+ beginResumeAttempt(id: string): void;
734
+ close(id: string): void;
735
+ /** Stop tracking handles and release any children and workspaces still owned by this registry. */
736
+ dispose(): void;
69
737
  }
70
738
  /**
71
739
  * Run one delegation to completion. Throws rather than returning a failure value,
@@ -87,9 +755,22 @@ export interface DelegationResult {
87
755
  * or `buildChildSession`. `buildChildSession` receives the child's depth (parent + 1)
88
756
  * so the caller can record it on the child's own session header.
89
757
  */
758
+ /**
759
+ * Whether two resolved paths denote the same directory or either contains the
760
+ * other. Comparison is separator-correct: forward-slash prefix matching
761
+ * silently never matches on platforms whose resolve() produces backslashes.
762
+ */
763
+ export declare function claimPathsOverlap(a: string, b: string): boolean;
90
764
  export declare function runDelegation(options: DelegationRuntimeOptions, agentType: string, task: string, request?: {
91
765
  background?: boolean;
766
+ workspace?: ChildWorkspaceRequest;
767
+ handleId?: string;
768
+ /** Spawn dedupe key (spec 2026-09-09, idempotent spawn): a known key returns the EXISTING handle without building a second child. */
769
+ idempotencyKey?: string;
770
+ /** Wall-time cap for the child's own run budget; also recorded as the record's deadlineMs for lazy observation. */
771
+ timeoutMs?: number;
92
772
  }): Promise<DelegationResult>;
93
773
  /** Retrieve a background delegation. Running children are awaited; unknown handles fail explicitly. */
94
774
  export declare function retrieveDelegationResult(options: DelegationRuntimeOptions, handleId: string, expectedAgentType?: string): Promise<DelegationResult>;
775
+ export {};
95
776
  //# sourceMappingURL=runtime.d.ts.map