@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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@yaag/runtime",
3
- "version": "0.26.0",
3
+ "version": "0.27.0",
4
4
  "publishConfig": {
5
5
  "access": "public"
6
6
  },
@@ -1,5 +1,5 @@
1
1
  import type { Static, TSchema } from "typebox";
2
- import type { EffectiveAskOptions } from "../ask/index.ts";
2
+ import type { AskTiming, EffectiveAskOptions } from "../ask/index.ts";
3
3
  import { exchangeAsk } from "../ask/index.ts";
4
4
  import { REPORT_RESULT_WRAP_UP, ReportResultTool, wrapUpMessage } from "../ask-contract/index.ts";
5
5
  import type { AskAdmission, AskInFlight, AskSettled } from "../control/index.ts";
@@ -55,12 +55,8 @@ export interface AgentOptions {
55
55
  readonly askDefaults?: AskOptions;
56
56
  /** Definition identity recorded on its Asks, outside replay identity. */
57
57
  readonly definitionName?: string;
58
- /** Test-only override for the fixed duration-limit grace. */
59
- readonly askLimitGraceMs?: number;
60
- /** Test-only override for the bounded wait for `agent_settled` after an idle abort. */
61
- readonly idleAbortSettleMs?: number;
62
- /** Test-only override for the bounded wait for the Stall Watchdog probe. */
63
- readonly stallProbeSettleMs?: number;
58
+ /** Test-only waits of the Ask Guard's controls; absent in production. */
59
+ readonly timing?: AskTiming;
64
60
  /** Run-scoped Ask gate; a closed gate refuses every later Ask (ADR-0024). */
65
61
  readonly askAdmission?: AskAdmission;
66
62
  /** Run-scoped sink of Agent questions; absent when this Agent cannot ask (ADR-0023). */
@@ -79,9 +75,7 @@ export class Agent implements Handle {
79
75
  readonly #spawnOptions: ResolvedSpawnOptions;
80
76
  readonly #askDefaults: AskOptions;
81
77
  readonly #definitionName: string | undefined;
82
- readonly #askLimitGraceMs: number | undefined;
83
- readonly #idleAbortSettleMs: number | undefined;
84
- readonly #stallProbeSettleMs: number | undefined;
78
+ readonly #timing: AskTiming | undefined;
85
79
  readonly #modelFallback: AgentModelFallback | undefined;
86
80
  #model: string;
87
81
  #candidate: string;
@@ -113,9 +107,7 @@ export class Agent implements Handle {
113
107
  this.#definitionName = options.definitionName;
114
108
  this.#sessionFile = options.sessionFile;
115
109
  this.#fork = options.fork;
116
- this.#askLimitGraceMs = options.askLimitGraceMs;
117
- this.#idleAbortSettleMs = options.idleAbortSettleMs;
118
- this.#stallProbeSettleMs = options.stallProbeSettleMs;
110
+ this.#timing = options.timing;
119
111
  this.#askAdmission = options.askAdmission;
120
112
  this.#questions = options.questions;
121
113
  this.#usage = new AgentUsage((snapshot) =>
@@ -188,9 +180,7 @@ export class Agent implements Handle {
188
180
  },
189
181
  },
190
182
  close: () => void this.close().catch(() => {}),
191
- askLimitGraceMs: this.#askLimitGraceMs,
192
- idleAbortSettleMs: this.#idleAbortSettleMs,
193
- stallProbeSettleMs: this.#stallProbeSettleMs,
183
+ ...(this.#timing === undefined ? {} : { timing: this.#timing }),
194
184
  ...(this.#questions === undefined
195
185
  ? {}
196
186
  : { questions: this.#questions, park: () => inFlight.park() }),
@@ -284,7 +274,18 @@ export class Agent implements Handle {
284
274
  });
285
275
  }
286
276
 
287
- /** Spawns a new Agent from a copy of this Agent's session (ADR-0044). */
277
+ /**
278
+ * Spawns a new Agent from a copy of this Agent's session (ADR-0044).
279
+ *
280
+ * Four refusals, in this order: `FORK_REFUSED` when the Run cannot open a
281
+ * fork at all, `FORK_REFUSED` when the overrides name `fork`, because that
282
+ * verb belongs to `ctx.spawn({ fork: ctx.host })` and never to a fork of an
283
+ * Agent (ADR-0068), `FORK_DURING_ASK` while an Ask is in flight, and
284
+ * `FORK_REFUSED` when the tail of the session is undefined or the Agent
285
+ * holds no session file to copy. The value check comes before the state
286
+ * checks, so a wrong call is refused the same way whatever the Agent is
287
+ * doing.
288
+ */
288
289
  fork(overrides?: ForkOptions): Promise<Handle> {
289
290
  const spawner = this.#fork;
290
291
  if (spawner === undefined) {
@@ -292,6 +293,17 @@ export class Agent implements Handle {
292
293
  agentError(this.name, "FORK_REFUSED", "this Agent's Run cannot open a fork"),
293
294
  );
294
295
  }
296
+ // A Host Source is a spawn verb, not a fork override (ADR-0068). The key is
297
+ // absent from `ForkOptions`, so it can only arrive untyped.
298
+ if (overrides !== undefined && typeof overrides === "object" && "fork" in overrides) {
299
+ return Promise.reject(
300
+ agentError(
301
+ this.name,
302
+ "FORK_REFUSED",
303
+ "handle.fork() forks this Agent — a Host Source belongs to ctx.spawn({ fork })",
304
+ ),
305
+ );
306
+ }
295
307
  if (this.#busy) {
296
308
  return Promise.reject(
297
309
  agentError(this.name, "FORK_DURING_ASK", "an Ask is in flight — fork between Asks"),
package/src/agent/fork.ts CHANGED
@@ -6,6 +6,7 @@ import type {
6
6
  ResolvedSpawnOptions,
7
7
  SpawnOptions,
8
8
  } from "../types.ts";
9
+ import { withoutForkVerbs } from "./host-fork.ts";
9
10
 
10
11
  /** What one Agent hands the spawn gate when it is forked (ADR-0044). */
11
12
  export interface ForkSource {
@@ -26,14 +27,32 @@ export interface ForkSource {
26
27
  /** Opens one fork. The spawn gate owns it, so a fork walks the normal spawn path. */
27
28
  export type ForkSpawner = (source: ForkSource, overrides?: ForkOptions) => Promise<Handle>;
28
29
 
29
- /** Spawn identity and launch facts that only a fork carries. */
30
- export interface ForkIdentity {
31
- readonly forkOf: string;
32
- readonly forkAsks: number;
33
- /** The session pi copies with `--fork`; machine-specific, never identity. */
34
- readonly forkSession: string;
35
- readonly worktreeFrom?: WorktreeResolution;
36
- }
30
+ /**
31
+ * Spawn identity and launch facts that only a fork carries.
32
+ *
33
+ * The two fork kinds are one union, so no site can build a half fork: an Agent
34
+ * fork names its source Agent and the Asks it had settled, while a Host Fork
35
+ * names neither and carries the Host Session identity instead (ADR-0068).
36
+ */
37
+ export type ForkIdentity =
38
+ | {
39
+ readonly kind: "agent";
40
+ readonly forkOf: string;
41
+ readonly forkAsks: number;
42
+ /** The session pi copies with `--fork`; machine-specific, never identity. */
43
+ readonly forkSession: string;
44
+ readonly worktreeFrom?: WorktreeResolution;
45
+ }
46
+ | {
47
+ readonly kind: "host";
48
+ /**
49
+ * The copy of the Host Session pi forks with `--fork`. Absent when the
50
+ * Run holds no copy — a replay or a resume reconstructed its Host Source.
51
+ */
52
+ readonly forkSession?: string;
53
+ /** SHA-256 of the Host Session bytes as read; spawn identity (ADR-0068). */
54
+ readonly hostHash: string;
55
+ };
37
56
 
38
57
  /** One fork request: what to spawn, whose child it is, and whether to compact it. */
39
58
  export interface ForkRequest {
@@ -58,9 +77,15 @@ export interface ForkRequest {
58
77
  *
59
78
  * Inheritance is verbatim, with two deliberate exceptions: `name` is dropped,
60
79
  * so the child gets a fresh auto-name unless the overrides give it one, and
61
- * `compact` never reaches the spawn options, because it is a fork verb rather
62
- * than a property of the Agent. `askDefaults` travels beside the spawn
63
- * options, as on every spawn path, and an explicit one replaces the source's.
80
+ * neither fork verb reaches the spawn options, because `fork` and `compact`
81
+ * are verbs of the spawn rather than properties of the Agent (ADR-0068).
82
+ * The rule holds on both sides: the spawn gate strips both verbs before the
83
+ * render and `withSelection` strips them again, so a source cannot carry one
84
+ * to inherit, and `withoutForkVerbs` here drops an overridden one. `compact`
85
+ * travels as a field of the request instead, and an untyped `fork` is refused
86
+ * by `handle.fork()` above this function.
87
+ * `askDefaults` travels beside the spawn options, as on every spawn path, and
88
+ * an explicit one replaces the source's.
64
89
  */
65
90
  export function forkRequest(source: ForkSource, overrides?: ForkOptions): ForkRequest {
66
91
  if (source.sessionFile === undefined) {
@@ -69,10 +94,13 @@ export function forkRequest(source: ForkSource, overrides?: ForkOptions): ForkRe
69
94
  const { name: _name, ...inherited } = source.spawnOptions;
70
95
  const { compact, parent, askDefaults, ...explicit } = overrides ?? {};
71
96
  return {
72
- spawnOptions: { ...inherited, ...stripUndefined(explicit) },
97
+ // A Host Source belongs to `ctx.spawn({ fork })`: `handle.fork()` refuses
98
+ // one, and this strip is the wall behind that refusal.
99
+ spawnOptions: withoutForkVerbs({ ...inherited, ...stripUndefined(explicit) }),
73
100
  parent: parent ?? source.handle,
74
101
  askDefaults: askDefaults ?? source.askDefaults,
75
102
  fork: {
103
+ kind: "agent",
76
104
  forkOf: source.name,
77
105
  forkAsks: source.settledAsks,
78
106
  forkSession: source.sessionFile,
@@ -0,0 +1,85 @@
1
+ /**
2
+ * The Host Fork branch of the spawn gate: `ctx.spawn({ fork: ctx.host })`
3
+ * (ADR-0068).
4
+ *
5
+ * A Host Fork walks the ordinary spawn path. This module does two things and
6
+ * nothing else: it reads the Host Source a program handed back into the fork
7
+ * facts the open path already understands, and it refuses every other use of
8
+ * `fork` and `compact` before any transport work starts.
9
+ *
10
+ * Neither key may reach the rendered, resolved or recorded spawn options — the
11
+ * peeked request is what a resume compares against the recorded spawn — so the
12
+ * open path strips both, and this module is the only reader of them.
13
+ */
14
+ import { YaagError } from "../errors.ts";
15
+ import type { SpawnOptions } from "../types.ts";
16
+ import type { ForkIdentity } from "./fork.ts";
17
+
18
+ /** The Host Source as the Run built it; the brand itself is type-only. */
19
+ interface RuntimeHostSource {
20
+ readonly kind: "host";
21
+ /** Absent when the Run holds no copy: a replayed or resumed Host Source. */
22
+ readonly sessionFile?: string;
23
+ readonly hostHash: string;
24
+ }
25
+
26
+ /** What the spawn gate reads out of one options object. */
27
+ export interface HostForkRequest {
28
+ /** The fork facts, absent for an ordinary spawn. */
29
+ readonly fork?: ForkIdentity;
30
+ /** The compaction the sugar runs after the Agent opened (ADR-0043). */
31
+ readonly compact?: boolean | string;
32
+ }
33
+
34
+ /**
35
+ * Reads the Host Fork request of one spawn.
36
+ *
37
+ * Refuses with `FORK_REFUSED` when `fork` is present but is not a Host Source
38
+ * this Run prepared — `undefined` slipping past the type, or a foreign object —
39
+ * and with `OPTIONS_CONFLICT` when `compact` is given without `fork`, because
40
+ * compaction is a fork verb and not a property of an Agent.
41
+ */
42
+ export function hostForkRequest(options: SpawnOptions): HostForkRequest {
43
+ const holdsFork = "fork" in options;
44
+ const compact = options.compact;
45
+ if (!holdsFork) {
46
+ if (compact !== undefined) {
47
+ throw new YaagError("OPTIONS_CONFLICT", "cannot use compact without fork");
48
+ }
49
+ return {};
50
+ }
51
+ const source = options.fork;
52
+ if (!isRuntimeHostSource(source)) {
53
+ throw new YaagError(
54
+ "FORK_REFUSED",
55
+ 'spawn option "fork" must be the Run\'s ctx.host — a program cannot build one',
56
+ );
57
+ }
58
+ return {
59
+ fork: {
60
+ kind: "host",
61
+ ...(source.sessionFile === undefined ? {} : { forkSession: source.sessionFile }),
62
+ hostHash: source.hostHash,
63
+ },
64
+ ...(compact === undefined ? {} : { compact }),
65
+ };
66
+ }
67
+
68
+ /** The spawn options without the two fork verbs, which no consumer may see. */
69
+ export function withoutForkVerbs(options: SpawnOptions): SpawnOptions {
70
+ const { fork: _fork, compact: _compact, ...rest } = options;
71
+ return rest;
72
+ }
73
+
74
+ function isRuntimeHostSource(value: unknown): value is RuntimeHostSource {
75
+ return (
76
+ typeof value === "object" &&
77
+ value !== null &&
78
+ "kind" in value &&
79
+ value.kind === "host" &&
80
+ // The copy path is optional, but a present one must still be a path.
81
+ (!("sessionFile" in value) || typeof value.sessionFile === "string") &&
82
+ "hostHash" in value &&
83
+ typeof value.hostHash === "string"
84
+ );
85
+ }
@@ -3,7 +3,7 @@
3
3
  * Definition, with its override validation. Separate from `spawn.ts` so the
4
4
  * profiled path can reuse it without a cycle.
5
5
  */
6
- import type { SpawnOptions, SpawnOverrides } from "../types.ts";
6
+ import type { HostSource, SpawnOptions, SpawnOverrides } from "../types.ts";
7
7
  import { type AgentDefinition, agentDefinitionConfig, isAgentDefinition } from "./define-agent.ts";
8
8
  import type { OpenAgentRequest } from "./spawn-open.ts";
9
9
 
@@ -26,7 +26,7 @@ interface ValidatedOverrides {
26
26
  * `askDefaults` leaves the spawn options and travels beside them, so it never
27
27
  * enters the recorded spawn options or the Cassette.
28
28
  * Throws a TypeError when the overrides are not an object, when they name a
29
- * key that is not `name`, `cwd`, `worktree` or `parent`, or when one of those
29
+ * key that is not `name`, `cwd`, `worktree`, `parent`, `fork` or `compact`, or when one of those
30
30
  * carries the wrong type. `parent` stays raw: `resolveParent` checks it.
31
31
  */
32
32
  export function resolveRequest(
@@ -45,6 +45,10 @@ export function resolveRequest(
45
45
  name: topology.name ?? name,
46
46
  ...(topology.cwd === undefined ? {} : { cwd: topology.cwd }),
47
47
  ...(topology.worktree === undefined ? {} : { worktree: topology.worktree }),
48
+ // Presence, not value: `ctx.spawn(def, { fork: undefined })` must reach the
49
+ // spawn gate and be refused there, exactly as the plain-options path is.
50
+ ...("fork" in topology ? { fork: topology.fork } : {}),
51
+ ...("compact" in topology ? { compact: topology.compact } : {}),
48
52
  },
49
53
  parent,
50
54
  askDefaults,
@@ -61,6 +65,11 @@ function definedFields<T extends object>(policy: T): Partial<T> {
61
65
  return copy;
62
66
  }
63
67
 
68
+ /** The shape a fork source has at runtime; the brand itself is type-only. */
69
+ function isHostSource(value: unknown): value is HostSource {
70
+ return typeof value === "object" && value !== null && "kind" in value && value.kind === "host";
71
+ }
72
+
64
73
  function validateOverrides(overrides: unknown): ValidatedOverrides {
65
74
  if (overrides === undefined) return { topology: {}, parent: undefined };
66
75
  if (typeof overrides !== "object" || overrides === null || Array.isArray(overrides)) {
@@ -69,7 +78,14 @@ function validateOverrides(overrides: unknown): ValidatedOverrides {
69
78
  );
70
79
  }
71
80
  for (const key of Object.keys(overrides)) {
72
- if (key !== "name" && key !== "cwd" && key !== "worktree" && key !== "parent") {
81
+ if (
82
+ key !== "name" &&
83
+ key !== "cwd" &&
84
+ key !== "worktree" &&
85
+ key !== "parent" &&
86
+ key !== "fork" &&
87
+ key !== "compact"
88
+ ) {
73
89
  throw new TypeError(
74
90
  `spawn override "${key}" is not allowed: definitions own policy and spawn overrides own topology`,
75
91
  );
@@ -99,6 +115,25 @@ function validateOverrides(overrides: unknown): ValidatedOverrides {
99
115
  }
100
116
  topology.worktree = value;
101
117
  }
118
+ // Both keys are checked here and then carried into the spawn options, where
119
+ // the spawn gate reads them: `host-fork.ts` turns them into the Host Fork
120
+ // facts or refuses them, and `spawn-open.ts` strips both above the prompt
121
+ // render, so neither reaches a rendered, resolved or recorded spawn
122
+ // request (ADR-0068). The check here is a shape check only: a wrong-typed
123
+ // value is a TypeError, and a well-shaped foreign object is FORK_REFUSED
124
+ // at the gate.
125
+ if (key === "fork") {
126
+ if (value !== undefined && !isHostSource(value)) {
127
+ throw new TypeError('spawn override "fork" must be a fork source when present');
128
+ }
129
+ topology.fork = value;
130
+ }
131
+ if (key === "compact") {
132
+ if (value !== undefined && typeof value !== "boolean" && typeof value !== "string") {
133
+ throw new TypeError('spawn override "compact" must be a boolean or a string when present');
134
+ }
135
+ topology.compact = value;
136
+ }
102
137
  }
103
138
  return { topology, parent };
104
139
  }
@@ -9,24 +9,21 @@ import {
9
9
  } from "../model/index.ts";
10
10
  import type {
11
11
  AgentTransport,
12
+ OpenOptions,
12
13
  TransportFactory,
13
14
  TransportStartup,
14
- WorktreeResolution,
15
15
  } from "../transport/index.ts";
16
16
  import type { AskOptions, ResolvedSpawnOptions, SpawnOptions } from "../types.ts";
17
17
  import { Agent } from "./agent.ts";
18
18
  import { uniqueAgentName } from "./agent-names.ts";
19
19
  import { assertAskUserTools } from "./ask-user-capability.ts";
20
20
  import type { ForkIdentity, ForkSpawner } from "./fork.ts";
21
+ import { withoutForkVerbs } from "./host-fork.ts";
21
22
  import type { SpawnDependencies } from "./spawn.ts";
22
23
  import { resolveSpawnExtensions } from "./spawn-extensions.ts";
23
24
  import { resolveParent } from "./spawn-parent.ts";
24
- import {
25
- openRequest,
26
- type RenderedSpawnOptions,
27
- renderPolicyPrompt,
28
- withSelection,
29
- } from "./spawn-request.ts";
25
+ import { createSpawnPlan } from "./spawn-plan.ts";
26
+ import { type RenderedSpawnOptions, renderPolicyPrompt } from "./spawn-request.ts";
30
27
 
31
28
  /** One request the open path serves: a plain spawn, or a fork of another Agent. */
32
29
  export interface OpenAgentRequest {
@@ -39,7 +36,7 @@ export interface OpenAgentRequest {
39
36
  readonly definitionName: string | undefined;
40
37
  /** The prompt is a fork's inherited rendered text, not author-written. */
41
38
  readonly inheritedPrompt?: boolean;
42
- /** Present only for a fork; adds `origin: "fork"` and the `--fork` source. */
39
+ /** Present only for a fork; supplies the origin and the `--fork` source. */
43
40
  readonly fork?: ForkIdentity;
44
41
  /**
45
42
  * Id of the active Profile, on a profiled spawn only. It rides the
@@ -76,7 +73,17 @@ export interface OpenAgentContext extends SpawnDependencies {
76
73
  * the Run's own machinery reaps what it opens, and `close()` lives below the
77
74
  * author surface (ADR-0022).
78
75
  */
79
- export async function openAgent(deps: OpenAgentContext, request: OpenAgentRequest): Promise<Agent> {
76
+ export async function openAgent(
77
+ deps: OpenAgentContext,
78
+ incoming: OpenAgentRequest,
79
+ ): Promise<Agent> {
80
+ // The two fork verbs are read by the spawn gate and stripped here, above the
81
+ // prompt render: `rendered` feeds the peeked request a resume compares with
82
+ // the recorded spawn, so neither key may travel past this line (ADR-0039).
83
+ const request: OpenAgentRequest = {
84
+ ...incoming,
85
+ spawnOptions: withoutForkVerbs(incoming.spawnOptions),
86
+ };
80
87
  const cwd = resolve(request.spawnOptions.cwd ?? process.cwd());
81
88
  const name = uniqueAgentName(request.spawnOptions.name, deps.agents.length, deps.taken);
82
89
  // Resolved before any transport work, so a bad Parent Link costs nothing.
@@ -107,62 +114,32 @@ export async function openAgent(deps: OpenAgentContext, request: OpenAgentReques
107
114
  if (error instanceof YaagError) throw error;
108
115
  throw new YaagError("SPAWN_FAILED", `agent "${name}": ${String(error)}`, name);
109
116
  });
110
- // One local for both open sites, so the launch arguments and the recorded
111
- // identity cannot drift apart.
112
- const extensionFields =
113
- extensions === undefined
114
- ? {}
115
- : {
116
- resolvedExtensionPaths: extensions.resolvedPaths,
117
- declaredExtensions: extensions.declared,
118
- };
119
- const forkFields =
120
- request.fork === undefined
121
- ? {}
122
- : {
123
- origin: "fork" as const,
124
- forkOf: request.fork.forkOf,
125
- forkAsks: request.fork.forkAsks,
126
- forkSession: request.fork.forkSession,
127
- ...(request.fork.worktreeFrom === undefined
128
- ? {}
129
- : { worktreeFrom: request.fork.worktreeFrom }),
130
- };
117
+ // One plan for both open sites, so the launch arguments and the recorded
118
+ // identity cannot drift apart: the peek and every attempt differ only in the
119
+ // settled model and thinking.
120
+ const plan = createSpawnPlan({
121
+ name,
122
+ runName: deps.runName,
123
+ cwd,
124
+ rendered,
125
+ ...(extensions === undefined ? {} : { extensions }),
126
+ ...(request.fork === undefined ? {} : { fork: request.fork }),
127
+ ...(parent === undefined ? {} : { parent }),
128
+ sessionDir: deps.sessionDir,
129
+ ...(request.sessionFile === undefined ? {} : { sessionFile: request.sessionFile }),
130
+ });
131
131
  const attempt = async (
132
132
  selection: ModelSelection,
133
133
  ): Promise<{ opened: OpenedTransport; spawnOptions: ResolvedSpawnOptions }> => {
134
- const settled = withSelection(rendered, selection);
134
+ const settled = plan.attempt(selection);
135
135
  return {
136
- opened: await openTransport({
137
- factory: deps.factory,
138
- name,
139
- runName: deps.runName,
140
- cwd,
141
- spawnOptions: settled,
142
- ...extensionFields,
143
- ...forkFields,
144
- ...(parent === undefined ? {} : { parent }),
145
- sessionDir: deps.sessionDir,
146
- ...(request.sessionFile === undefined ? {} : { sessionFile: request.sessionFile }),
147
- }),
148
- spawnOptions: settled,
136
+ opened: await openTransport(deps.factory, name, settled.request),
137
+ spawnOptions: settled.spawnOptions,
149
138
  };
150
139
  };
151
140
  // The peek must stay in the same synchronous block as the first open: a
152
141
  // Cassette-backed factory claims Agents in open order (ADR-0013).
153
- const recorded = deps.factory.recordedSpawn?.(
154
- openRequest({
155
- name,
156
- runName: deps.runName,
157
- cwd,
158
- spawnOptions: rendered,
159
- ...extensionFields,
160
- ...forkFields,
161
- ...(parent === undefined ? {} : { parent }),
162
- sessionDir: deps.sessionDir,
163
- ...(request.sessionFile === undefined ? {} : { sessionFile: request.sessionFile }),
164
- }),
165
- );
142
+ const recorded = deps.factory.recordedSpawn?.(plan.peek());
166
143
  // A Cassette-backed spawn adopts the recorded resolved selection and skips
167
144
  // the loop, so a replayed Run emits no spawn-time fallback (ADR-0039).
168
145
  const adopted =
@@ -220,7 +197,7 @@ export async function openAgent(deps: OpenAgentContext, request: OpenAgentReques
220
197
  ...(sessionFile === undefined ? {} : { sessionFile }),
221
198
  ...(thinking === undefined ? {} : { thinking }),
222
199
  ...(parent === undefined ? {} : { parent }),
223
- ...(request.fork === undefined ? {} : { origin: "fork" as const }),
200
+ ...(plan.origin === undefined ? {} : { origin: plan.origin }),
224
201
  ...(request.profile === undefined
225
202
  ? {}
226
203
  : { profile: request.profile, role: request.role ?? [] }),
@@ -242,60 +219,23 @@ function isSpawnFailure(error: unknown): error is YaagError {
242
219
  return error instanceof YaagError && error.code === "SPAWN_FAILED";
243
220
  }
244
221
 
245
- interface OpenTransportOptions {
246
- readonly factory: TransportFactory;
247
- readonly name: string;
248
- /** The Run name; the peek and the open must pass the same one (ADR-0013). */
249
- readonly runName: string;
250
- readonly cwd: string;
251
- readonly spawnOptions: ResolvedSpawnOptions;
252
- readonly resolvedExtensionPaths?: readonly string[];
253
- readonly declaredExtensions?: readonly string[];
254
- readonly parent?: string;
255
- readonly origin?: "fork";
256
- readonly forkOf?: string;
257
- readonly forkAsks?: number;
258
- readonly forkSession?: string;
259
- readonly worktreeFrom?: WorktreeResolution;
260
- readonly sessionDir: string | undefined;
261
- /** An existing pi session to open on; never spawn identity (ADR-0022). */
262
- readonly sessionFile?: string;
263
- }
264
-
265
222
  interface OpenedTransport {
266
223
  readonly transport: AgentTransport;
267
224
  readonly startup: TransportStartup;
268
225
  }
269
226
 
270
- async function openTransport(options: OpenTransportOptions): Promise<OpenedTransport> {
227
+ /** Opens one built request, and turns any foreign failure into a spawn failure. */
228
+ async function openTransport(
229
+ factory: TransportFactory,
230
+ name: string,
231
+ request: OpenOptions,
232
+ ): Promise<OpenedTransport> {
271
233
  const startup: TransportStartup = {};
272
234
  try {
273
- const transport = await options.factory.open(
274
- openRequest({
275
- name: options.name,
276
- runName: options.runName,
277
- cwd: options.cwd,
278
- spawnOptions: options.spawnOptions,
279
- ...(options.resolvedExtensionPaths === undefined
280
- ? {}
281
- : { resolvedExtensionPaths: options.resolvedExtensionPaths }),
282
- ...(options.declaredExtensions === undefined
283
- ? {}
284
- : { declaredExtensions: options.declaredExtensions }),
285
- ...(options.parent === undefined ? {} : { parent: options.parent }),
286
- ...(options.origin === undefined ? {} : { origin: options.origin }),
287
- ...(options.forkOf === undefined ? {} : { forkOf: options.forkOf }),
288
- ...(options.forkAsks === undefined ? {} : { forkAsks: options.forkAsks }),
289
- ...(options.forkSession === undefined ? {} : { forkSession: options.forkSession }),
290
- ...(options.worktreeFrom === undefined ? {} : { worktreeFrom: options.worktreeFrom }),
291
- sessionDir: options.sessionDir,
292
- ...(options.sessionFile === undefined ? {} : { sessionFile: options.sessionFile }),
293
- }),
294
- (report) => Object.assign(startup, report),
295
- );
235
+ const transport = await factory.open(request, (report) => Object.assign(startup, report));
296
236
  return { transport, startup };
297
237
  } catch (error) {
298
238
  if (error instanceof YaagError) throw error;
299
- throw new YaagError("SPAWN_FAILED", `agent "${options.name}": ${String(error)}`, options.name);
239
+ throw new YaagError("SPAWN_FAILED", `agent "${name}": ${String(error)}`, name);
300
240
  }
301
241
  }