@yaag/runtime 0.26.0 → 0.28.1

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 (66) hide show
  1. package/package.json +1 -1
  2. package/src/agent/agent-name.ts +22 -0
  3. package/src/agent/agent-names.ts +5 -1
  4. package/src/agent/agent.ts +34 -17
  5. package/src/agent/define-agent.ts +4 -0
  6. package/src/agent/fork.ts +50 -12
  7. package/src/agent/host-fork.ts +85 -0
  8. package/src/agent/index.ts +1 -0
  9. package/src/agent/spawn-definition-request.ts +41 -6
  10. package/src/agent/spawn-open.ts +54 -107
  11. package/src/agent/spawn-parent.ts +64 -0
  12. package/src/agent/spawn-plan.ts +120 -0
  13. package/src/agent/spawn-request.ts +26 -6
  14. package/src/agent/spawn.ts +47 -6
  15. package/src/ask/ask-exchange-options.ts +3 -6
  16. package/src/ask/ask-exchange.ts +48 -108
  17. package/src/ask/ask-guard.ts +207 -0
  18. package/src/ask/ask-timing.ts +12 -0
  19. package/src/ask/index.ts +1 -0
  20. package/src/cassette/cassette-loader.ts +9 -20
  21. package/src/cassette/cassette-schema.ts +11 -1
  22. package/src/cassette/cassette.ts +16 -34
  23. package/src/cassette/checkpoint.ts +306 -0
  24. package/src/cassette/index.ts +16 -7
  25. package/src/cassette/parked-asks.ts +38 -0
  26. package/src/cassette/replay-divergence.ts +7 -102
  27. package/src/cassette/resume-identity.ts +5 -1
  28. package/src/cassette/resume-preconditions.ts +14 -0
  29. package/src/cassette/resume-transport.ts +26 -32
  30. package/src/cassette/run-identity.ts +109 -0
  31. package/src/cassette/session-answer.ts +51 -114
  32. package/src/cassette/spawn-identity.ts +328 -0
  33. package/src/contract/error-codes.ts +4 -0
  34. package/src/contract/group.ts +38 -0
  35. package/src/contract/index.ts +2 -0
  36. package/src/contract/spawn-options.ts +48 -7
  37. package/src/error-factories.ts +8 -0
  38. package/src/events.ts +22 -2
  39. package/src/index.ts +7 -0
  40. package/src/pi-session/append-tool-result.ts +165 -0
  41. package/src/pi-session/index.ts +30 -0
  42. package/src/pi-session/pi-session-error.ts +34 -0
  43. package/src/pi-session/session-copy.ts +113 -0
  44. package/src/pi-session/session-entries.ts +130 -0
  45. package/src/public-api.ts +2 -0
  46. package/src/question-summary/index.ts +4 -8
  47. package/src/question-summary/summarize-question.ts +1 -1
  48. package/src/question-summary/summary-policy.ts +5 -2
  49. package/src/run/agent-questions.ts +82 -0
  50. package/src/run/answers.ts +22 -1
  51. package/src/run/groups.ts +111 -0
  52. package/src/run/host-session.ts +233 -0
  53. package/src/run/index.ts +8 -0
  54. package/src/run/run-context.ts +15 -0
  55. package/src/run/run.ts +208 -182
  56. package/src/summary/index.ts +1 -0
  57. package/src/summary/summary-agent.ts +6 -0
  58. package/src/summary/summary-group.ts +31 -0
  59. package/src/summary/summary.ts +12 -0
  60. package/src/transport/live-transport.ts +19 -0
  61. package/src/transport/pi-state.ts +10 -1
  62. package/src/transport/transport.ts +20 -9
  63. package/src/types.ts +3 -0
  64. package/src/cassette/checkpoint-flush.ts +0 -101
  65. package/src/cassette/run-checkpoint.ts +0 -272
  66. package/src/question-summary/session-copy.ts +0 -169
@@ -9,37 +9,39 @@ 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
- import { resolveParent } from "./spawn-parent.ts";
24
- import {
25
- openRequest,
26
- type RenderedSpawnOptions,
27
- renderPolicyPrompt,
28
- withSelection,
29
- } from "./spawn-request.ts";
24
+ import { resolveParentPosition, treeFields } from "./spawn-parent.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 {
33
30
  /** Never carries `parent`: a Handle must not reach the recorded options. */
34
31
  readonly spawnOptions: SpawnOptions;
35
- /** The raw Parent Link option, validated by `resolveParent`. */
32
+ /** The raw Parent Link option, the author's raw Handle or Group, resolved by `resolveParentPosition` inside `openAgent`. */
36
33
  readonly parent: unknown;
34
+ /**
35
+ * The Group path a Fork inherits from its source; an explicit Group `parent`
36
+ * overrides it (ADR-0070).
37
+ */
38
+ readonly group?: string;
37
39
  readonly askDefaults: AskOptions | undefined;
38
40
  /** Definition identity stays separate from a topology-overridden Agent name. */
39
41
  readonly definitionName: string | undefined;
40
42
  /** The prompt is a fork's inherited rendered text, not author-written. */
41
43
  readonly inheritedPrompt?: boolean;
42
- /** Present only for a fork; adds `origin: "fork"` and the `--fork` source. */
44
+ /** Present only for a fork; supplies the origin and the `--fork` source. */
43
45
  readonly fork?: ForkIdentity;
44
46
  /**
45
47
  * Id of the active Profile, on a profiled spawn only. It rides the
@@ -76,11 +78,22 @@ export interface OpenAgentContext extends SpawnDependencies {
76
78
  * the Run's own machinery reaps what it opens, and `close()` lives below the
77
79
  * author surface (ADR-0022).
78
80
  */
79
- export async function openAgent(deps: OpenAgentContext, request: OpenAgentRequest): Promise<Agent> {
81
+ export async function openAgent(
82
+ deps: OpenAgentContext,
83
+ incoming: OpenAgentRequest,
84
+ ): Promise<Agent> {
85
+ // The two fork verbs are read by the spawn gate and stripped here, above the
86
+ // prompt render: `rendered` feeds the peeked request a resume compares with
87
+ // the recorded spawn, so neither key may travel past this line (ADR-0039).
88
+ const request: OpenAgentRequest = {
89
+ ...incoming,
90
+ spawnOptions: withoutForkVerbs(incoming.spawnOptions),
91
+ };
80
92
  const cwd = resolve(request.spawnOptions.cwd ?? process.cwd());
81
93
  const name = uniqueAgentName(request.spawnOptions.name, deps.agents.length, deps.taken);
82
94
  // Resolved before any transport work, so a bad Parent Link costs nothing.
83
- const parent = resolveParent(request.parent, deps.agents);
95
+ const position = resolveParentPosition(request.parent, deps.agents, deps.isGroup);
96
+ const tree = treeFields(position, request.group);
84
97
  const resolution = normalizeModelResolution(request.spawnOptions);
85
98
  // One history per Agent: its spawn loop and every mid-Ask fallback loop
86
99
  // append to it, so a resolver sees every candidate that already failed.
@@ -107,62 +120,32 @@ export async function openAgent(deps: OpenAgentContext, request: OpenAgentReques
107
120
  if (error instanceof YaagError) throw error;
108
121
  throw new YaagError("SPAWN_FAILED", `agent "${name}": ${String(error)}`, name);
109
122
  });
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
- };
123
+ // One plan for both open sites, so the launch arguments and the recorded
124
+ // identity cannot drift apart: the peek and every attempt differ only in the
125
+ // settled model and thinking.
126
+ const plan = createSpawnPlan({
127
+ name,
128
+ runName: deps.runName,
129
+ cwd,
130
+ rendered,
131
+ ...(extensions === undefined ? {} : { extensions }),
132
+ ...(request.fork === undefined ? {} : { fork: request.fork }),
133
+ ...(Object.keys(tree).length === 0 ? {} : { tree }),
134
+ sessionDir: deps.sessionDir,
135
+ ...(request.sessionFile === undefined ? {} : { sessionFile: request.sessionFile }),
136
+ });
131
137
  const attempt = async (
132
138
  selection: ModelSelection,
133
139
  ): Promise<{ opened: OpenedTransport; spawnOptions: ResolvedSpawnOptions }> => {
134
- const settled = withSelection(rendered, selection);
140
+ const settled = plan.attempt(selection);
135
141
  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,
142
+ opened: await openTransport(deps.factory, name, settled.request),
143
+ spawnOptions: settled.spawnOptions,
149
144
  };
150
145
  };
151
146
  // The peek must stay in the same synchronous block as the first open: a
152
147
  // 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
- );
148
+ const recorded = deps.factory.recordedSpawn?.(plan.peek());
166
149
  // A Cassette-backed spawn adopts the recorded resolved selection and skips
167
150
  // the loop, so a replayed Run emits no spawn-time fallback (ADR-0039).
168
151
  const adopted =
@@ -202,6 +185,7 @@ export async function openAgent(deps: OpenAgentContext, request: OpenAgentReques
202
185
  : { modelFallback: { resolution, history, candidate: spawnOptions.model } }),
203
186
  ...(sessionFile === undefined ? {} : { sessionFile }),
204
187
  fork: deps.forkSpawner,
188
+ ...(tree.group === undefined ? {} : { group: tree.group }),
205
189
  ...(deps.askAdmission === undefined ? {} : { askAdmission: deps.askAdmission }),
206
190
  // Only an Agent that may ask gets the sink, so no other Ask can park.
207
191
  ...(deps.questions === undefined || rendered.canAskUser !== true
@@ -219,8 +203,8 @@ export async function openAgent(deps: OpenAgentContext, request: OpenAgentReques
219
203
  ...(branch === undefined ? {} : { branch }),
220
204
  ...(sessionFile === undefined ? {} : { sessionFile }),
221
205
  ...(thinking === undefined ? {} : { thinking }),
222
- ...(parent === undefined ? {} : { parent }),
223
- ...(request.fork === undefined ? {} : { origin: "fork" as const }),
206
+ ...tree,
207
+ ...(plan.origin === undefined ? {} : { origin: plan.origin }),
224
208
  ...(request.profile === undefined
225
209
  ? {}
226
210
  : { profile: request.profile, role: request.role ?? [] }),
@@ -242,60 +226,23 @@ function isSpawnFailure(error: unknown): error is YaagError {
242
226
  return error instanceof YaagError && error.code === "SPAWN_FAILED";
243
227
  }
244
228
 
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
229
  interface OpenedTransport {
266
230
  readonly transport: AgentTransport;
267
231
  readonly startup: TransportStartup;
268
232
  }
269
233
 
270
- async function openTransport(options: OpenTransportOptions): Promise<OpenedTransport> {
234
+ /** Opens one built request, and turns any foreign failure into a spawn failure. */
235
+ async function openTransport(
236
+ factory: TransportFactory,
237
+ name: string,
238
+ request: OpenOptions,
239
+ ): Promise<OpenedTransport> {
271
240
  const startup: TransportStartup = {};
272
241
  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
- );
242
+ const transport = await factory.open(request, (report) => Object.assign(startup, report));
296
243
  return { transport, startup };
297
244
  } catch (error) {
298
245
  if (error instanceof YaagError) throw error;
299
- throw new YaagError("SPAWN_FAILED", `agent "${options.name}": ${String(error)}`, options.name);
246
+ throw new YaagError("SPAWN_FAILED", `agent "${name}": ${String(error)}`, name);
300
247
  }
301
248
  }
@@ -1,3 +1,4 @@
1
+ import type { Group } from "../contract/index.ts";
1
2
  import type { Agent } from "./agent.ts";
2
3
 
3
4
  /**
@@ -8,6 +9,10 @@ import type { Agent } from "./agent.ts";
8
9
  * spawn resolved. Liveness is deliberately not checked — a cleanly exited Agent
9
10
  * remains a valid parent, because the link states tree position, not a
10
11
  * dependency on a live process.
12
+ *
13
+ * This is the one Handle lookup of the Run: `resolveParentPosition` below
14
+ * builds on it for the spawn position, and the Group registry calls it for
15
+ * `ctx.group({ parent })` (ADR-0070).
11
16
  */
12
17
  export function resolveParent(parent: unknown, agents: readonly Agent[]): string | undefined {
13
18
  if (parent === undefined) return undefined;
@@ -19,3 +24,62 @@ export function resolveParent(parent: unknown, agents: readonly Agent[]): string
19
24
  }
20
25
  return known.name;
21
26
  }
27
+
28
+ /**
29
+ * Where a spawn sits in the Run tree (ADR-0070).
30
+ *
31
+ * Two variants: the parent Agent, and a Group, which is a tree position with no
32
+ * process.
33
+ */
34
+ export type ParentPosition =
35
+ | { readonly kind: "agent"; readonly name: string }
36
+ | { readonly kind: "group"; readonly path: string };
37
+
38
+ /** The tree fields one spawn stamps: an Agent parent, a Group, or neither. */
39
+ export interface SpawnTreeFields {
40
+ readonly parent?: string;
41
+ readonly group?: string;
42
+ }
43
+
44
+ /**
45
+ * Resolves a Parent Link to its tree position, or `undefined` when unset.
46
+ *
47
+ * A Group of this Run resolves to a Group position; everything else goes to the
48
+ * Handle lookup, so a foreign `{ kind: "group" }` literal is refused exactly as
49
+ * `ctx.group({ parent })` refuses it.
50
+ */
51
+ export function resolveParentPosition(
52
+ parent: unknown,
53
+ agents: readonly Agent[],
54
+ isGroup?: (value: unknown) => value is Group,
55
+ ): ParentPosition | undefined {
56
+ if (isGroup?.(parent) === true) return { kind: "group", path: parent.path };
57
+ const name = resolveParent(parent, agents);
58
+ return name === undefined ? undefined : { kind: "agent", name };
59
+ }
60
+
61
+ /**
62
+ * Projects a tree position onto the fields a spawn carries.
63
+ *
64
+ * The one place a position becomes `parent`/`group`, shared by the
65
+ * `agent_spawn` event and the open options, so a new variant lands in both at
66
+ * once. A Fork passes its source's Group as `inheritedGroup`: an explicit Group
67
+ * position wins over it, and it never merges.
68
+ */
69
+ export function treeFields(
70
+ position: ParentPosition | undefined,
71
+ inheritedGroup?: string,
72
+ ): SpawnTreeFields {
73
+ const inherited = inheritedGroup === undefined ? {} : { group: inheritedGroup };
74
+ if (position === undefined) return inherited;
75
+ switch (position.kind) {
76
+ case "agent":
77
+ return { parent: position.name, ...inherited };
78
+ case "group":
79
+ return { group: position.path };
80
+ default: {
81
+ const never: never = position;
82
+ throw new TypeError(`unknown parent position: ${JSON.stringify(never)}`);
83
+ }
84
+ }
85
+ }
@@ -0,0 +1,120 @@
1
+ /**
2
+ * The Spawn Plan: the one open request built for one spawn.
3
+ *
4
+ * The peek a Cassette-backed factory reads and every model attempt read from
5
+ * this value. Before it, the same field list was spread at three sites and
6
+ * mirrored by a fourth type, and only a comment said the three must agree.
7
+ */
8
+ import type { SpawnOrigin } from "../events.ts";
9
+ import type { ModelSelection } from "../model/index.ts";
10
+ import type { OpenOptions } from "../transport/index.ts";
11
+ import type { ResolvedSpawnOptions } from "../types.ts";
12
+ import type { ForkIdentity } from "./fork.ts";
13
+ import type { SpawnTreeFields } from "./spawn-parent.ts";
14
+ import {
15
+ type OpenRequestOptions,
16
+ openRequest,
17
+ type RenderedSpawnOptions,
18
+ withSelection,
19
+ } from "./spawn-request.ts";
20
+
21
+ /** What one spawn knows before a model settles. */
22
+ export interface SpawnPlanInput {
23
+ readonly name: string;
24
+ readonly runName: string;
25
+ readonly cwd: string;
26
+ /** The Prompt Definition, rendered once above the plan (ADR-0064). */
27
+ readonly rendered: RenderedSpawnOptions;
28
+ /** Resolved and declared extension paths, or nothing when the Agent runs none. */
29
+ readonly extensions?: {
30
+ readonly resolvedPaths: readonly string[];
31
+ readonly declared: readonly string[];
32
+ };
33
+ /** Fork facts, present only for a fork of an Agent or of the Host Session. */
34
+ readonly fork?: ForkIdentity;
35
+ /**
36
+ * The resolved tree fields (Parent Link, Group). Neither one ever becomes
37
+ * argv. `parent` and `group` are both spawn identity; neither ever becomes
38
+ * argv (ADR-0070).
39
+ */
40
+ readonly tree?: SpawnTreeFields;
41
+ readonly sessionDir: string | undefined;
42
+ readonly sessionFile?: string;
43
+ }
44
+
45
+ /** One attempt's open request and the settled options the Agent records. */
46
+ export interface SpawnAttempt {
47
+ readonly request: OpenOptions;
48
+ readonly spawnOptions: ResolvedSpawnOptions;
49
+ }
50
+
51
+ /** The open requests of one spawn: the peek, and one per model attempt. */
52
+ export interface SpawnPlan {
53
+ /**
54
+ * The request a Cassette-backed factory peeks at, with the caller's unsettled
55
+ * `model`/`thinking` forms (ADR-0039).
56
+ */
57
+ peek(): OpenOptions;
58
+ /** The origin this spawn records, absent for an ordinary spawn. */
59
+ readonly origin?: SpawnOrigin;
60
+ /** The same request with one settled selection applied, and nothing else changed. */
61
+ attempt(selection: ModelSelection): SpawnAttempt;
62
+ }
63
+
64
+ /**
65
+ * The open-request fields of one fork. An Agent fork names its source; a Host
66
+ * Fork names the Host Session hash instead, and carries no `forkOf`/`forkAsks`.
67
+ */
68
+ function forkFields(
69
+ fork: ForkIdentity,
70
+ origin: SpawnOrigin | undefined,
71
+ ): Partial<OpenRequestOptions> {
72
+ if (fork.kind === "host") {
73
+ return {
74
+ origin,
75
+ ...(fork.forkSession === undefined ? {} : { forkSession: fork.forkSession }),
76
+ hostHash: fork.hostHash,
77
+ };
78
+ }
79
+ return {
80
+ origin,
81
+ forkOf: fork.forkOf,
82
+ forkAsks: fork.forkAsks,
83
+ forkSession: fork.forkSession,
84
+ ...(fork.worktreeFrom === undefined ? {} : { worktreeFrom: fork.worktreeFrom }),
85
+ };
86
+ }
87
+
88
+ /**
89
+ * Builds one spawn's plan. The base below is the single field roster of the
90
+ * open path: `peek()` and `attempt()` differ only in the spawn options they
91
+ * pass, so the peek and every attempt cannot drift apart (ADR-0013).
92
+ */
93
+ export function createSpawnPlan(input: SpawnPlanInput): SpawnPlan {
94
+ const origin: SpawnOrigin | undefined =
95
+ input.fork === undefined ? undefined : input.fork.kind === "host" ? "host-fork" : "fork";
96
+ const base = {
97
+ name: input.name,
98
+ runName: input.runName,
99
+ cwd: input.cwd,
100
+ ...(input.extensions === undefined
101
+ ? {}
102
+ : {
103
+ resolvedExtensionPaths: input.extensions.resolvedPaths,
104
+ declaredExtensions: input.extensions.declared,
105
+ }),
106
+ ...(input.fork === undefined ? {} : forkFields(input.fork, origin)),
107
+ ...(input.tree === undefined ? {} : { tree: input.tree }),
108
+ sessionDir: input.sessionDir,
109
+ ...(input.sessionFile === undefined ? {} : { sessionFile: input.sessionFile }),
110
+ } satisfies Omit<OpenRequestOptions, "spawnOptions">;
111
+
112
+ return {
113
+ ...(origin === undefined ? {} : { origin }),
114
+ peek: () => openRequest({ ...base, spawnOptions: input.rendered }),
115
+ attempt: (selection) => {
116
+ const spawnOptions = withSelection(input.rendered, selection);
117
+ return { request: openRequest({ ...base, spawnOptions }), spawnOptions };
118
+ },
119
+ };
120
+ }
@@ -1,6 +1,7 @@
1
1
  import { REQUEST_USER_INPUT_PROTOCOL } from "../ask-contract/index.ts";
2
2
  import type { SystemPromptAgent } from "../contract/index.ts";
3
3
  import { YaagError } from "../errors.ts";
4
+ import type { SpawnOrigin } from "../events.ts";
4
5
  import type { ModelSelection } from "../model/index.ts";
5
6
  import {
6
7
  assertKnownSentinels,
@@ -13,6 +14,7 @@ import {
13
14
  } from "../system-prompt/index.ts";
14
15
  import type { OpenOptions, WorktreeResolution } from "../transport/index.ts";
15
16
  import type { ResolvedSpawnOptions, SpawnOptions } from "../types.ts";
17
+ import type { SpawnTreeFields } from "./spawn-parent.ts";
16
18
 
17
19
  /** Spawn options whose `systemPrompt`, if set, is already a plain string. */
18
20
  export type RenderedSpawnOptions = Omit<SpawnOptions, "systemPrompt"> & {
@@ -103,13 +105,19 @@ export interface OpenRequestOptions {
103
105
  readonly spawnOptions: RenderedSpawnOptions;
104
106
  readonly resolvedExtensionPaths?: readonly string[];
105
107
  readonly declaredExtensions?: readonly string[];
106
- /** Resolved parent Agent name (Parent Link); spawn identity only, never argv. */
107
- readonly parent?: string;
108
+ /**
109
+ * The resolved tree fields (Parent Link, Group). Neither one ever becomes
110
+ * argv. `parent` and `group` are both spawn identity; neither ever becomes
111
+ * argv (ADR-0070).
112
+ */
113
+ readonly tree?: SpawnTreeFields;
108
114
  /** Fork facts (ADR-0044); the first three are spawn identity, the rest are not. */
109
- readonly origin?: "fork";
115
+ readonly origin?: SpawnOrigin;
110
116
  readonly forkOf?: string;
111
117
  readonly forkAsks?: number;
112
118
  readonly forkSession?: string;
119
+ /** Host Session identity of a Host Fork; a launch field, never argv (ADR-0068). */
120
+ readonly hostHash?: string;
113
121
  readonly worktreeFrom?: WorktreeResolution;
114
122
  readonly sessionDir: string | undefined;
115
123
  /**
@@ -195,11 +203,12 @@ export function openRequest(options: OpenRequestOptions): OpenOptions {
195
203
  ...(options.declaredExtensions === undefined || options.declaredExtensions.length === 0
196
204
  ? {}
197
205
  : { declaredExtensions: options.declaredExtensions }),
198
- ...(options.parent === undefined ? {} : { parent: options.parent }),
206
+ ...(options.tree ?? {}),
199
207
  ...(options.origin === undefined ? {} : { origin: options.origin }),
200
208
  ...(options.forkOf === undefined ? {} : { forkOf: options.forkOf }),
201
209
  ...(options.forkAsks === undefined ? {} : { forkAsks: options.forkAsks }),
202
210
  ...(options.forkSession === undefined ? {} : { forkSession: options.forkSession }),
211
+ ...(options.hostHash === undefined ? {} : { hostHash: options.hostHash }),
203
212
  ...(options.worktreeFrom === undefined ? {} : { worktreeFrom: options.worktreeFrom }),
204
213
  ...(spawnOptions.worktree === true ? { worktree: true as const } : {}),
205
214
  ...(options.sessionDir === undefined ? {} : { sessionDir: options.sessionDir }),
@@ -212,8 +221,19 @@ export function withSelection(
212
221
  options: RenderedSpawnOptions,
213
222
  selection: ModelSelection,
214
223
  ): ResolvedSpawnOptions {
215
- // `parent` is dropped here as well: a Handle must never reach recorded options.
216
- const { model: _model, thinking: _thinking, parent: _parent, ...rest } = options;
224
+ // `parent` is dropped here as well: a Handle **or a Group** must never reach
225
+ // recorded options.
226
+ // `fork` and `compact` are spawn verbs, not properties of the Agent. The spawn
227
+ // gate already strips them before the render; this line is the second wall, so
228
+ // an inherited one cannot travel into a resolved or recorded spawn request.
229
+ const {
230
+ model: _model,
231
+ thinking: _thinking,
232
+ parent: _parent,
233
+ fork: _fork,
234
+ compact: _compact,
235
+ ...rest
236
+ } = options;
217
237
  return {
218
238
  ...rest,
219
239
  ...(selection.model === undefined ? {} : { model: selection.model }),
@@ -6,10 +6,11 @@ import type { ActiveProfile, ProfiledDefinition } from "../profile/index.ts";
6
6
  import { isProfiledDefinition } from "../profile/index.ts";
7
7
  import type { AgentQuestions, RunContext } from "../run/index.ts";
8
8
  import type { TransportFactory } from "../transport/index.ts";
9
- import type { Handle, SpawnOptions, SpawnOverrides } from "../types.ts";
9
+ import type { Group, Handle, SpawnOptions, SpawnOverrides } from "../types.ts";
10
10
  import type { Agent } from "./agent.ts";
11
11
  import { type AgentDefinition, isAgentDefinition } from "./define-agent.ts";
12
12
  import { type ForkSpawner, forkRequest } from "./fork.ts";
13
+ import { hostForkRequest } from "./host-fork.ts";
13
14
  import { resolveRequest } from "./spawn-definition-request.ts";
14
15
  import { type OpenAgentContext, type OpenAgentRequest, openAgent } from "./spawn-open.ts";
15
16
  import { profiledRequest } from "./spawn-profiled.ts";
@@ -31,6 +32,12 @@ export interface SpawnDependencies {
31
32
  readonly askAdmission?: AskAdmission;
32
33
  /** Run-scoped sink of the questions an Agent asks its human (ADR-0023). */
33
34
  readonly questions?: AgentQuestions;
35
+ /**
36
+ * Recognises a Group of this Run as a spawn position (ADR-0070). Everything
37
+ * this refuses goes to the Handle lookup, which names the parent Agent or
38
+ * throws the frozen TypeError.
39
+ */
40
+ readonly isGroup: (value: unknown) => value is Group;
34
41
  }
35
42
 
36
43
  /** A RunContext spawn function that can synchronously stop accepting new Agents. */
@@ -45,6 +52,15 @@ export interface SpawnGate {
45
52
  * then — nor its Agent-question sink, so it can neither be refused nor park.
46
53
  */
47
54
  readonly openInternal: (request: OpenAgentRequest) => Promise<Agent>;
55
+ /** Throws RUN_CLOSED once the gate closed. `ctx.group()` reads the same gate. */
56
+ readonly assertOpen: () => void;
57
+ /**
58
+ * True when an Agent or a root Group of this Run already holds the name.
59
+ * A root Group name joins the Agent name space (ADR-0070, amended 2026-09-11).
60
+ */
61
+ readonly hasName: (name: string) => boolean;
62
+ /** Reserves a root Group's name in the Run-unique Agent-name set (ADR-0070). */
63
+ readonly reserveName: (name: string) => void;
48
64
  close(): void;
49
65
  }
50
66
 
@@ -57,10 +73,13 @@ export interface SpawnGate {
57
73
  export function makeSpawn(deps: SpawnDependencies): SpawnGate {
58
74
  const taken = new Set<string>();
59
75
  let closed = false;
76
+ const assertOpen = (): void => {
77
+ if (closed) throw new YaagError("RUN_CLOSED", "run has already settled");
78
+ };
60
79
  // Declared before use: every Agent this gate opens is handed the same fork
61
80
  // spawner, so a fork is gated and named exactly like a spawn.
62
81
  const forkSpawner: ForkSpawner = async (source, overrides) => {
63
- if (closed) throw new YaagError("RUN_CLOSED", "run has already settled");
82
+ assertOpen();
64
83
  const request = forkRequest(source, overrides);
65
84
  const handle = await openAgent(context, {
66
85
  spawnOptions: request.spawnOptions,
@@ -69,6 +88,7 @@ export function makeSpawn(deps: SpawnDependencies): SpawnGate {
69
88
  definitionName: undefined,
70
89
  inheritedPrompt: request.inheritedPrompt,
71
90
  fork: request.fork,
91
+ ...(request.group === undefined ? {} : { group: request.group }),
72
92
  });
73
93
  if (request.compact !== undefined && request.compact !== false) {
74
94
  await handle.compact(typeof request.compact === "string" ? request.compact : undefined);
@@ -84,19 +104,40 @@ export function makeSpawn(deps: SpawnDependencies): SpawnGate {
84
104
  definitionOrOptions: SpawnOptions | AgentDefinition | ProfiledDefinition = {},
85
105
  overrides?: SpawnOverrides,
86
106
  ): Promise<Handle> => {
87
- if (closed) throw new YaagError("RUN_CLOSED", "run has already settled");
107
+ assertOpen();
88
108
  // The Agent Definition branch is explicit, although `resolveRequest` takes
89
109
  // a plain options object too: it states the three accepted shapes in order.
90
110
  if (isAgentDefinition(definitionOrOptions)) {
91
- return openAgent(context, resolveRequest(definitionOrOptions, overrides));
111
+ return openRequested(resolveRequest(definitionOrOptions, overrides));
92
112
  }
93
113
  if (isProfiledDefinition(definitionOrOptions)) {
94
- return openAgent(context, profiledRequest(deps.profile, definitionOrOptions, overrides));
114
+ return openRequested(profiledRequest(deps.profile, definitionOrOptions, overrides));
95
115
  }
96
- return openAgent(context, resolveRequest(definitionOrOptions, overrides));
116
+ return openRequested(resolveRequest(definitionOrOptions, overrides));
117
+ };
118
+ /**
119
+ * Opens one requested Agent, as a Host Fork when the options carry `ctx.host`.
120
+ * A Host Fork gets no default Parent Link: `parent` stays the program's to
121
+ * give. `compact` is the ADR-0043 sugar — spawn, compact, hand the Handle back.
122
+ */
123
+ const openRequested = async (request: OpenAgentRequest): Promise<Handle> => {
124
+ const host = hostForkRequest(request.spawnOptions);
125
+ const handle = await openAgent(context, {
126
+ ...request,
127
+ ...(host.fork === undefined ? {} : { fork: host.fork }),
128
+ });
129
+ if (host.compact !== undefined && host.compact !== false) {
130
+ await handle.compact(typeof host.compact === "string" ? host.compact : undefined);
131
+ }
132
+ return handle;
97
133
  };
98
134
  return {
99
135
  spawn,
136
+ assertOpen,
137
+ hasName: (name: string): boolean => taken.has(name),
138
+ reserveName: (name: string): void => {
139
+ taken.add(name);
140
+ },
100
141
  // The concrete Agent, not a Handle: the Run reaps its own machinery itself,
101
142
  // and `close()` lives below the author surface.
102
143
  openInternal: (request: OpenAgentRequest): Promise<Agent> =>
@@ -5,6 +5,7 @@ import type { AgentQuestions } from "../run/index.ts";
5
5
  import type { AgentTransport, Connection, Frame } from "../transport/index.ts";
6
6
  import type { ResolvedSpawnOptions } from "../types.ts";
7
7
  import type { EffectiveAskOptions } from "./ask-hash.ts";
8
+ import type { AskTiming } from "./ask-timing.ts";
8
9
 
9
10
  /** A frame consumer whose lifetime exceeds one Ask; the Agent's AgentUsage satisfies it. */
10
11
  export interface FrameObserver {
@@ -41,12 +42,8 @@ export interface AskExchangeOptions {
41
42
  readonly modelFallback: AskModelFallback | undefined;
42
43
  /** Kills the Agent on ASK_TIMEOUT and destructive stalls — the one upward capability. */
43
44
  readonly close: () => void;
44
- /** Test-only override for the fixed duration-limit grace. */
45
- readonly askLimitGraceMs: number | undefined;
46
- /** Test-only override for the bounded settle wait after an idle abort. */
47
- readonly idleAbortSettleMs: number | undefined;
48
- /** Test-only override for the bounded wait for the Stall Watchdog probe. */
49
- readonly stallProbeSettleMs: number | undefined;
45
+ /** Test-only waits of the Ask Guard's controls; absent in production. */
46
+ readonly timing?: AskTiming;
50
47
  /** Records one parked question and raises the Run pause; absent when the Agent cannot ask. */
51
48
  readonly questions?: AgentQuestions;
52
49
  /** Marks this Ask parked, so the pause drain skips it (ADR-0022 §3, ADR-0023). */