@yaag/runtime 0.26.0 → 0.27.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (54) hide show
  1. package/package.json +1 -1
  2. package/src/agent/agent.ts +29 -17
  3. package/src/agent/fork.ts +40 -12
  4. package/src/agent/host-fork.ts +85 -0
  5. package/src/agent/spawn-definition-request.ts +38 -3
  6. package/src/agent/spawn-open.ts +43 -103
  7. package/src/agent/spawn-plan.ts +114 -0
  8. package/src/agent/spawn-request.ts +16 -2
  9. package/src/agent/spawn.ts +20 -3
  10. package/src/ask/ask-exchange-options.ts +3 -6
  11. package/src/ask/ask-exchange.ts +48 -108
  12. package/src/ask/ask-guard.ts +207 -0
  13. package/src/ask/ask-timing.ts +12 -0
  14. package/src/ask/index.ts +1 -0
  15. package/src/cassette/cassette-loader.ts +9 -20
  16. package/src/cassette/cassette-schema.ts +10 -1
  17. package/src/cassette/cassette.ts +11 -34
  18. package/src/cassette/checkpoint.ts +306 -0
  19. package/src/cassette/index.ts +16 -7
  20. package/src/cassette/parked-asks.ts +38 -0
  21. package/src/cassette/replay-divergence.ts +7 -102
  22. package/src/cassette/resume-identity.ts +5 -1
  23. package/src/cassette/resume-preconditions.ts +14 -0
  24. package/src/cassette/resume-transport.ts +26 -32
  25. package/src/cassette/run-identity.ts +109 -0
  26. package/src/cassette/session-answer.ts +51 -114
  27. package/src/cassette/spawn-identity.ts +318 -0
  28. package/src/contract/error-codes.ts +1 -0
  29. package/src/contract/index.ts +1 -0
  30. package/src/contract/spawn-options.ts +33 -2
  31. package/src/error-factories.ts +8 -0
  32. package/src/events.ts +4 -2
  33. package/src/index.ts +4 -0
  34. package/src/pi-session/append-tool-result.ts +165 -0
  35. package/src/pi-session/index.ts +30 -0
  36. package/src/pi-session/pi-session-error.ts +34 -0
  37. package/src/pi-session/session-copy.ts +113 -0
  38. package/src/pi-session/session-entries.ts +130 -0
  39. package/src/question-summary/index.ts +4 -8
  40. package/src/question-summary/summarize-question.ts +1 -1
  41. package/src/question-summary/summary-policy.ts +5 -2
  42. package/src/run/agent-questions.ts +82 -0
  43. package/src/run/answers.ts +22 -1
  44. package/src/run/host-session.ts +233 -0
  45. package/src/run/index.ts +7 -0
  46. package/src/run/run-context.ts +3 -0
  47. package/src/run/run.ts +191 -181
  48. package/src/transport/live-transport.ts +19 -0
  49. package/src/transport/pi-state.ts +10 -1
  50. package/src/transport/transport.ts +13 -9
  51. package/src/types.ts +1 -0
  52. package/src/cassette/checkpoint-flush.ts +0 -101
  53. package/src/cassette/run-checkpoint.ts +0 -272
  54. package/src/question-summary/session-copy.ts +0 -169
@@ -0,0 +1,233 @@
1
+ /**
2
+ * The Host Session file this Run was given: the pre-flight, the hash, and the
3
+ * one copy a Host Fork is spawned from.
4
+ *
5
+ * The pre-flight exists to pre-empt pi's own `SessionManager.forkFrom`, which
6
+ * throws inside the child — a `SPAWN_FAILED` far away from the cause. So a Run
7
+ * refuses a missing, unreadable, empty, header-less or ill-formed Host Session
8
+ * before it starts, and before it emits any Lifecycle Event.
9
+ *
10
+ * The hash is taken over the source bytes as read, before any append, so a
11
+ * replay can hash without copying and two Runs over one unchanged file agree.
12
+ */
13
+ import { sha256Hex } from "../cassette/index.ts";
14
+ import type { HostSource } from "../contract/index.ts";
15
+ import { hostSessionUnusableError } from "../error-factories.ts";
16
+ import type { YaagError } from "../errors.ts";
17
+ import {
18
+ findToolCall,
19
+ isPiSessionError,
20
+ isRecord,
21
+ parseSession,
22
+ prepareSessionCopy,
23
+ type SessionCopy,
24
+ } from "../pi-session/index.ts";
25
+
26
+ /** The Host Fork orientation text, written into the copy in place of the human's result. */
27
+ export const HOST_FORK_TOOL_RESULT_TEXT =
28
+ "yaag started a Run from this point. This session is a copy of the human's session. " +
29
+ "You are an Agent of that Run. Wait for the next message.";
30
+
31
+ /** What the launcher gives the Run: the Host Session file and the call that started it. */
32
+ export interface HostSessionOptions {
33
+ readonly sessionFile: string;
34
+ /** Required on a live Run, which must close that call in the copy. */
35
+ readonly toolCallId?: string;
36
+ }
37
+
38
+ /**
39
+ * The Host Source this Run resolved: the runtime shape behind the branded
40
+ * `HostSource`. The brand key is private to `contract/spawn-options.ts`, so the
41
+ * object is built here and branded with one documented cast; the spawn side
42
+ * reads these two fields to spawn the Host Fork.
43
+ */
44
+ export interface ResolvedHostSource extends HostSource {
45
+ /**
46
+ * The copy a Host Fork is spawned from. It is present only when a copy was
47
+ * made.
48
+ *
49
+ * Absent means this Run holds no copy: a strict replay, a resume with no
50
+ * tool call id, and a Host Source rebuilt from the Cassette alone. The source
51
+ * path is never put here — a spawn must never fork from it, because it would
52
+ * append to the human's live session. With no path, the spawn side refuses to
53
+ * fork instead (ADR-0068 decision 2).
54
+ */
55
+ readonly sessionFile?: string;
56
+ /** SHA-256 hex of the source bytes as read. */
57
+ readonly hostHash: string;
58
+ }
59
+
60
+ /** The prepared Host Source, plus the removal of its copy. */
61
+ export interface PreparedHostSource {
62
+ readonly source: ResolvedHostSource;
63
+ /** Removes the copy. Best effort: it never throws. */
64
+ remove(): Promise<void>;
65
+ }
66
+
67
+ /**
68
+ * What one pre-flight needs: the option, and the two Run facts that decide how
69
+ * strict it is. `live` means a `toolCallId` is required; `copies` means the copy
70
+ * is made. A strict replay does neither, so it only hashes.
71
+ */
72
+ export interface PrepareHostSourceRequest {
73
+ readonly host: HostSessionOptions;
74
+ readonly live: boolean;
75
+ readonly copies: boolean;
76
+ }
77
+
78
+ /**
79
+ * Pre-flights the Host Session, hashes it, and prepares its copy.
80
+ *
81
+ * Throws `HOST_SESSION_UNUSABLE` — and nothing else — when the file is missing,
82
+ * unreadable, empty, header-less, ill-formed, holds no such tool call, or when
83
+ * a live Run was given no `toolCallId`. It never writes to the source file.
84
+ */
85
+ export async function prepareHostSource(
86
+ request: PrepareHostSourceRequest,
87
+ ): Promise<PreparedHostSource> {
88
+ const sessionFile = request.host.sessionFile;
89
+ const bytes = await readBytes(sessionFile);
90
+ // Before the copy, so the hash names the human's file and not yaag's append.
91
+ const hostHash = sha256Hex(bytes);
92
+ const toolName = checkedToolName(sessionFile, bytes, request.host.toolCallId);
93
+ // A live Run must close that call in the copy, and it cannot find the call
94
+ // itself: a session may hold several `yaag_run` calls (ADR-0068).
95
+ if (request.live && request.host.toolCallId === undefined) {
96
+ throw hostSessionUnusableError(
97
+ sessionFile,
98
+ "no tool call id was given, and a live run must close that call in the copy",
99
+ );
100
+ }
101
+ const copy =
102
+ request.copies && request.host.toolCallId !== undefined
103
+ ? await copySession(sessionFile, request.host.toolCallId, toolName)
104
+ : undefined;
105
+ // The brand key is private to the contract, which is type-only and exports no
106
+ // factory (ADR-0045), so the one cast that builds a HostSource lives here.
107
+ const source = {
108
+ kind: "host",
109
+ ...(copy === undefined ? {} : { sessionFile: copy.path }),
110
+ hostHash,
111
+ } as ResolvedHostSource;
112
+ return { source, remove: async (): Promise<void> => await copy?.remove() };
113
+ }
114
+
115
+ /**
116
+ * The Host Source of a replay or a resume that was given no `--host-session`:
117
+ * the recorded hash, and no copy. A replay never spawns pi, and a resume
118
+ * re-opens each Host Fork from its recorded session file, so neither needs one.
119
+ */
120
+ export function adoptedHostSource(hostHash: string): ResolvedHostSource {
121
+ // The same single documented cast as above: the brand key is private to the
122
+ // contract, which exports no factory (ADR-0045).
123
+ return { kind: "host", hostHash } as ResolvedHostSource;
124
+ }
125
+
126
+ async function readBytes(sessionFile: string): Promise<ArrayBuffer> {
127
+ try {
128
+ return await Bun.file(sessionFile).arrayBuffer();
129
+ } catch (error) {
130
+ // Node reports a missing file by code; a directory or a permission failure
131
+ // arrives here too, and says so with its own message.
132
+ if (isRecord(error) && error.code === "ENOENT") {
133
+ throw hostSessionUnusableError(sessionFile, "the file does not exist");
134
+ }
135
+ throw hostSessionUnusableError(
136
+ sessionFile,
137
+ `the file cannot be read: ${error instanceof Error ? error.message : String(error)}`,
138
+ );
139
+ }
140
+ }
141
+
142
+ /**
143
+ * The tool name of the named call, which the copy records the result under.
144
+ * Checks the file-level rules the copy module does not own on the way, and
145
+ * throws the refusal of the first one that fails.
146
+ */
147
+ function checkedToolName(
148
+ sessionFile: string,
149
+ bytes: ArrayBuffer,
150
+ toolCallId: string | undefined,
151
+ ): string | undefined {
152
+ const text = new TextDecoder().decode(bytes);
153
+ if (text.trim().length === 0) throw hostSessionUnusableError(sessionFile, "the file is empty");
154
+ // The pre-flight must not be stricter than the copy it guards: it reuses the
155
+ // writer's parse policy, which tolerates one half-written last line.
156
+ assertHeader(sessionFile, text);
157
+ const entries = parse(sessionFile, text);
158
+ if (toolCallId === undefined) return undefined;
159
+ const holder = findToolCall(entries.entries, toolCallId);
160
+ if (holder === undefined) {
161
+ throw hostSessionUnusableError(sessionFile, `no entry holds the tool call ${toolCallId}`);
162
+ }
163
+ return holder.toolName;
164
+ }
165
+
166
+ function parse(sessionFile: string, text: string): ReturnType<typeof parseSession> {
167
+ try {
168
+ return parseSession(text, sessionFile);
169
+ } catch (error) {
170
+ throw refusalOf(sessionFile, error);
171
+ }
172
+ }
173
+
174
+ function assertHeader(sessionFile: string, text: string): void {
175
+ const first = text.split("\n").find((line) => line.trim().length > 0) ?? "";
176
+ let parsed: unknown;
177
+ try {
178
+ parsed = JSON.parse(first);
179
+ } catch {
180
+ throw hostSessionUnusableError(sessionFile, "the first line is no session header");
181
+ }
182
+ if (!isRecord(parsed) || parsed.type !== "session") {
183
+ throw hostSessionUnusableError(sessionFile, "the first line is no session header");
184
+ }
185
+ }
186
+
187
+ async function copySession(
188
+ sessionFile: string,
189
+ toolCallId: string,
190
+ toolName: string | undefined,
191
+ ): Promise<SessionCopy> {
192
+ try {
193
+ return await prepareSessionCopy({
194
+ sessionFile,
195
+ toolCallId,
196
+ text: HOST_FORK_TOOL_RESULT_TEXT,
197
+ ...(toolName === undefined ? {} : { toolName }),
198
+ // The `background: true` race: the human's client may answer the call
199
+ // while yaag copies, so an answered call is used as it is and never a
200
+ // refusal on this path.
201
+ toleratesAnsweredCall: true,
202
+ });
203
+ } catch (error) {
204
+ throw refusalOf(sessionFile, error);
205
+ }
206
+ }
207
+
208
+ /** Every refusal of the copy module, said in this module's one message shape. */
209
+ function refusalOf(sessionFile: string, error: unknown): YaagError {
210
+ if (!isPiSessionError(error)) {
211
+ return hostSessionUnusableError(
212
+ sessionFile,
213
+ error instanceof Error ? error.message : String(error),
214
+ );
215
+ }
216
+ switch (error.reason) {
217
+ case "unreadable":
218
+ return hostSessionUnusableError(sessionFile, "the file cannot be read");
219
+ case "bad-line":
220
+ return hostSessionUnusableError(sessionFile, badLineReason(error.message));
221
+ case "no-such-call":
222
+ return hostSessionUnusableError(sessionFile, "no entry holds the tool call");
223
+ case "different-result":
224
+ // Unreachable: this module always tolerates an answered call.
225
+ return hostSessionUnusableError(sessionFile, "the tool call is already answered");
226
+ }
227
+ }
228
+
229
+ /** The writer says which line failed; the refusal keeps that number. */
230
+ function badLineReason(message: string): string {
231
+ const line = /line (\d+)/.exec(message)?.[1];
232
+ return line === undefined ? "a line is no session entry" : `line ${line} is no session entry`;
233
+ }
package/src/run/index.ts CHANGED
@@ -11,6 +11,13 @@ export {
11
11
  type ProgramDefinition,
12
12
  programDefinition,
13
13
  } from "./define-run.ts";
14
+ export {
15
+ adoptedHostSource,
16
+ HOST_FORK_TOOL_RESULT_TEXT,
17
+ type HostSessionOptions,
18
+ prepareHostSource,
19
+ type ResolvedHostSource,
20
+ } from "./host-session.ts";
14
21
  export { isPauseSignal, RunPauseSignal } from "./pause-signal.ts";
15
22
  export type { AskUserOptions, Question } from "./questions.ts";
16
23
  export { executeRun, type RunOptions } from "./run.ts";
@@ -3,6 +3,7 @@
3
3
  import type { AgentDefinition } from "../agent/define-agent.ts";
4
4
  import type {
5
5
  Handle,
6
+ HostSource,
6
7
  SpawnableDefinition,
7
8
  SpawnOptions,
8
9
  SpawnOverrides,
@@ -50,4 +51,6 @@ export interface RunContext<Args = unknown> {
50
51
  * declares Profiles, undefined otherwise.
51
52
  */
52
53
  readonly profile?: { readonly id: string };
54
+ /** The Host Session's conversation as a fork source. Absent when the Run has none. */
55
+ readonly host?: HostSource;
53
56
  }