@yaag/runtime 0.26.0 → 0.27.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 (54) hide show
  1. package/package.json +1 -1
  2. package/src/agent/agent.ts +29 -17
  3. package/src/agent/fork.ts +40 -12
  4. package/src/agent/host-fork.ts +85 -0
  5. package/src/agent/spawn-definition-request.ts +38 -3
  6. package/src/agent/spawn-open.ts +43 -103
  7. package/src/agent/spawn-plan.ts +114 -0
  8. package/src/agent/spawn-request.ts +16 -2
  9. package/src/agent/spawn.ts +20 -3
  10. package/src/ask/ask-exchange-options.ts +3 -6
  11. package/src/ask/ask-exchange.ts +48 -108
  12. package/src/ask/ask-guard.ts +207 -0
  13. package/src/ask/ask-timing.ts +12 -0
  14. package/src/ask/index.ts +1 -0
  15. package/src/cassette/cassette-loader.ts +9 -20
  16. package/src/cassette/cassette-schema.ts +10 -1
  17. package/src/cassette/cassette.ts +11 -34
  18. package/src/cassette/checkpoint.ts +306 -0
  19. package/src/cassette/index.ts +16 -7
  20. package/src/cassette/parked-asks.ts +38 -0
  21. package/src/cassette/replay-divergence.ts +7 -102
  22. package/src/cassette/resume-identity.ts +5 -1
  23. package/src/cassette/resume-preconditions.ts +14 -0
  24. package/src/cassette/resume-transport.ts +26 -32
  25. package/src/cassette/run-identity.ts +109 -0
  26. package/src/cassette/session-answer.ts +51 -114
  27. package/src/cassette/spawn-identity.ts +318 -0
  28. package/src/contract/error-codes.ts +1 -0
  29. package/src/contract/index.ts +1 -0
  30. package/src/contract/spawn-options.ts +33 -2
  31. package/src/error-factories.ts +8 -0
  32. package/src/events.ts +4 -2
  33. package/src/index.ts +4 -0
  34. package/src/pi-session/append-tool-result.ts +165 -0
  35. package/src/pi-session/index.ts +30 -0
  36. package/src/pi-session/pi-session-error.ts +34 -0
  37. package/src/pi-session/session-copy.ts +113 -0
  38. package/src/pi-session/session-entries.ts +130 -0
  39. package/src/question-summary/index.ts +4 -8
  40. package/src/question-summary/summarize-question.ts +1 -1
  41. package/src/question-summary/summary-policy.ts +5 -2
  42. package/src/run/agent-questions.ts +82 -0
  43. package/src/run/answers.ts +22 -1
  44. package/src/run/host-session.ts +233 -0
  45. package/src/run/index.ts +7 -0
  46. package/src/run/run-context.ts +3 -0
  47. package/src/run/run.ts +191 -181
  48. package/src/transport/live-transport.ts +19 -0
  49. package/src/transport/pi-state.ts +10 -1
  50. package/src/transport/transport.ts +13 -9
  51. package/src/types.ts +1 -0
  52. package/src/cassette/checkpoint-flush.ts +0 -101
  53. package/src/cassette/run-checkpoint.ts +0 -272
  54. package/src/question-summary/session-copy.ts +0 -169
@@ -0,0 +1,207 @@
1
+ import { AskLimit } from "../ask-contract/index.ts";
2
+ import { agentError, askStalledError } from "../error-factories.ts";
3
+ import type { AskLimitOutcome, AskStalledOutcome } from "../errors.ts";
4
+ import type { CommandResponse, Frame } from "../transport/index.ts";
5
+ import type { EffectiveAskOptions } from "./ask-hash.ts";
6
+ import type { AskTiming } from "./ask-timing.ts";
7
+ import { IdleKillSignal, IdleWatch } from "./idle-watch.ts";
8
+ import {
9
+ type SettlementCause,
10
+ StallSignal,
11
+ StallWatchdog,
12
+ stallBudgetMs,
13
+ } from "./stall-watchdog.ts";
14
+
15
+ export interface AskGuardOptions {
16
+ /** The Agent this Ask runs on; names every error the guard reports. */
17
+ readonly agent: string;
18
+ readonly ask: EffectiveAskOptions;
19
+ /** Sends one control frame to the Agent and resolves with its response. */
20
+ readonly command: (frame: Frame) => Promise<CommandResponse>;
21
+ /** True when this Ask already observed a terminal assistant `message_end`. */
22
+ readonly terminal: () => boolean;
23
+ /** One sentence appended to the wrap-up, present when the Ask reports a result. */
24
+ readonly wrapUpSuffix?: string;
25
+ /** Test-only waits of the controls; absent in production. */
26
+ readonly timing?: AskTiming;
27
+ /** Called once when the Stall Watchdog recovered, so the Ask settles by hand. */
28
+ readonly onRecovered: () => void;
29
+ }
30
+
31
+ /**
32
+ * Every control of one Ask attempt, behind one object (ADR-0020, ADR-0038).
33
+ *
34
+ * The guard owns the Ask limit, the idle watch and the Stall Watchdog. It is a
35
+ * composition unit only: it adds no policy and ranks nothing. "First trip wins"
36
+ * stays a race between the controls' own failure promises, and the guard
37
+ * translates whichever signal wins into a `YaagError`. One guard serves one
38
+ * attempt and is never reused.
39
+ */
40
+ export class AskGuard {
41
+ readonly #agent: string;
42
+ readonly #limit: AskLimit;
43
+ readonly #idle: IdleWatch | null;
44
+ readonly #stall: StallWatchdog | null;
45
+ readonly #failure: Promise<never>;
46
+ #cause: SettlementCause = "normal";
47
+ #drain = false;
48
+
49
+ constructor(options: AskGuardOptions) {
50
+ this.#agent = options.agent;
51
+ const command = options.command;
52
+ this.#limit = new AskLimit({
53
+ ask: options.ask,
54
+ durationGraceMs: options.timing?.askLimitGraceMs,
55
+ command: async (frame) => (await command(frame)).success,
56
+ ...(options.wrapUpSuffix === undefined ? {} : { wrapUpSuffix: options.wrapUpSuffix }),
57
+ });
58
+ this.#idle =
59
+ options.ask.idleMs === undefined
60
+ ? null
61
+ : new IdleWatch({
62
+ idleMs: options.ask.idleMs,
63
+ ...(options.timing?.idleAbortSettleMs === undefined
64
+ ? {}
65
+ : { abortSettleMs: options.timing.idleAbortSettleMs }),
66
+ command: async (frame) => (await command(frame)).success,
67
+ });
68
+ const stallMs = stallBudgetMs(options.ask.stallMs);
69
+ this.#stall =
70
+ stallMs === null
71
+ ? null
72
+ : new StallWatchdog({
73
+ stallMs,
74
+ ...(options.timing?.stallProbeSettleMs === undefined
75
+ ? {}
76
+ : { probeSettleMs: options.timing.stallProbeSettleMs }),
77
+ command,
78
+ terminal: options.terminal,
79
+ recover: () => {
80
+ this.#cause = "recovered";
81
+ // The missing `agent_settled` may still arrive: it belongs to the
82
+ // turn yaag just settled by hand, never to the next Ask.
83
+ this.#drain = true;
84
+ options.onRecovered();
85
+ },
86
+ });
87
+ this.#failure = this.#raceFailures();
88
+ // A control may trip before the Ask starts awaiting the race.
89
+ void this.#failure.catch(() => {});
90
+ }
91
+
92
+ /** Arms every control it holds. */
93
+ start(): void {
94
+ this.#limit.start();
95
+ this.#idle?.start();
96
+ this.#stall?.start();
97
+ }
98
+
99
+ /** Feeds one frame to every control. */
100
+ observe(frame: Frame): void {
101
+ this.#limit.observe(frame);
102
+ // The idle watch only cares about `agent_settled` once it escalated: before
103
+ // that the frame is the settlement the Ask itself is waiting for.
104
+ if (frame.type !== "agent_settled" || this.#idle?.tripped === true) this.#idle?.observe(frame);
105
+ this.#stall?.observe(frame);
106
+ }
107
+
108
+ /** The turn settled normally. */
109
+ settled(): void {
110
+ this.#stall?.settled();
111
+ }
112
+
113
+ /**
114
+ * Parks every control before an Agent Question is raised (ADR-0023), so no
115
+ * control can trip between the park and the Question. Returns false when a
116
+ * limit already tripped: first signal wins and the Ask raises nothing.
117
+ */
118
+ suspend(): boolean {
119
+ if (this.#limit.tripped) return false;
120
+ this.#limit.suspend();
121
+ this.#idle?.suspend();
122
+ this.#stall?.suspend();
123
+ return true;
124
+ }
125
+
126
+ /** Opens a new settlement window after a correction steer. */
127
+ rearm(): void {
128
+ this.#stall?.rearm();
129
+ }
130
+
131
+ /** Stops every timer. Idempotent. */
132
+ cleanup(): void {
133
+ this.#limit.cleanup();
134
+ this.#idle?.cleanup();
135
+ this.#stall?.cleanup();
136
+ }
137
+
138
+ /** Rejects with a `YaagError` when the first control trips destructively. */
139
+ get failure(): Promise<never> {
140
+ return this.#failure;
141
+ }
142
+
143
+ /** How this Ask settled, as reported in its `ask_end` Lifecycle Event. */
144
+ get cause(): SettlementCause {
145
+ return this.#cause;
146
+ }
147
+
148
+ /** True when the connection must drain a stale turn at cleanup. */
149
+ get drainStaleFrames(): boolean {
150
+ return this.#drain;
151
+ }
152
+
153
+ /** The limit outcome, once a limit aborted this Ask. */
154
+ get limit(): AskLimitOutcome | null {
155
+ return this.#limit.abortOutcome;
156
+ }
157
+
158
+ /** The recording view of a stall: whichever control ended the Ask. */
159
+ get stalled(): AskStalledOutcome | null {
160
+ return this.#idle?.result ?? this.#stall?.result ?? null;
161
+ }
162
+
163
+ /**
164
+ * The post-settlement check, which is the idle watch alone. A stall reaches
165
+ * the Ask through {@link failure}; reading it here too would let a stall that
166
+ * resolves together with settlement be thrown from the settled path.
167
+ */
168
+ settlementStall(): AskStalledOutcome | null {
169
+ return this.#idle?.result ?? null;
170
+ }
171
+
172
+ /** Opens one output-correction pass under the limit's budget. */
173
+ beginCorrection(): boolean {
174
+ return this.#limit.enterOutputCorrection();
175
+ }
176
+
177
+ leaveCorrection(): void {
178
+ this.#limit.leaveOutputCorrection();
179
+ }
180
+
181
+ /** True once a limit tripped and the Ask is wrapping up. */
182
+ get wrappingUp(): boolean {
183
+ return this.#limit.tripped;
184
+ }
185
+
186
+ #raceFailures(): Promise<never> {
187
+ const controls = [
188
+ this.#limit.failed,
189
+ this.#idle?.failed,
190
+ this.#idle?.killed,
191
+ this.#stall?.failed,
192
+ ].filter((promise): promise is Promise<never> => promise !== undefined);
193
+ return Promise.race(controls).catch((error: unknown) => {
194
+ if (error instanceof IdleKillSignal) throw askStalledError(this.#agent, error.outcome);
195
+ if (error instanceof StallSignal) {
196
+ this.#cause = "stalled";
197
+ this.#drain = !error.outcome.destructive;
198
+ throw askStalledError(this.#agent, error.outcome);
199
+ }
200
+ throw agentError(
201
+ this.#agent,
202
+ "AGENT_FAILED",
203
+ error instanceof Error ? error.message : "limit control command failed",
204
+ );
205
+ });
206
+ }
207
+ }
@@ -0,0 +1,12 @@
1
+ /**
2
+ * Test-only waits of the Ask Guard's controls; production passes none and every
3
+ * control applies its own fixed constant.
4
+ */
5
+ export interface AskTiming {
6
+ /** Test-only override for the fixed duration-limit grace. */
7
+ readonly askLimitGraceMs?: number;
8
+ /** Test-only override for the bounded settle wait after an idle abort. */
9
+ readonly idleAbortSettleMs?: number;
10
+ /** Test-only override for the bounded wait for the Stall Watchdog probe. */
11
+ readonly stallProbeSettleMs?: number;
12
+ }
package/src/ask/index.ts CHANGED
@@ -8,5 +8,6 @@ export { exchangeAsk } from "./ask-exchange.ts";
8
8
  export type { AskModelFallback } from "./ask-exchange-options.ts";
9
9
  export { askHash, askMarkerContext, type EffectiveAskOptions } from "./ask-hash.ts";
10
10
  export { AskOutputTail } from "./ask-output-tail.ts";
11
+ export type { AskTiming } from "./ask-timing.ts";
11
12
  export { AskTurn } from "./ask-turn.ts";
12
13
  export type { SettlementCause } from "./stall-watchdog.ts";
@@ -8,6 +8,7 @@ import {
8
8
  type CassetteAsk,
9
9
  } from "./cassette.ts";
10
10
  import { CassetteSchema } from "./cassette-schema.ts";
11
+ import { readableCassette } from "./checkpoint.ts";
11
12
 
12
13
  /**
13
14
  * Reads and validates one Cassette artifact before replay begins.
@@ -135,7 +136,9 @@ function assertRunPresence(artifact: CassetteArtifact, path: string): void {
135
136
  * Deliberately not checked: that every `ask.incomplete.questionId` names a
136
137
  * Question of this run block. A `stopped` artifact can hold a parked Ask whose
137
138
  * Question the drain never collected, and the loader must not refuse an
138
- * artifact yaag itself writes.
139
+ * artifact yaag itself writes. The loader stays permissive on purpose: the rule
140
+ * belongs to resume, which refuses such a marker at ledger construction, in
141
+ * `run/answers.ts`, before the first Agent starts (ADR-0022/ADR-0023).
139
142
  */
140
143
  function assertUniqueQuestionIds(artifact: CassetteArtifact, path: string): void {
141
144
  const seen = new Set<string>();
@@ -173,15 +176,13 @@ function upgrade(artifact: CassetteArtifact): Cassette {
173
176
  }
174
177
 
175
178
  /**
176
- * Strict replay demands a settled Run. An `interrupted` artifact stops at the
177
- * last Ask boundary, so its final Ask has no recorded settlement (ADR-0031).
179
+ * Strict replay demands a settled Run. The `interrupted` refusal is the
180
+ * Checkpoint's own read-side rule (ADR-0031); the parked-Ask refusal below is a
181
+ * replay rule and stays here.
178
182
  */
179
183
  export function assertReplayable(cassette: Cassette, path: string): void {
180
- if (cassette.run.outcome === "interrupted") {
181
- throw new Error(
182
- `cannot replay interrupted cassette "${path}": the Run died before it settled; use resume instead`,
183
- );
184
- }
184
+ const readable = readableCassette(cassette, path, "replay");
185
+ if (!readable.ok) throw new Error(readable.reason);
185
186
  for (const agent of cassette.agents) {
186
187
  for (const [index, ask] of agent.asks.entries()) {
187
188
  if (ask.incomplete === undefined) continue;
@@ -192,18 +193,6 @@ export function assertReplayable(cassette: Cassette, path: string): void {
192
193
  }
193
194
  }
194
195
 
195
- /**
196
- * Warns once when a resume source came from a hard death. The Run continues:
197
- * resume already handles an incomplete last Ask.
198
- */
199
- export function interruptedResumeWarning(cassette: Cassette, path: string): string | null {
200
- if (cassette.run.outcome !== "interrupted") return null;
201
- return (
202
- `resuming interrupted cassette "${path}": the Run died before it settled, ` +
203
- "the recording stops at the last Ask boundary, and re-run tools can repeat their effects"
204
- );
205
- }
206
-
207
196
  function message(error: unknown): string {
208
197
  return error instanceof Error ? error.message : "is invalid";
209
198
  }
@@ -21,6 +21,11 @@ const ThinkingSchema = Type.Union(
21
21
 
22
22
  const StringArray = Type.Array(Type.String());
23
23
 
24
+ /**
25
+ * The policy half of a recorded spawn. It mirrors the rows the spawn field
26
+ * table marks `askContext` (`spawn-identity.ts`), minus `cwd` and `worktree`,
27
+ * which the two schemas below place themselves.
28
+ */
24
29
  const spawnPolicyFields = {
25
30
  model: Type.Optional(Type.String()),
26
31
  systemPrompt: Type.Optional(Type.String()),
@@ -41,7 +46,10 @@ const CassetteSpawnSchema = Type.Object({
41
46
  canAskUser: Type.Optional(Type.Literal(true)),
42
47
  askUserProtocol: Type.Optional(Type.Integer()),
43
48
  parent: Type.Optional(Type.String()),
44
- origin: Type.Optional(Type.Literal("fork")),
49
+ origin: Type.Optional(
50
+ Type.Union([Type.Literal("spawn"), Type.Literal("fork"), Type.Literal("host-fork")]),
51
+ ),
52
+ hostHash: Type.Optional(Type.String()),
45
53
  forkOf: Type.Optional(Type.String()),
46
54
  forkAsks: Type.Optional(Type.Number()),
47
55
  });
@@ -189,6 +197,7 @@ const CassetteRunSchema = Type.Object({
189
197
  args: Type.Optional(Type.Unknown()),
190
198
  programHash: Type.Optional(Type.String()),
191
199
  profile: Type.Optional(Type.String()),
200
+ host: Type.Optional(Type.Object({ hostHash: Type.String() })),
192
201
  questions: Type.Optional(Type.Array(CassetteQuestionSchema)),
193
202
  answers: Type.Optional(Type.Array(CassetteAnswerSchema)),
194
203
  reason: Type.Optional(Type.String()),
@@ -1,6 +1,6 @@
1
1
  import type { CanonicalJsonObject } from "../ask-contract/index.ts";
2
2
  import type { AskLimitOutcome, AskStalledOutcome } from "../errors.ts";
3
- import type { RunOutcome } from "../events.ts";
3
+ import type { RunOutcome, SpawnOrigin } from "../events.ts";
4
4
  import type {
5
5
  AgentStats,
6
6
  AskCompletion,
@@ -15,6 +15,7 @@ import type {
15
15
  } from "../transport/index.ts";
16
16
  import type { ThinkingLevel } from "../types.ts";
17
17
  import { shapeFrame } from "./cassette-frame-shape.ts";
18
+ import { fromOpenOptions } from "./spawn-identity.ts";
18
19
 
19
20
  /** The Cassette format this runtime writes; the loader also reads version 1. */
20
21
  export const CASSETTE_VERSION = 2 as const;
@@ -63,6 +64,8 @@ export interface CassetteRun {
63
64
  readonly programHash?: string;
64
65
  /** Id of the active Profile; absent for a program with no Profiles and for an older Cassette. */
65
66
  readonly profile?: string;
67
+ /** The Host Source this Run was given (ADR-0068). Run-level: ctx.host exists before any spawn. */
68
+ readonly host?: { readonly hostHash: string };
66
69
  /** Wake payload of a `paused` or `stopped` Run; absent otherwise (ADR-0021). */
67
70
  readonly questions?: readonly CassetteQuestion[];
68
71
  /** Questions this Run resolved from `--answers`, plus every inherited one (ADR-0022). */
@@ -154,7 +157,12 @@ export interface CassetteSpawn {
154
157
  */
155
158
  readonly parent?: string;
156
159
  /** How the Agent came to be; absent means an ordinary spawn. Spawn identity. */
157
- readonly origin?: "fork";
160
+ readonly origin?: SpawnOrigin;
161
+ /**
162
+ * SHA-256 of the Host Session bytes a Host Fork was taken from. Spawn
163
+ * identity; the copy path is not (ADR-0068).
164
+ */
165
+ readonly hostHash?: string;
158
166
  /** Name of the Agent this one was forked from. Spawn identity. */
159
167
  readonly forkOf?: string;
160
168
  /** Settled Asks of the fork source at the fork point. Spawn identity. */
@@ -262,7 +270,7 @@ export class CassetteCollector implements CassetteSink {
262
270
 
263
271
  reserve(options: OpenOptions): CassetteRecorder {
264
272
  const slot = this.#agents.length;
265
- const spawn = spawnIdentity(options);
273
+ const spawn = fromOpenOptions(options);
266
274
  let agent: MutableAgent | null = null;
267
275
  this.#agents.push(null);
268
276
  return {
@@ -360,37 +368,6 @@ export class CassetteCollector implements CassetteSink {
360
368
  }
361
369
  }
362
370
 
363
- function spawnIdentity(options: OpenOptions): CassetteSpawn {
364
- return {
365
- name: options.name,
366
- cwd: options.cwd,
367
- ...(options.model === undefined ? {} : { model: options.model }),
368
- ...(options.systemPrompt === undefined ? {} : { systemPrompt: options.systemPrompt }),
369
- ...(options.thinking === undefined ? {} : { thinking: options.thinking }),
370
- ...(options.appendSystemPrompt === undefined
371
- ? {}
372
- : { appendSystemPrompt: options.appendSystemPrompt }),
373
- ...(options.tools === undefined ? {} : { tools: [...options.tools] }),
374
- ...(options.disallowedTools === undefined
375
- ? {}
376
- : { disallowedTools: [...options.disallowedTools] }),
377
- ...(options.skills === undefined ? {} : { skills: [...options.skills] }),
378
- ...(options.disallowedSkills === undefined
379
- ? {}
380
- : { disallowedSkills: [...options.disallowedSkills] }),
381
- ...(options.declaredExtensions === undefined || options.declaredExtensions.length === 0
382
- ? {}
383
- : { declaredExtensions: [...options.declaredExtensions] }),
384
- ...(options.canAskUser === undefined ? {} : { canAskUser: options.canAskUser }),
385
- ...(options.askUserProtocol === undefined ? {} : { askUserProtocol: options.askUserProtocol }),
386
- ...(options.parent === undefined ? {} : { parent: options.parent }),
387
- ...(options.origin === undefined ? {} : { origin: options.origin }),
388
- ...(options.forkOf === undefined ? {} : { forkOf: options.forkOf }),
389
- ...(options.forkAsks === undefined ? {} : { forkAsks: options.forkAsks }),
390
- ...(options.worktree === true ? { worktree: true } : {}),
391
- };
392
- }
393
-
394
371
  /** The Ask that later frames belong to, or nothing when a compaction owns them. */
395
372
  function activeAsk(agent: MutableAgent | null): MutableAsk | null {
396
373
  const active = agent?.active;