@yaag/runtime 0.10.0 → 0.12.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (59) hide show
  1. package/package.json +1 -1
  2. package/src/agent/agent-compaction.ts +80 -0
  3. package/src/agent/agent-usage.ts +11 -0
  4. package/src/agent/agent.ts +95 -3
  5. package/src/agent/define-agent.ts +7 -5
  6. package/src/agent/fork.ts +74 -0
  7. package/src/agent/index.ts +1 -0
  8. package/src/agent/spawn-open.ts +249 -0
  9. package/src/agent/spawn-request.ts +12 -1
  10. package/src/agent/spawn.ts +25 -197
  11. package/src/ask/ask-exchange.ts +2 -8
  12. package/src/cassette/cassette-replay.ts +33 -1
  13. package/src/cassette/cassette-schema.ts +20 -0
  14. package/src/cassette/cassette.ts +69 -6
  15. package/src/cassette/index.ts +1 -0
  16. package/src/cassette/recording-transport.ts +13 -0
  17. package/src/cassette/replay-divergence.ts +51 -2
  18. package/src/cassette/replay-transport.ts +22 -1
  19. package/src/cassette/resume-transport.ts +27 -2
  20. package/src/catalog/agent-describe-fixture.ts +121 -0
  21. package/src/catalog/agent-describe.ts +210 -0
  22. package/src/catalog/catalog-entry.ts +39 -0
  23. package/src/catalog/catalog-fixture.ts +87 -0
  24. package/src/catalog/catalog-match.ts +77 -0
  25. package/src/catalog/catalog-result.ts +69 -0
  26. package/src/catalog/index.ts +57 -0
  27. package/src/catalog/load-catalog.ts +74 -0
  28. package/src/catalog/program-scan.ts +64 -0
  29. package/src/catalog/registry-paths.ts +26 -0
  30. package/src/catalog/registry-reader.ts +115 -0
  31. package/src/catalog/registry-schema.ts +119 -0
  32. package/src/config/config-paths.ts +14 -7
  33. package/src/config/index.ts +1 -0
  34. package/src/contract/agent-report.ts +42 -0
  35. package/src/contract/error-codes.ts +65 -0
  36. package/src/contract/handle.ts +132 -0
  37. package/src/contract/index.ts +34 -0
  38. package/src/contract/model-spec.ts +81 -0
  39. package/src/contract/spawn-options.ts +127 -0
  40. package/src/error-factories.ts +70 -0
  41. package/src/errors.ts +22 -114
  42. package/src/events.ts +26 -1
  43. package/src/index.ts +49 -0
  44. package/src/model/model-resolution.ts +19 -71
  45. package/src/model/model-swap.ts +1 -1
  46. package/src/model/resolution-loop.ts +1 -1
  47. package/src/model/thinking-level.ts +5 -5
  48. package/src/public-api.ts +28 -0
  49. package/src/run/run-context.ts +4 -2
  50. package/src/summary/index.ts +1 -0
  51. package/src/summary/summary-agent.ts +38 -0
  52. package/src/summary/summary.ts +20 -0
  53. package/src/transport/fake-transport.ts +35 -1
  54. package/src/transport/index.ts +9 -1
  55. package/src/transport/live-transport.ts +9 -0
  56. package/src/transport/pi-state.ts +53 -10
  57. package/src/transport/transport.ts +54 -9
  58. package/src/transport/worktree-transport.ts +39 -6
  59. package/src/types.ts +16 -201
package/src/index.ts CHANGED
@@ -5,6 +5,7 @@ export type {
5
5
  CassetteAgent,
6
6
  CassetteArtifact,
7
7
  CassetteAsk,
8
+ CassetteCompaction,
8
9
  CassetteGit,
9
10
  CassetteRun,
10
11
  CassetteSink,
@@ -18,6 +19,49 @@ export {
18
19
  replayTransport,
19
20
  resumeTransport,
20
21
  } from "./cassette/index.ts";
22
+ export type {
23
+ AgentDeclaredMetadata,
24
+ AgentDefinitionEntry,
25
+ AgentDescribeFinding,
26
+ AgentDescribeFindingCode,
27
+ AgentDescribeFindingResult,
28
+ AgentDescribeRequest,
29
+ AgentDescribeResult,
30
+ AgentDescribeTranscriptEntry,
31
+ CatalogDiagnostic,
32
+ CatalogKind,
33
+ CatalogLayer,
34
+ CatalogQuery,
35
+ CatalogRequest,
36
+ CatalogResult,
37
+ CatalogRow,
38
+ CatalogSource,
39
+ DescribedAgent,
40
+ NameDeviation,
41
+ ParsedRegistryFile,
42
+ RegistryDocument,
43
+ RegistryLayerRequest,
44
+ } from "./catalog/index.ts";
45
+ export {
46
+ AGENT_DESCRIBE_FINDING_CODES,
47
+ AGENT_DESCRIBE_TRANSCRIPT,
48
+ agentDescribeArgv,
49
+ CATALOG_FIXTURE,
50
+ describedAgent,
51
+ encodeAgentDescribe,
52
+ filterCatalog,
53
+ globalRegistryPath,
54
+ loadCatalog,
55
+ matchesPattern,
56
+ parseAgentDescribe,
57
+ parseRegistryFile,
58
+ projectRegistryPath,
59
+ REGISTRY_FILE_NAME,
60
+ readRegistryDocument,
61
+ readRegistryLayer,
62
+ scanPrograms,
63
+ transcriptFor,
64
+ } from "./catalog/index.ts";
21
65
  export type {
22
66
  ConfigEnvironment,
23
67
  ConfigExtension,
@@ -79,6 +123,7 @@ export type {
79
123
  AgentInfo,
80
124
  AgentState,
81
125
  AskingAgentInfo,
126
+ CompactionInfo,
82
127
  EndedRunSummary,
83
128
  ExitedAgentInfo,
84
129
  IdleAgentInfo,
@@ -96,6 +141,9 @@ export type {
96
141
  AskMarker,
97
142
  AskMarkerContext,
98
143
  AskPlayback,
144
+ CompactionMarker,
145
+ CompactionPlayback,
146
+ CompactionResult,
99
147
  DiscoveredSkill,
100
148
  Frame,
101
149
  ReapPath,
@@ -110,6 +158,7 @@ export type {
110
158
  export { readSystemPromptSidecar, reap, worktreeTransport } from "./transport/index.ts";
111
159
  export type {
112
160
  AskOptions,
161
+ ForkOptions,
113
162
  Handle,
114
163
  ResolvedSpawnOptions,
115
164
  SpawnOptions,
@@ -1,76 +1,24 @@
1
+ import type {
2
+ ModelError,
3
+ ModelResolver,
4
+ ModelSelection,
5
+ ModelSpec,
6
+ ThinkingLevel,
7
+ ThinkingResolver,
8
+ ThinkingSpec,
9
+ } from "../contract/index.ts";
1
10
  import { parseModelSuffix } from "./model-suffix.ts";
2
- import { isThinkingLevel, type ThinkingLevel } from "./thinking-level.ts";
11
+ import { isThinkingLevel } from "./thinking-level.ts";
3
12
 
4
- /**
5
- * Why one model candidate was rejected by pi (ADR-0037).
6
- *
7
- * `not_found`: the pattern matched no model, or pi refused the live swap.
8
- * `auth`: the provider refused the credentials.
9
- * `rate_limited`: the provider stayed rate-limited after pi's own retries.
10
- *
11
- * These three classes are the only triggers of Model Resolution. A different
12
- * transport or turn failure stays an ordinary failure and starts no new attempt.
13
- */
14
- export type ModelErrorReason = "not_found" | "auth" | "rate_limited";
15
-
16
- /**
17
- * One failed Model Resolution attempt, handed back to the caller's resolver.
18
- *
19
- * yaag gives the full history to each resolver call, oldest attempt first. The
20
- * first call gets an empty list (ADR-0037).
21
- */
22
- export interface ModelError {
23
- readonly reason: ModelErrorReason;
24
- /** The model pattern that failed, after inline-suffix stripping. */
25
- readonly failedModel: string;
26
- /** 0-based index of the attempt that produced this error. */
27
- readonly attempt: number;
28
- }
29
-
30
- /**
31
- * Picks the next model candidate, or `undefined` to give up (ADR-0037).
32
- *
33
- * When the resolver gives up, the spawn or the Ask fails with
34
- * `MODEL_RESOLUTION_FAILED`, which carries the full error history. yaag also
35
- * refuses a candidate that already failed with `not_found` or `auth` in the
36
- * same loop, so a resolver cannot loop forever. The resolver must be pure and
37
- * synchronous.
38
- */
39
- export type ModelResolver = (errors: readonly ModelError[]) => string | undefined;
40
-
41
- /**
42
- * Every accepted `model` form: one pattern, an ordered list, or a resolver.
43
- *
44
- * An array is the resolver that reads the candidate at the attempt index, and
45
- * gives `undefined` past the end. One pattern is the one-element list. So the
46
- * termination rule of `ModelResolver` covers every form (ADR-0037).
47
- */
48
- export type ModelSpec = string | readonly string[] | ModelResolver;
49
-
50
- /**
51
- * Picks the thinking level for a settled model, or `undefined` for pi's default.
52
- *
53
- * `undefined` means "no thinking preference". It is not a failure, and it does
54
- * not stop the attempt (ADR-0037).
55
- */
56
- export type ThinkingResolver = (
57
- selectedModel: string,
58
- errors: readonly ModelError[],
59
- ) => ThinkingLevel | undefined;
60
-
61
- /**
62
- * Every accepted `thinking` form: one level or a resolver.
63
- *
64
- * An inline suffix on the resolved model pattern wins over this property
65
- * (ADR-0037).
66
- */
67
- export type ThinkingSpec = ThinkingLevel | ThinkingResolver;
68
-
69
- /** One attempt's settled selection; `model: undefined` inherits pi's default model. */
70
- export interface ModelSelection {
71
- readonly model: string | undefined;
72
- readonly thinking: ThinkingLevel | undefined;
73
- }
13
+ export type {
14
+ ModelError,
15
+ ModelErrorReason,
16
+ ModelResolver,
17
+ ModelSelection,
18
+ ModelSpec,
19
+ ThinkingResolver,
20
+ ThinkingSpec,
21
+ } from "../contract/index.ts";
74
22
 
75
23
  /** The canonical shape the spawn loop consumes, whatever form the caller wrote. */
76
24
  export interface ModelResolution {
@@ -1,4 +1,4 @@
1
- import { agentError } from "../errors.ts";
1
+ import { agentError } from "../error-factories.ts";
2
2
  import type { CommandResponse, Frame } from "../transport/index.ts";
3
3
  import { matchAvailableModel, readAvailableModel, readAvailableModels } from "./model-match.ts";
4
4
  import type { ModelSelection } from "./model-resolution.ts";
@@ -1,4 +1,4 @@
1
- import { modelResolutionError } from "../errors.ts";
1
+ import { modelResolutionError } from "../error-factories.ts";
2
2
  import { ModelErrorHistory } from "./model-error-history.ts";
3
3
  import { classifyAskFailure, classifyModelFailure } from "./model-failure.ts";
4
4
  import type { ModelFallbackSink } from "./model-fallback.ts";
@@ -1,10 +1,10 @@
1
1
  /**
2
- * pi's supported thinking levels.
3
- *
4
- * Lives in its own leaf module so both `types.ts` and the Model Resolution
5
- * modules can depend on it without forming an import cycle.
2
+ * The value side of pi's thinking levels. The type itself lives in
3
+ * `contract/model-spec.ts` (ADR-0045) and is re-exported here.
6
4
  */
7
- export type ThinkingLevel = "off" | "minimal" | "low" | "medium" | "high" | "xhigh" | "max";
5
+ import type { ThinkingLevel } from "../contract/index.ts";
6
+
7
+ export type { ThinkingLevel } from "../contract/index.ts";
8
8
 
9
9
  /**
10
10
  * The closed level list, authored as a total record so that adding a level to
@@ -0,0 +1,28 @@
1
+ /**
2
+ * The author surface of `@yaag/runtime` (ADR-0045).
3
+ *
4
+ * An Orchestration Program imports exactly `@yaag/runtime` and `typebox`
5
+ * (ADR-0033). This file states the subset a program author may use, and the
6
+ * declaration tree a workspace gets is emitted from it alone.
7
+ *
8
+ * The imports go past the directory indexes on purpose: a directory index
9
+ * states the runtime API, which holds `executeRun`, `Agent`, or `promptGist`
10
+ * as well. This file must not pull those into the emitted tree.
11
+ */
12
+
13
+ export type { AgentConfig, AgentDefinition } from "./agent/define-agent.ts";
14
+ export { defineAgent } from "./agent/define-agent.ts";
15
+ export type {
16
+ AskOptions,
17
+ Handle,
18
+ SpawnOptions,
19
+ SpawnOverrides,
20
+ StructuredAskOptions,
21
+ ThinkingLevel,
22
+ } from "./contract/index.ts";
23
+ export type { YaagErrorCode } from "./errors.ts";
24
+ export { isYaagError, YaagError } from "./errors.ts";
25
+ export { prompt } from "./prompt/prompt.ts";
26
+ export type { OrchestrationProgram, ProgramDefinition } from "./run/define-run.ts";
27
+ export { defineRun } from "./run/define-run.ts";
28
+ export type { RunContext } from "./run/run-context.ts";
@@ -1,5 +1,7 @@
1
- import type { AgentDefinition } from "../agent/index.ts";
2
- import type { Handle, SpawnOptions, SpawnOverrides } from "../types.ts";
1
+ // `../agent/define-agent.ts` is a deep import on purpose: the author
2
+ // declaration tree must not pull the `agent/` barrel (ADR-0045).
3
+ import type { AgentDefinition } from "../agent/define-agent.ts";
4
+ import type { Handle, SpawnOptions, SpawnOverrides } from "../contract/index.ts";
3
5
 
4
6
  /** What an Orchestration Program is handed. */
5
7
  export interface RunContext<Args = unknown> {
@@ -16,6 +16,7 @@ export type {
16
16
  AgentInfo,
17
17
  AgentState,
18
18
  AskingAgentInfo,
19
+ CompactionInfo,
19
20
  ExitedAgentInfo,
20
21
  IdleAgentInfo,
21
22
  ModelFallbackInfo,
@@ -7,6 +7,15 @@ export type { AgentActivity, SpawnOrigin } from "../events.ts";
7
7
  export type { ModelFallbackInfo } from "./summary-fallbacks.ts";
8
8
  export type { NodeInfo } from "./summary-nodes.ts";
9
9
 
10
+ /** What one compaction of an Agent's context reported (ADR-0043). */
11
+ export interface CompactionInfo {
12
+ readonly tokensBefore: number | null;
13
+ readonly tokensAfter: number | null;
14
+ /** The summary call's own cost, already included in `agent_exit` accounting. */
15
+ readonly cost: number | null;
16
+ readonly at: number | null;
17
+ }
18
+
10
19
  /** The observer-facing lifecycle state of an Agent. */
11
20
  export type AgentState = "idle" | "asking" | "exited";
12
21
 
@@ -34,6 +43,10 @@ interface AgentInfoBase {
34
43
  /** Timestamp ordering only cumulative live accounting, never lifecycle state. */
35
44
  readonly usageUpdatedAt: number | null;
36
45
  readonly askStartedAt: number | null;
46
+ /** Compactions of this Agent's context so far (ADR-0043). */
47
+ readonly compactions: number;
48
+ /** What the newest compaction reported, or null when the Agent compacted none. */
49
+ readonly lastCompaction: CompactionInfo | null;
37
50
  /** This Agent's bounded Nested Node table, in first-seen order (spec §3). */
38
51
  readonly nodes: readonly NodeInfo[];
39
52
  /** Exited Nested Nodes dropped to keep the table bounded. */
@@ -103,6 +116,8 @@ export function placeholderAgent(): IdleAgentInfo {
103
116
  sessionFile: null,
104
117
  parent: null,
105
118
  origin: "spawn",
119
+ compactions: 0,
120
+ lastCompaction: null,
106
121
  state: "idle",
107
122
  askIndex: null,
108
123
  promptGist: null,
@@ -264,6 +279,29 @@ export function setUsage(
264
279
  return { ...agent, tokens: observation.tokens, cost: observation.cost, usageUpdatedAt: at };
265
280
  }
266
281
 
282
+ /**
283
+ * Counts one compaction and keeps what it reported.
284
+ *
285
+ * It folds no cost: the summary call's spend reaches the Summary through
286
+ * `agent_usage`, and `agent_exit` stays authoritative (ADR-0043). A terminal
287
+ * Agent still counts a late compaction, because the count is a fact about the
288
+ * conversation rather than a lifecycle state.
289
+ */
290
+ export function compactAgent(
291
+ current: AgentRecord | undefined,
292
+ observation: CompactionInfo,
293
+ at: number | null,
294
+ ): AgentRecord {
295
+ const agent = current ?? placeholderAgent();
296
+ const stale =
297
+ at !== null && agent.lastCompaction?.at !== null && at < (agent.lastCompaction?.at ?? at);
298
+ return {
299
+ ...agent,
300
+ compactions: agent.compactions + 1,
301
+ lastCompaction: stale ? agent.lastCompaction : { ...observation, at },
302
+ };
303
+ }
304
+
267
305
  /**
268
306
  * Folds authoritative shutdown accounting into the terminal Agent state.
269
307
  *
@@ -3,6 +3,7 @@ import type { TokenBreakdown } from "../transport/index.ts";
3
3
  import type { AgentInfo } from "./summary-agent.ts";
4
4
  import {
5
5
  type AgentRecord,
6
+ compactAgent,
6
7
  endAsk,
7
8
  exitAgent,
8
9
  placeholderAgent,
@@ -22,6 +23,7 @@ export type {
22
23
  AgentInfo,
23
24
  AgentState,
24
25
  AskingAgentInfo,
26
+ CompactionInfo,
25
27
  ExitedAgentInfo,
26
28
  IdleAgentInfo,
27
29
  ModelFallbackInfo,
@@ -51,6 +53,8 @@ interface RunSummaryBase {
51
53
  readonly worstFrameGapMs: number;
52
54
  /** Run-wide Model Resolution fallbacks, pruned per-Agent entries included. */
53
55
  readonly modelFallbacks: number;
56
+ /** Compactions across every Agent of this Run (ADR-0043). */
57
+ readonly compactions: number;
54
58
  }
55
59
 
56
60
  /** A Run that has not settled; it has neither outcome nor compatibility result. */
@@ -109,6 +113,7 @@ export function initialSummary(): RunningRunSummary {
109
113
  durationMs: 0,
110
114
  worstFrameGapMs: 0,
111
115
  modelFallbacks: 0,
116
+ compactions: 0,
112
117
  ok: null,
113
118
  };
114
119
  }
@@ -160,6 +165,21 @@ export function applyEvent(
160
165
  event.agent,
161
166
  applyAgentModel(summary.agents[event.agent] ?? placeholderAgent(), event),
162
167
  );
168
+ case "agent_compaction":
169
+ return withAgent(
170
+ { ...summary, compactions: summary.compactions + 1 },
171
+ event.agent,
172
+ compactAgent(
173
+ summary.agents[event.agent],
174
+ {
175
+ tokensBefore: event.tokensBefore,
176
+ tokensAfter: event.tokensAfter,
177
+ cost: event.cost,
178
+ at,
179
+ },
180
+ at,
181
+ ),
182
+ );
163
183
  case "agent_usage":
164
184
  return withAgent(summary, event.agent, setUsage(summary.agents[event.agent], event, at));
165
185
  case "ask_end":
@@ -6,7 +6,13 @@ import {
6
6
  import type { AvailableModel } from "../model/index.ts";
7
7
  import { FrameQueue } from "./frame-queue.ts";
8
8
  import { parseFrame } from "./jsonl.ts";
9
- import type { AgentStats, AgentTransport, AskMarker, Frame } from "./transport.ts";
9
+ import type {
10
+ AgentStats,
11
+ AgentTransport,
12
+ AskMarker,
13
+ CompactionMarker,
14
+ Frame,
15
+ } from "./transport.ts";
10
16
 
11
17
  /**
12
18
  * Scripted frame playback for one prompt sent through a FakeTransport.
@@ -50,6 +56,10 @@ export interface FakeTransportOptions extends FakePromptScript {
50
56
  readonly steerError?: string;
51
57
  /** Makes an abort RPC response fail without embedding a limit decision in playback. */
52
58
  readonly abortError?: string;
59
+ /** Payload of a `compact` command response; omission answers a bare success. */
60
+ readonly compaction?: Record<string, unknown>;
61
+ /** Makes a `compact` command response fail, as pi does when it cannot summarize. */
62
+ readonly compactError?: string;
53
63
  /** Makes the private report_result schema command fail. */
54
64
  readonly schemaCommandError?: string;
55
65
  /** The snapshot answered to `get_available_models`; defaults to this fake's own model. */
@@ -87,6 +97,7 @@ export class FakeTransport implements AgentTransport {
87
97
  /** Everything the runtime wrote, in order. */
88
98
  readonly sent: Frame[] = [];
89
99
  readonly asks: AskMarker[] = [];
100
+ readonly compactions: CompactionMarker[] = [];
90
101
  readonly #queue = new FrameQueue();
91
102
  readonly #options: FakeTransportOptions;
92
103
  #closed = false;
@@ -113,6 +124,7 @@ export class FakeTransport implements AgentTransport {
113
124
  if (frame.type === "abort") void this.#answerAbort(frame);
114
125
  if (frame.type === "get_last_assistant_text") this.#answerLastText(frame);
115
126
  if (frame.type === "get_state") this.#answerState(frame);
127
+ if (frame.type === "compact") this.#answerCompact(frame);
116
128
  if (frame.type === "get_available_models") this.#answerAvailableModels(frame);
117
129
  if (frame.type === "set_model") this.#answerSetModel(frame);
118
130
  if (frame.type === "set_thinking_level")
@@ -133,6 +145,15 @@ export class FakeTransport implements AgentTransport {
133
145
  // This live test transport does not persist Ask outcomes.
134
146
  }
135
147
 
148
+ beginCompaction(marker: CompactionMarker): undefined {
149
+ this.compactions.push(marker);
150
+ return undefined;
151
+ }
152
+
153
+ finishCompaction(): void {
154
+ // This live test transport does not persist compaction outcomes.
155
+ }
156
+
136
157
  /** True once the runtime shut this Agent down. */
137
158
  get closed(): boolean {
138
159
  return this.#closed;
@@ -295,6 +316,19 @@ export class FakeTransport implements AgentTransport {
295
316
  });
296
317
  }
297
318
 
319
+ #answerCompact(frame: Frame): void {
320
+ const error = this.#options.compactError;
321
+ this.#queue.push({
322
+ type: "response",
323
+ command: "compact",
324
+ id: frame.id,
325
+ success: error === undefined,
326
+ ...(error === undefined
327
+ ? { data: this.#options.compaction ?? { summary: "summary" } }
328
+ : { error }),
329
+ });
330
+ }
331
+
298
332
  #answerState(frame: Frame): void {
299
333
  if (this.#options.stateSilent === true) return;
300
334
  this.#queue.push({
@@ -17,7 +17,12 @@ export { FrameGapTracker } from "./frame-gap.ts";
17
17
  export { FrameQueue } from "./frame-queue.ts";
18
18
  export { decodeFrames } from "./jsonl.ts";
19
19
  export { liveTransport } from "./live-transport.ts";
20
- export { type AgentProgress, piCommand, readAgentProgress } from "./pi-state.ts";
20
+ export {
21
+ type AgentProgress,
22
+ piCommand,
23
+ readAgentProgress,
24
+ readCompaction,
25
+ } from "./pi-state.ts";
21
26
  export { type ReapPath, type ReapTarget, reap } from "./reap.ts";
22
27
  export { type DiscoveredSkill, liveSkillProbe, type SkillProbeFactory } from "./skill-probe.ts";
23
28
  export { skillRestrictionTransport } from "./skill-restriction-transport.ts";
@@ -34,6 +39,9 @@ export type {
34
39
  AskMarker,
35
40
  AskMarkerContext,
36
41
  AskPlayback,
42
+ CompactionMarker,
43
+ CompactionPlayback,
44
+ CompactionResult,
37
45
  Frame,
38
46
  OpenOptions,
39
47
  TokenBreakdown,
@@ -140,6 +140,15 @@ class LiveTransport implements AgentTransport {
140
140
  // Live transport has no Cassette outcome to complete.
141
141
  }
142
142
 
143
+ beginCompaction(): undefined {
144
+ // Nothing to do live; a recording implementation groups frames by this.
145
+ return undefined;
146
+ }
147
+
148
+ finishCompaction(): void {
149
+ // Live transport has no Cassette compaction to complete.
150
+ }
151
+
143
152
  close(): Promise<AgentStats> {
144
153
  this.#closing ??= this.#shutdown();
145
154
  return this.#closing;
@@ -1,16 +1,15 @@
1
1
  import { REPORT_RESULT_EXTENSION_PATH, REPORT_RESULT_TOOL_NAME } from "../ask-contract/index.ts";
2
+ import type { AgentProgress } from "../contract/index.ts";
2
3
  import { SYSTEM_PROMPT_RECORDER_EXTENSION_PATH } from "./system-prompt-recorder.ts";
3
- import type { AgentStats, Frame, OpenOptions, TokenBreakdown } from "./transport.ts";
4
+ import type {
5
+ AgentStats,
6
+ CompactionResult,
7
+ Frame,
8
+ OpenOptions,
9
+ TokenBreakdown,
10
+ } from "./transport.ts";
4
11
 
5
- /** What the Agent reported about its own work, read from a `get_state` probe. */
6
- export interface AgentProgress {
7
- /** True while pi streams a completion, compacts its context, or holds a queued prompt. */
8
- readonly working: boolean;
9
- readonly streaming: boolean;
10
- readonly compacting: boolean;
11
- /** Prompts pi has queued but not started. */
12
- readonly pendingMessages: number;
13
- }
12
+ export type { AgentProgress } from "../contract/index.ts";
14
13
 
15
14
  /** The command line for one Agent. */
16
15
  export function piCommand(options: OpenOptions, toolProbeExtensionPath?: string): string[] {
@@ -23,7 +22,10 @@ export function piCommand(options: OpenOptions, toolProbeExtensionPath?: string)
23
22
  }
24
23
  appendCapabilities(cmd, options, toolProbeExtensionPath);
25
24
  if (options.sessionDir) cmd.push("--session-dir", options.sessionDir);
25
+ // `--session` and `--fork` are mutually exclusive in pi, and a resume is the
26
+ // stronger claim: it names the very session this Agent must continue.
26
27
  if (options.sessionFile) cmd.push("--session", options.sessionFile);
28
+ else if (options.forkSession) cmd.push("--fork", options.forkSession);
27
29
  // No --approve: Agents inherit the user's saved project-trust decision (ADR-0009).
28
30
  return cmd;
29
31
  }
@@ -154,6 +156,47 @@ export function readStats(response: Frame): AgentStats {
154
156
  return { tokens: readBreakdown("tokens" in data ? data.tokens : null), cost };
155
157
  }
156
158
 
159
+ /**
160
+ * What a `compact` response reports (ADR-0043).
161
+ *
162
+ * A missing field becomes null rather than 0, so "unknown" and "free" stay
163
+ * distinguishable: a custom compaction handler may answer without usage.
164
+ */
165
+ export function readCompaction(response: Frame): CompactionResult {
166
+ const data: unknown = response.data;
167
+ if (typeof data !== "object" || data === null) {
168
+ return { tokensBefore: null, tokensAfter: null, tokens: null, cost: null };
169
+ }
170
+ const record: Record<string, unknown> = { ...data };
171
+ const usage: unknown = record.usage;
172
+ const usageRecord: Record<string, unknown> =
173
+ typeof usage === "object" && usage !== null ? { ...usage } : {};
174
+ const cost: unknown = usageRecord.cost;
175
+ return {
176
+ tokensBefore: typeof record.tokensBefore === "number" ? record.tokensBefore : null,
177
+ tokensAfter:
178
+ typeof record.estimatedTokensAfter === "number" ? record.estimatedTokensAfter : null,
179
+ tokens: readCompactionTokens(usageRecord),
180
+ cost:
181
+ typeof cost === "object" &&
182
+ cost !== null &&
183
+ typeof (cost as { total?: unknown }).total === "number"
184
+ ? (cost as { total: number }).total
185
+ : null,
186
+ };
187
+ }
188
+
189
+ /** The summary call's own token breakdown, or null when pi reported none. */
190
+ function readCompactionTokens(usage: Record<string, unknown>): TokenBreakdown | null {
191
+ return readBreakdown({
192
+ input: usage.input,
193
+ output: usage.output,
194
+ cacheRead: usage.cacheRead,
195
+ cacheWrite: usage.cacheWrite,
196
+ total: usage.totalTokens,
197
+ });
198
+ }
199
+
157
200
  function readBreakdown(tokens: unknown): TokenBreakdown | null {
158
201
  if (typeof tokens !== "object" || tokens === null) return null;
159
202
  const record: Record<string, unknown> = { ...tokens };
@@ -1,7 +1,13 @@
1
1
  import type { CanonicalJsonObject, ReportedResult } from "../ask-contract/index.ts";
2
+ import type {
3
+ AskOptions,
4
+ CompactionResult,
5
+ ResolvedSpawnOptions,
6
+ ThinkingLevel,
7
+ TokenBreakdown,
8
+ } from "../contract/index.ts";
2
9
  import type { AskLimitOutcome, AskStalledOutcome } from "../errors.ts";
3
10
  import type { RecordedSpawnSelection } from "../model/index.ts";
4
- import type { AskOptions, ResolvedSpawnOptions, ThinkingLevel } from "../types.ts";
5
11
 
6
12
  /**
7
13
  * The one seam of the runtime (ticket 04). An AgentTransport represents a whole
@@ -15,14 +21,7 @@ import type { AskOptions, ResolvedSpawnOptions, ThinkingLevel } from "../types.t
15
21
  /** One JSONL frame in either direction. Unknown `type`s must survive (ticket 01). */
16
22
  export type Frame = { readonly type: string; readonly [k: string]: unknown };
17
23
 
18
- /** pi's full token usage for one Agent, as reported by `get_session_stats`. */
19
- export interface TokenBreakdown {
20
- readonly input: number;
21
- readonly output: number;
22
- readonly cacheRead: number;
23
- readonly cacheWrite: number;
24
- readonly total: number;
25
- }
24
+ export type { CompactionResult, TokenBreakdown } from "../contract/index.ts";
26
25
 
27
26
  /** Cost and usage read at Agent shutdown (ADR-0012). */
28
27
  export interface AgentStats {
@@ -93,6 +92,27 @@ export interface AskCompletion {
93
92
  readonly recovered?: true;
94
93
  }
95
94
 
95
+ /**
96
+ * Opaque marker naming one compaction of an Agent's context.
97
+ *
98
+ * A compaction sits between two Asks, so it cannot ride the Agent-level frame
99
+ * streams: a Cassette replay switches those cursors to an Ask and never
100
+ * switches back. The marker gives the exchange its own recorded streams.
101
+ */
102
+ export interface CompactionMarker {
103
+ /** Monotonic per Agent, from 0. */
104
+ readonly index: number;
105
+ /** sha256 of the settled-Ask count and the custom instructions, when given. */
106
+ readonly hash: string;
107
+ /** Settled Asks of this Agent at the compaction point. */
108
+ readonly afterAsks: number;
109
+ }
110
+
111
+ /** Presence identifies Cassette playback of one compaction. */
112
+ export interface CompactionPlayback {
113
+ readonly result: CompactionResult;
114
+ }
115
+
96
116
  /** Presence identifies Cassette playback, including recorded successful Asks. */
97
117
  export interface AskPlayback {
98
118
  /** Limit outcome recorded for this Ask, if it rejected with ASK_LIMIT. */
@@ -143,6 +163,15 @@ export interface AgentTransport {
143
163
  /** Reports surfaced live outcomes; replay ignores completion. */
144
164
  finishAsk(completion: AskCompletion): void;
145
165
 
166
+ /**
167
+ * Begins one compaction. Live transports return undefined; replay transports
168
+ * return the recorded result.
169
+ */
170
+ beginCompaction(marker: CompactionMarker): CompactionPlayback | undefined;
171
+
172
+ /** Ends the compaction exchange, so later frames belong to the Agent again. */
173
+ finishCompaction(result: CompactionResult | undefined): void;
174
+
146
175
  /**
147
176
  * The extraction policy recorded for the Ask at `index`, when a Cassette
148
177
  * backs it. An Ask recorded under an older policy keeps that policy, so its
@@ -200,6 +229,22 @@ export interface OpenOptions {
200
229
  readonly sessionDir?: string;
201
230
  /** Resumes an existing pi session, translated to `--session <path>`. */
202
231
  readonly sessionFile?: string;
232
+ /** How the Agent came to be; absent means an ordinary spawn. Spawn identity. */
233
+ readonly origin?: "fork";
234
+ /** Name of the Agent this one was forked from. Spawn identity; never argv. */
235
+ readonly forkOf?: string;
236
+ /** Settled Asks of the fork source at the fork point. Spawn identity. */
237
+ readonly forkAsks?: number;
238
+ /**
239
+ * The fork source's session file, translated to `pi --fork <path>`.
240
+ * Never spawn identity: the path is machine-specific.
241
+ */
242
+ readonly forkSession?: string;
243
+ /**
244
+ * The fork source's worktree, so the fork branches from it instead of from a
245
+ * clean base tree. Never spawn identity.
246
+ */
247
+ readonly worktreeFrom?: WorktreeResolution;
203
248
  }
204
249
 
205
250
  /** Nondeterministic worktree identity resolved below the transport seam. */