@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
package/src/run/run.ts CHANGED
@@ -10,17 +10,14 @@ import {
10
10
  type CassetteSink,
11
11
  checkpointFileName,
12
12
  cleanStaleCheckpointTemp,
13
- createCheckpointFlusher,
14
- flushingSink,
15
- interruptedResumeWarning,
16
- keepsCheckpoint,
13
+ createCheckpoint,
17
14
  loadCassette,
18
15
  type ProgramIdentity,
16
+ parkedAsks,
19
17
  prepareRecordDestination,
20
18
  profileIdentityWarning,
21
19
  programIdentityWarning,
22
- publishRunCheckpoint,
23
- type RunCheckpointResult,
20
+ readableCassette,
24
21
  recordingTransport,
25
22
  replayTransport,
26
23
  resolveCheckpointDirectory,
@@ -48,10 +45,11 @@ import {
48
45
  skillRestrictionTransport,
49
46
  worktreeTransport,
50
47
  } from "../transport/index.ts";
51
- import { createAgentQuestions } from "./agent-questions.ts";
48
+ import { createAgentQuestions, seedFromResume } from "./agent-questions.ts";
52
49
  import { type AnswerLedger, createAnswerLedger, emptyAnswerLedger } from "./answers.ts";
53
50
  import { validateArgs } from "./args-validation.ts";
54
51
  import { type OrchestrationProgram, programDefinition } from "./define-run.ts";
52
+ import { adoptedHostSource, type HostSessionOptions, prepareHostSource } from "./host-session.ts";
55
53
  import { createPauseRequests } from "./pause-questions.ts";
56
54
  import type { RunContext } from "./run-context.ts";
57
55
  import type { RunResult } from "./run-result.ts";
@@ -99,6 +97,14 @@ export interface RunOptions {
99
97
  readonly control?: RunController;
100
98
  /** Overrides the default checkpoint directory a stopped Run publishes into (ADR-0021). */
101
99
  readonly checkpointDir?: string;
100
+ /**
101
+ * The Host Session this Run was started from (ADR-0068). The runtime hashes
102
+ * the file, copies it once, and offers the copy as `ctx.host`.
103
+ *
104
+ * `toolCallId` is optional: a live Run requires it, because it must close
105
+ * that call in the copy; a --replay or --resume only hashes and compares.
106
+ */
107
+ readonly host?: HostSessionOptions;
102
108
  /**
103
109
  * Effective Config for this Run, read once by the launcher (ADR-0040). The
104
110
  * Run never loads it itself: omission runs config-free, so no Run picks up a
@@ -185,162 +191,202 @@ export async function executeRun<Args, Result>(
185
191
  args,
186
192
  ...(profile === undefined ? {} : { profile: profile.id }),
187
193
  });
188
- const checkpoint = { collector, record: options.record, destination, identity };
194
+ // The Checkpoint owns the whole publish policy: when the artifact flushes,
195
+ // what each outcome keeps, and what run_end may name (ADR-0021/0031/0054).
196
+ // Building it does no I/O, so the ARGS_INVALID "no events before rejection"
197
+ // rule still holds.
198
+ const checkpoint = createCheckpoint({
199
+ collector,
200
+ record: options.record,
201
+ destination,
202
+ identity,
203
+ });
189
204
  try {
190
205
  assertArgs<Args>(definition.args, args);
191
206
  } catch (error) {
192
207
  // The result is discarded on purpose: this rejection precedes run_start, and
193
208
  // no event may precede an ARGS_INVALID rejection, so a lost Checkpoint here
194
209
  // stays a stderr diagnostic (ticket 04).
195
- await publishRunCheckpoint({ outcome: "failed", ...checkpoint });
210
+ await checkpoint.settle("failed");
196
211
  throw error;
197
212
  }
198
213
  // The directory of the --record path is made before any Agent starts, so a Run
199
214
  // whose Cassette can never land does not do its work first and fail last.
200
215
  if (options.record !== undefined) await prepareRecordDestination(options.record);
216
+ // Before the first emit, so a HOST_SESSION_UNUSABLE refusal precedes every
217
+ // Lifecycle Event, exactly like RECORD_PATH_UNUSABLE. A strict replay makes no
218
+ // copy — no live child can consume it — and it needs no tool call id, while a
219
+ // live Run does (ADR-0068).
220
+ const recordedHost = replay?.run.host ?? resume?.run.host;
221
+ const host =
222
+ options.host !== undefined
223
+ ? await prepareHostSource({
224
+ host: options.host,
225
+ live: options.replay === undefined && options.resume === undefined,
226
+ copies: options.replay === undefined,
227
+ })
228
+ : recordedHost === undefined
229
+ ? undefined
230
+ : // A replay never spawns pi and a resume re-opens each Host Fork from
231
+ // its recorded session file, so the adopted source needs no copy path.
232
+ {
233
+ source: adoptedHostSource(recordedHost.hostHash),
234
+ remove: async (): Promise<void> => {},
235
+ };
236
+ if (host !== undefined) checkpoint.identifyHost({ hostHash: host.source.hostHash });
201
237
 
202
- let summary: RunSummary = initialSummary();
203
- const sink: StampedEventSink = options.events ?? (() => {});
204
- // Every event the Run emits also feeds the fold, so its own final accounting
205
- // is derived exactly the way an outside observer would derive it. `at` is
206
- // stamped here, once, so no individual emitter touches the wall clock.
207
- const emit: EventSink = (body) => {
208
- const event: LifecycleEvent = { ...body, at: Date.now() };
209
- summary = applyEvent(summary, event);
210
- sink(event);
211
- };
212
- const flusher = createCheckpointFlusher(checkpoint);
213
- // Built before the first Agent starts, so every refusal of the answer
214
- // contract precedes the Run's work (ADR-0022).
215
- const answers: AnswerLedger =
216
- resume === null
217
- ? emptyAnswerLedger()
218
- : createAnswerLedger({
219
- supplied: options.answers ?? {},
220
- questions: resume.run.questions ?? [],
221
- inherited: resume.run.answers ?? [],
222
- });
223
- // Every answered park is restored into its session before the first Agent
224
- // starts, so a conflicting answer refuses the resume before any work (ADR-0023).
225
- if (resume !== null) await restoreSessionAnswers(resume, (id) => answers.take(id));
226
- const factory = selectFactory({
227
- options,
228
- collector: flushingSink(collector, flusher),
229
- replay,
230
- resume,
231
- answers,
232
- });
233
- const agents: Agent[] = [];
234
- const startedAt = Date.now();
235
- const askAdmission = createAskAdmission();
236
- const agentQuestions = createAgentQuestions();
237
- const spawnGate = makeSpawn({
238
- factory,
239
- agents,
240
- emit,
241
- askAdmission,
242
- questions: agentQuestions,
243
- sessionDir: options.sessionDir,
244
- programFile: options.programFile,
245
- // The same value `run_start.program` carries, so an Agent's prompt names
246
- // the Run the reader sees in the Run record.
247
- runName: definition.name ?? "program",
248
- configExtensions: options.config?.extensions ?? EMPTY_EFFECTIVE_CONFIG.extensions,
249
- ...(profile === undefined ? {} : { profile }),
250
- });
238
+ // Everything below can throw with the copy already on disk — a refused
239
+ // resume, a failed session restore, a failed spawn gate — so the removal
240
+ // guards from here. Every exit path removes it; a killed process leaks it,
241
+ // and that is a stated limit (ADR-0068).
242
+ try {
243
+ let summary: RunSummary = initialSummary();
244
+ const sink: StampedEventSink = options.events ?? (() => {});
245
+ // Every event the Run emits also feeds the fold, so its own final accounting
246
+ // is derived exactly the way an outside observer would derive it. `at` is
247
+ // stamped here, once, so no individual emitter touches the wall clock.
248
+ const emit: EventSink = (body) => {
249
+ const event: LifecycleEvent = { ...body, at: Date.now() };
250
+ summary = applyEvent(summary, event);
251
+ sink(event);
252
+ };
253
+ // Built before the first Agent starts, so every refusal of the answer
254
+ // contract precedes the Run's work (ADR-0022).
255
+ const parked = resume === null ? [] : parkedAsks(resume);
256
+ const answers: AnswerLedger =
257
+ resume === null
258
+ ? emptyAnswerLedger()
259
+ : createAnswerLedger({
260
+ supplied: options.answers ?? {},
261
+ questions: resume.run.questions ?? [],
262
+ inherited: resume.run.answers ?? [],
263
+ parked,
264
+ });
265
+ // Every answered park is restored into its session before the first Agent
266
+ // starts, so a conflicting answer refuses the resume before any work (ADR-0023).
267
+ if (resume !== null) await restoreSessionAnswers(resume, (id) => answers.take(id));
268
+ const factory = selectFactory({
269
+ options,
270
+ collector: checkpoint.sink,
271
+ replay,
272
+ resume,
273
+ answers,
274
+ });
275
+ const agents: Agent[] = [];
276
+ const startedAt = Date.now();
277
+ const askAdmission = createAskAdmission();
278
+ const agentQuestions = createAgentQuestions();
279
+ // The open Questions of the Checkpoint are the Questions of this resume: a
280
+ // re-opened Question keeps its id, text, context and summary (ADR-0022/0023).
281
+ if (resume !== null) {
282
+ seedFromResume({ questions: agentQuestions, open: answers.open(), parked });
283
+ }
284
+ const spawnGate = makeSpawn({
285
+ factory,
286
+ agents,
287
+ emit,
288
+ askAdmission,
289
+ questions: agentQuestions,
290
+ sessionDir: options.sessionDir,
291
+ programFile: options.programFile,
292
+ // The same value `run_start.program` carries, so an Agent's prompt names
293
+ // the Run the reader sees in the Run record.
294
+ runName: definition.name ?? "program",
295
+ configExtensions: options.config?.extensions ?? EMPTY_EFFECTIVE_CONFIG.extensions,
296
+ ...(profile === undefined ? {} : { profile }),
297
+ });
251
298
 
252
- const pauseRequests = createPauseRequests(answers);
253
- const ctx: RunContext<Args> = {
254
- args,
255
- spawn: spawnGate.spawn,
256
- askUser: pauseRequests.askUser,
257
- pause: pauseRequests.pause,
258
- ...(profile === undefined ? {} : { profile: { id: profile.id } }),
259
- };
260
- emit({
261
- type: "run_start",
262
- program: definition.name ?? "program",
263
- artifact: destination,
264
- ...(profile === undefined ? {} : { profile: profile.id }),
265
- });
299
+ const pauseRequests = createPauseRequests(answers);
300
+ const ctx: RunContext<Args> = {
301
+ args,
302
+ spawn: spawnGate.spawn,
303
+ askUser: pauseRequests.askUser,
304
+ pause: pauseRequests.pause,
305
+ ...(profile === undefined ? {} : { profile: { id: profile.id } }),
306
+ ...(host === undefined ? {} : { host: host.source }),
307
+ };
308
+ emit({
309
+ type: "run_start",
310
+ program: definition.name ?? "program",
311
+ artifact: destination,
312
+ ...(profile === undefined ? {} : { profile: profile.id }),
313
+ });
266
314
 
267
- // The program's settlement is held rather than rethrown from a `finally`, so
268
- // publication can displace it when the checkpoint fails (ADR-0021).
269
- const settlement = await settleRun({
270
- program: () => definition.run(ctx),
271
- requests: controlRequests(options.control, options.signal),
272
- agents,
273
- closeAdmission: () => {
274
- askAdmission.close();
275
- spawnGate.close();
276
- },
277
- questionRaised: agentQuestions.raised,
278
- });
279
- const outcome: RunOutcome = settlement.outcome;
280
- const settled = heldSettlement(settlement);
281
- // Idempotent: a settlement that never drained has not closed admission yet.
282
- askAdmission.close();
283
- spawnGate.close();
284
- await reapAll({ agents, emit });
285
- // No flush may land after the settled artifact, or an acknowledged Run would
286
- // be overwritten by an `interrupted` one.
287
- await flusher.quiesce();
288
- // The summarizer runs here and nowhere else: after quiescence and after every
289
- // Agent is reaped, so it reads a session file pi has finished writing, and
290
- // before publication, so each summary is durable in the Cassette (ADR-0022).
291
- const summarized =
292
- outcome === "paused"
293
- ? await summarizeQuestions({
294
- questions: agentQuestions,
295
- agents,
296
- policy: questionSummaryOf(options.config),
297
- openAgent: spawnGate.openInternal,
298
- ...(options.replay === undefined ? {} : { replaying: true }),
299
- })
300
- : { warnings: [] };
301
- // Built once, after the summaries landed, so the wake payload and the returned
302
- // result carry the same questions. The program's own questions come first;
303
- // both registries are Run-scoped and neither can key a question of the other.
304
- const openQuestions = [...pauseRequests.questions, ...agentQuestions.questions];
305
- const pausedWarnings = [
306
- ...(settled.ok === "paused" ? settled.warnings : []),
307
- ...summarized.warnings,
308
- ];
309
- // run_end is the acknowledgement: nothing may report an outcome before the
310
- // checkpoint's destination-directory fsync has landed (ADR-0021).
311
- const publication = await publishRunCheckpoint({
312
- outcome,
313
- ...checkpoint,
314
- wake: {
315
+ // The program's settlement is held rather than rethrown from a `finally`, so
316
+ // publication can displace it when the checkpoint fails (ADR-0021).
317
+ const settlement = await settleRun({
318
+ program: () => definition.run(ctx),
319
+ requests: controlRequests(options.control, options.signal),
320
+ agents,
321
+ closeAdmission: () => {
322
+ askAdmission.close();
323
+ spawnGate.close();
324
+ },
325
+ questionRaised: agentQuestions.raised,
326
+ });
327
+ const outcome: RunOutcome = settlement.outcome;
328
+ const settled = heldSettlement(settlement);
329
+ // Idempotent: a settlement that never drained has not closed admission yet.
330
+ askAdmission.close();
331
+ spawnGate.close();
332
+ await reapAll({ agents, emit });
333
+ // The summarizer runs here and nowhere else: after every Agent is reaped, so
334
+ // it reads a session file pi has finished writing, and before settlement, so
335
+ // each summary is durable in the Cassette (ADR-0022). `settle()` quiesces the
336
+ // in-flight flushes itself, so no flush can land after the settled artifact.
337
+ // The summarizer's own Agent runs before that quiescence, so it can flush one
338
+ // more `interrupted` artifact; the settled publication supersedes it.
339
+ const summarized =
340
+ outcome === "paused"
341
+ ? await summarizeQuestions({
342
+ questions: agentQuestions,
343
+ agents,
344
+ policy: questionSummaryOf(options.config),
345
+ openAgent: spawnGate.openInternal,
346
+ ...(options.replay === undefined ? {} : { replaying: true }),
347
+ })
348
+ : { warnings: [] };
349
+ // Built once, after the summaries landed, so the wake payload and the returned
350
+ // result carry the same questions. The program's own questions come first;
351
+ // both registries are Run-scoped and neither can key a question of the other.
352
+ const openQuestions = [...pauseRequests.questions, ...agentQuestions.questions];
353
+ const pausedWarnings = [
354
+ ...(settled.ok === "paused" ? settled.warnings : []),
355
+ ...summarized.warnings,
356
+ ];
357
+ // run_end is the acknowledgement: nothing may report an outcome before the
358
+ // checkpoint's destination-directory fsync has landed (ADR-0021).
359
+ const { displacedBy, ...ending } = await checkpoint.settle(outcome, {
315
360
  // The program's own Questions first, then the Agents': the same order the
316
361
  // RunResult carries, so an artifact and a reader agree (ADR-0022).
317
362
  questions: openQuestions,
318
363
  answers: answers.resolved(),
319
364
  ...(pauseRequests.reason === undefined ? {} : { reason: pauseRequests.reason }),
320
- },
321
- });
322
- const ending = endingFrom({ publication, outcome, destination, record: options.record });
323
- emitRunEnd({
324
- emit,
325
- durationMs: Date.now() - startedAt,
326
- summary,
327
- ...ending,
328
- ...(settled.ok === "paused" && pausedWarnings.length > 0 ? { warnings: pausedWarnings } : {}),
329
- });
330
- if (publication.kind === "displaced") throw publication.error;
331
- if (settled.ok === "paused") {
332
- // Built after publication, so `checkpoint` always names a file that is on
333
- // disk and fsynced (ADR-0021).
334
- return {
335
- outcome: "paused",
336
- questions: openQuestions,
337
- ...(pauseRequests.reason === undefined ? {} : { reason: pauseRequests.reason }),
338
- checkpoint: destination,
339
- ...(pausedWarnings.length > 0 ? { warnings: pausedWarnings } : {}),
340
- };
365
+ });
366
+ emitRunEnd({
367
+ emit,
368
+ durationMs: Date.now() - startedAt,
369
+ summary,
370
+ ...ending,
371
+ ...(settled.ok === "paused" && pausedWarnings.length > 0 ? { warnings: pausedWarnings } : {}),
372
+ });
373
+ if (displacedBy !== undefined) throw displacedBy;
374
+ if (settled.ok === "paused") {
375
+ // Built after publication, so `checkpoint` always names a file that is on
376
+ // disk and fsynced (ADR-0021).
377
+ return {
378
+ outcome: "paused",
379
+ questions: openQuestions,
380
+ ...(pauseRequests.reason === undefined ? {} : { reason: pauseRequests.reason }),
381
+ checkpoint: destination,
382
+ ...(pausedWarnings.length > 0 ? { warnings: pausedWarnings } : {}),
383
+ };
384
+ }
385
+ if (!settled.ok) throw settled.error;
386
+ return { outcome: "completed", value: settled.value };
387
+ } finally {
388
+ await host?.remove();
341
389
  }
342
- if (!settled.ok) throw settled.error;
343
- return { outcome: "completed", value: settled.value };
344
390
  }
345
391
 
346
392
  /**
@@ -370,8 +416,8 @@ async function loadResume(
370
416
  ): Promise<Cassette | null> {
371
417
  if (path === undefined) return null;
372
418
  const cassette = await loadCassette(path);
373
- const warning = interruptedResumeWarning(cassette, path);
374
- if (warning !== null) writeRecordingDiagnostic(warning);
419
+ const readable = readableCassette(cassette, path, "resume");
420
+ if (readable.ok && readable.warning !== undefined) writeRecordingDiagnostic(readable.warning);
375
421
  warnOnIdentity(cassette, path, program);
376
422
  return cassette;
377
423
  }
@@ -512,42 +558,6 @@ interface RunEndOptions {
512
558
  readonly warnings?: readonly string[];
513
559
  }
514
560
 
515
- /**
516
- * Folds one publication result into how the Run ends. A displaced publication
517
- * takes the outcome; a lost Checkpoint keeps it and reports the loss instead.
518
- */
519
- function endingFrom(options: {
520
- readonly publication: RunCheckpointResult;
521
- readonly outcome: RunOutcome;
522
- readonly destination: string;
523
- /** The `--record` destination, or undefined; it decides what is kept. */
524
- readonly record: string | undefined;
525
- }): {
526
- readonly outcome: RunOutcome;
527
- readonly checkpointLost?: string;
528
- readonly checkpoint?: string;
529
- } {
530
- const { publication, outcome, destination, record } = options;
531
- switch (publication.kind) {
532
- case "published":
533
- // A Run names a Checkpoint only when publication kept the artifact, and
534
- // only a paused or stopped Run resumes from one (ADR-0054). `keepsCheckpoint`
535
- // is the one rule for the first half, so no Run can name a file that
536
- // publication just deleted.
537
- return {
538
- outcome,
539
- ...((outcome === "paused" || outcome === "stopped") &&
540
- keepsCheckpoint({ outcome, ...(record === undefined ? {} : { record }) })
541
- ? { checkpoint: destination }
542
- : {}),
543
- };
544
- case "lost":
545
- return { outcome, checkpointLost: publication.message };
546
- case "displaced":
547
- return { outcome: "failed" };
548
- }
549
- }
550
-
551
561
  /** Emits the Run's acknowledgement, the last Lifecycle Event of every Run. */
552
562
  function emitRunEnd({
553
563
  emit,
@@ -36,12 +36,31 @@ export const liveTransport: TransportFactory = {
36
36
  options: OpenOptions,
37
37
  observeStartup?: TransportStartupObserver,
38
38
  ): Promise<AgentTransport> {
39
+ assertHostForkSource(options);
39
40
  const transport = new LiveTransport(options);
40
41
  await transport.ready(observeStartup);
41
42
  return transport;
42
43
  },
43
44
  };
44
45
 
46
+ /**
47
+ * Refuses a Host Fork that has no path to fork from, before any process work.
48
+ *
49
+ * The guard sits here and not at the spawn gate, because a replay legitimately
50
+ * holds no copy: it never spawns pi at all. Only a live open is a real `pi`
51
+ * process. A recorded `sessionFile` exempts the open: a resume continues a
52
+ * recorded Host Fork with `--session`, which is not a fork (ADR-0068).
53
+ */
54
+ function assertHostForkSource(options: OpenOptions): void {
55
+ if (options.origin !== "host-fork") return;
56
+ if (options.forkSession !== undefined || options.sessionFile !== undefined) return;
57
+ throw new YaagError(
58
+ "FORK_REFUSED",
59
+ `agent "${options.name}": this Run holds no host session copy to fork from`,
60
+ options.name,
61
+ );
62
+ }
63
+
45
64
  class LiveTransport implements AgentTransport {
46
65
  model = "";
47
66
 
@@ -23,7 +23,16 @@ import type {
23
23
 
24
24
  export type { AgentProgress } from "../contract/index.ts";
25
25
 
26
- /** The command line for one Agent. */
26
+ /**
27
+ * The command line for one Agent.
28
+ *
29
+ * Which fields may appear here is not decided in this file: the spawn field
30
+ * table (`cassette/spawn-identity.ts`) marks each row `argv: "flag"` or
31
+ * `argv: "never"`, and `open-options-classification.test.ts` fails when a row
32
+ * marked `never` reaches this command line. The direction of the dependency is
33
+ * deliberate: `transport/` must not import `cassette/` at runtime, so the test
34
+ * is the reader of the table, not this function.
35
+ */
27
36
  export function piCommand(options: OpenOptions, toolProbeExtensionPath?: string): string[] {
28
37
  const cmd = ["pi", "--mode", "rpc"];
29
38
  if (options.model) cmd.push("--model", options.model);
@@ -7,6 +7,7 @@ import type {
7
7
  TokenBreakdown,
8
8
  } from "../contract/index.ts";
9
9
  import type { AskLimitOutcome, AskStalledOutcome } from "../errors.ts";
10
+ import type { SpawnOrigin } from "../events.ts";
10
11
  import type { RecordedSpawnSelection } from "../model/index.ts";
11
12
 
12
13
  /**
@@ -148,15 +149,12 @@ export interface AskPlayback {
148
149
  readonly settles?: false;
149
150
  /**
150
151
  * The recorded Ask parked on `request_user_input` and this resume holds no
151
- * answer for it (ADR-0023). The Ask re-opens the same Question and parks
152
- * again, so the Run pauses with it still open.
152
+ * answer for it (ADR-0023). The playback reports only which Question this Ask
153
+ * is parked on: the question text lives in the run block of the Checkpoint,
154
+ * not in the recorded frames (ADR-0022). The Ask parks again, so the Run
155
+ * pauses with the Question still open.
153
156
  */
154
- readonly parked?: {
155
- readonly toolCallId: string;
156
- readonly questionId: string;
157
- readonly question: string;
158
- readonly context?: string;
159
- };
157
+ readonly parked?: { readonly toolCallId: string; readonly questionId: string };
160
158
  }
161
159
 
162
160
  /** One Agent, as the layer above sees it. */
@@ -259,7 +257,13 @@ export interface OpenOptions {
259
257
  /** Resumes an existing pi session, translated to `--session <path>`. */
260
258
  readonly sessionFile?: string;
261
259
  /** How the Agent came to be; absent means an ordinary spawn. Spawn identity. */
262
- readonly origin?: "fork";
260
+ readonly origin?: SpawnOrigin;
261
+ /**
262
+ * Identity of the Host Session conversation a host-fork was taken from.
263
+ * Spawn identity: the Cassette records it and a replay compares it. It never
264
+ * becomes argv; the copy path pi forks from is `forkSession` (ADR-0068).
265
+ */
266
+ readonly hostHash?: string;
263
267
  /** Name of the Agent this one was forked from. Spawn identity; never argv. */
264
268
  readonly forkOf?: string;
265
269
  /** Settled Asks of the fork source at the fork point. Spawn identity. */
package/src/types.ts CHANGED
@@ -11,6 +11,7 @@ export type {
11
11
  CompactionResult,
12
12
  ForkOptions,
13
13
  Handle,
14
+ HostSource,
14
15
  LiteralPromptText,
15
16
  ModelError,
16
17
  PromptAudience,
@@ -1,101 +0,0 @@
1
- import type { CassetteRecorder, CassetteSink } from "./cassette.ts";
2
- import { publishCassette } from "./cassette-publish.ts";
3
- import {
4
- ensureCheckpointDirectory,
5
- type RunIdentity,
6
- writeRecordingDiagnostic,
7
- } from "./run-checkpoint.ts";
8
-
9
- /**
10
- * Publishes the Run's in-progress Checkpoint (ADR-0031).
11
- *
12
- * Each flush rewrites the full collected Cassette to the Run's destination with
13
- * the same atomic write a settled Checkpoint uses, and states the outcome
14
- * `interrupted`. Flushes never reject: a failed one writes a diagnostic, and the
15
- * next Ask boundary tries again.
16
- */
17
- export interface CheckpointFlusher {
18
- /** Requests a publication; returns at once. Concurrent requests coalesce. */
19
- flush(): void;
20
- /** Resolves when no publication is in flight, and stops accepting new ones. */
21
- quiesce(): Promise<void>;
22
- }
23
-
24
- export interface CheckpointFlushOptions {
25
- /** Read at each flush; its current content becomes the artifact. */
26
- readonly collector: CassetteSink;
27
- /** Explicit `--record` destination, or undefined when the Run only checkpoints. */
28
- readonly record: string | undefined;
29
- /** Where the in-progress artifact lives; fixed at Run start. */
30
- readonly destination: string;
31
- readonly identity: RunIdentity;
32
- }
33
-
34
- export function createCheckpointFlusher(options: CheckpointFlushOptions): CheckpointFlusher {
35
- let active: Promise<void> | null = null;
36
- let requested = false;
37
- let stopped = false;
38
-
39
- const publish = async (): Promise<void> => {
40
- try {
41
- await ensureCheckpointDirectory(options.record, options.destination);
42
- await publishCassette(
43
- options.destination,
44
- options.collector.cassette({ outcome: "interrupted", ...options.identity }),
45
- );
46
- } catch (error) {
47
- // Losing this boundary costs one Ask of restorability; failing the Run
48
- // would cost the whole Run (ADR-0031).
49
- writeRecordingDiagnostic(error);
50
- }
51
- };
52
-
53
- // Only one publication runs at a time, so two Asks settling together cannot
54
- // interleave two writes onto one destination. A request that arrives during a
55
- // write is folded into exactly one follow-up write.
56
- const pump = async (): Promise<void> => {
57
- while (requested && !stopped) {
58
- requested = false;
59
- await publish();
60
- }
61
- active = null;
62
- };
63
-
64
- return {
65
- flush: (): void => {
66
- if (stopped) return;
67
- requested = true;
68
- active ??= pump();
69
- },
70
- quiesce: async (): Promise<void> => {
71
- stopped = true;
72
- while (active !== null) await active;
73
- },
74
- };
75
- }
76
-
77
- /**
78
- * Wraps a sink so every Ask boundary publishes the Checkpoint: an Agent opened,
79
- * an Ask begun, an Ask finished, an Agent closed (ADR-0031).
80
- */
81
- export function flushingSink(sink: CassetteSink, flusher: CheckpointFlusher): CassetteSink {
82
- return {
83
- cassette: (run) => sink.cassette(run),
84
- reserve: (options): CassetteRecorder => {
85
- const recorder = sink.reserve(options);
86
- const boundary =
87
- <Args extends unknown[]>(record: (...args: Args) => void) =>
88
- (...args: Args): void => {
89
- record(...args);
90
- flusher.flush();
91
- };
92
- return {
93
- ...recorder,
94
- opened: boundary(recorder.opened),
95
- beginAsk: boundary(recorder.beginAsk),
96
- finishAsk: boundary(recorder.finishAsk),
97
- closed: boundary(recorder.closed),
98
- };
99
- },
100
- };
101
- }