@autumnsgrove/lyra 0.1.0 → 0.3.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 (173) hide show
  1. package/dist/adapters/cloudflare/index.d.ts +1 -0
  2. package/dist/adapters/cloudflare/index.d.ts.map +1 -1
  3. package/dist/adapters/cloudflare/index.js +1 -0
  4. package/dist/adapters/cloudflare/index.js.map +1 -1
  5. package/dist/adapters/cloudflare/session.d.ts +102 -0
  6. package/dist/adapters/cloudflare/session.d.ts.map +1 -0
  7. package/dist/adapters/cloudflare/session.js +595 -0
  8. package/dist/adapters/cloudflare/session.js.map +1 -0
  9. package/dist/adapters/openai/errors.d.ts +36 -0
  10. package/dist/adapters/openai/errors.d.ts.map +1 -0
  11. package/dist/adapters/openai/errors.js +117 -0
  12. package/dist/adapters/openai/errors.js.map +1 -0
  13. package/dist/adapters/openai/index.d.ts +18 -0
  14. package/dist/adapters/openai/index.d.ts.map +1 -0
  15. package/dist/adapters/openai/index.js +18 -0
  16. package/dist/adapters/openai/index.js.map +1 -0
  17. package/dist/adapters/openai/model.d.ts +50 -0
  18. package/dist/adapters/openai/model.d.ts.map +1 -0
  19. package/dist/adapters/openai/model.js +169 -0
  20. package/dist/adapters/openai/model.js.map +1 -0
  21. package/dist/adapters/openai/presets.d.ts +36 -0
  22. package/dist/adapters/openai/presets.d.ts.map +1 -0
  23. package/dist/adapters/openai/presets.js +43 -0
  24. package/dist/adapters/openai/presets.js.map +1 -0
  25. package/dist/adapters/openai/request.d.ts +47 -0
  26. package/dist/adapters/openai/request.d.ts.map +1 -0
  27. package/dist/adapters/openai/request.js +93 -0
  28. package/dist/adapters/openai/request.js.map +1 -0
  29. package/dist/adapters/openai/sse.d.ts +44 -0
  30. package/dist/adapters/openai/sse.d.ts.map +1 -0
  31. package/dist/adapters/openai/sse.js +410 -0
  32. package/dist/adapters/openai/sse.js.map +1 -0
  33. package/dist/core/approval.d.ts +38 -0
  34. package/dist/core/approval.d.ts.map +1 -0
  35. package/dist/core/approval.js +47 -0
  36. package/dist/core/approval.js.map +1 -0
  37. package/dist/core/compaction.d.ts +193 -0
  38. package/dist/core/compaction.d.ts.map +1 -0
  39. package/dist/core/compaction.js +460 -0
  40. package/dist/core/compaction.js.map +1 -0
  41. package/dist/core/define-recipe.d.ts +8 -1
  42. package/dist/core/define-recipe.d.ts.map +1 -1
  43. package/dist/core/define-recipe.js +13 -0
  44. package/dist/core/define-recipe.js.map +1 -1
  45. package/dist/core/events.d.ts +32 -2
  46. package/dist/core/events.d.ts.map +1 -1
  47. package/dist/core/events.js +16 -1
  48. package/dist/core/events.js.map +1 -1
  49. package/dist/core/execute-tools.d.ts +7 -0
  50. package/dist/core/execute-tools.d.ts.map +1 -1
  51. package/dist/core/execute-tools.js +6 -0
  52. package/dist/core/execute-tools.js.map +1 -1
  53. package/dist/core/hash.d.ts +10 -0
  54. package/dist/core/hash.d.ts.map +1 -0
  55. package/dist/core/hash.js +14 -0
  56. package/dist/core/hash.js.map +1 -0
  57. package/dist/core/model.d.ts +12 -0
  58. package/dist/core/model.d.ts.map +1 -1
  59. package/dist/core/propose.d.ts +29 -0
  60. package/dist/core/propose.d.ts.map +1 -0
  61. package/dist/core/propose.js +75 -0
  62. package/dist/core/propose.js.map +1 -0
  63. package/dist/core/recipe.d.ts +2 -0
  64. package/dist/core/recipe.d.ts.map +1 -1
  65. package/dist/core/recipe.js +5 -8
  66. package/dist/core/recipe.js.map +1 -1
  67. package/dist/core/resume.d.ts +19 -1
  68. package/dist/core/resume.d.ts.map +1 -1
  69. package/dist/core/resume.js +64 -6
  70. package/dist/core/resume.js.map +1 -1
  71. package/dist/core/retry.d.ts +9 -0
  72. package/dist/core/retry.d.ts.map +1 -0
  73. package/dist/core/retry.js +9 -0
  74. package/dist/core/retry.js.map +1 -0
  75. package/dist/core/run-handle.d.ts +5 -0
  76. package/dist/core/run-handle.d.ts.map +1 -1
  77. package/dist/core/run-handle.js +1 -0
  78. package/dist/core/run-handle.js.map +1 -1
  79. package/dist/core/run.d.ts +29 -2
  80. package/dist/core/run.d.ts.map +1 -1
  81. package/dist/core/run.js +526 -132
  82. package/dist/core/run.js.map +1 -1
  83. package/dist/core/runtime.d.ts +12 -0
  84. package/dist/core/runtime.d.ts.map +1 -1
  85. package/dist/core/runtime.js +34 -2
  86. package/dist/core/runtime.js.map +1 -1
  87. package/dist/core/system-clock.d.ts.map +1 -1
  88. package/dist/core/system-clock.js +5 -1
  89. package/dist/core/system-clock.js.map +1 -1
  90. package/dist/core/tool.d.ts +55 -0
  91. package/dist/core/tool.d.ts.map +1 -1
  92. package/dist/core/tool.js +16 -0
  93. package/dist/core/tool.js.map +1 -1
  94. package/dist/core/usage.d.ts +27 -0
  95. package/dist/core/usage.d.ts.map +1 -0
  96. package/dist/core/usage.js +67 -0
  97. package/dist/core/usage.js.map +1 -0
  98. package/dist/index.d.ts +7 -0
  99. package/dist/index.d.ts.map +1 -1
  100. package/dist/index.js +7 -0
  101. package/dist/index.js.map +1 -1
  102. package/dist/protocol/answers.d.ts +33 -0
  103. package/dist/protocol/answers.d.ts.map +1 -0
  104. package/dist/protocol/answers.js +86 -0
  105. package/dist/protocol/answers.js.map +1 -0
  106. package/dist/protocol/commands.d.ts +84 -0
  107. package/dist/protocol/commands.d.ts.map +1 -0
  108. package/dist/protocol/commands.js +232 -0
  109. package/dist/protocol/commands.js.map +1 -0
  110. package/dist/protocol/events.d.ts +145 -0
  111. package/dist/protocol/events.d.ts.map +1 -0
  112. package/dist/protocol/events.js +195 -0
  113. package/dist/protocol/events.js.map +1 -0
  114. package/dist/protocol/frames.d.ts +72 -0
  115. package/dist/protocol/frames.d.ts.map +1 -0
  116. package/dist/protocol/frames.js +134 -0
  117. package/dist/protocol/frames.js.map +1 -0
  118. package/dist/protocol/http.d.ts +52 -0
  119. package/dist/protocol/http.d.ts.map +1 -0
  120. package/dist/protocol/http.js +357 -0
  121. package/dist/protocol/http.js.map +1 -0
  122. package/dist/protocol/reader.d.ts +35 -0
  123. package/dist/protocol/reader.d.ts.map +1 -0
  124. package/dist/protocol/reader.js +71 -0
  125. package/dist/protocol/reader.js.map +1 -0
  126. package/dist/protocol/session.d.ts +85 -0
  127. package/dist/protocol/session.d.ts.map +1 -0
  128. package/dist/protocol/session.js +801 -0
  129. package/dist/protocol/session.js.map +1 -0
  130. package/dist/record/entries.d.ts +110 -2
  131. package/dist/record/entries.d.ts.map +1 -1
  132. package/dist/record/entries.js +337 -10
  133. package/dist/record/entries.js.map +1 -1
  134. package/dist/record/replay.d.ts +6 -0
  135. package/dist/record/replay.d.ts.map +1 -1
  136. package/dist/record/replay.js +11 -3
  137. package/dist/record/replay.js.map +1 -1
  138. package/dist/record/truncate.d.ts +12 -0
  139. package/dist/record/truncate.d.ts.map +1 -1
  140. package/dist/record/truncate.js +72 -1
  141. package/dist/record/truncate.js.map +1 -1
  142. package/dist/testkit/cassette.d.ts +91 -0
  143. package/dist/testkit/cassette.d.ts.map +1 -0
  144. package/dist/testkit/cassette.js +250 -0
  145. package/dist/testkit/cassette.js.map +1 -0
  146. package/dist/testkit/fake-model-server.d.ts +104 -0
  147. package/dist/testkit/fake-model-server.d.ts.map +1 -0
  148. package/dist/testkit/fake-model-server.js +251 -0
  149. package/dist/testkit/fake-model-server.js.map +1 -0
  150. package/dist/testkit/index.d.ts +5 -2
  151. package/dist/testkit/index.d.ts.map +1 -1
  152. package/dist/testkit/index.js +5 -2
  153. package/dist/testkit/index.js.map +1 -1
  154. package/dist/testkit/misbehaving-model.d.ts +40 -0
  155. package/dist/testkit/misbehaving-model.d.ts.map +1 -0
  156. package/dist/testkit/misbehaving-model.js +134 -0
  157. package/dist/testkit/misbehaving-model.js.map +1 -0
  158. package/dist/testkit/model.d.ts +20 -0
  159. package/dist/testkit/model.d.ts.map +1 -1
  160. package/dist/testkit/model.js +50 -3
  161. package/dist/testkit/model.js.map +1 -1
  162. package/dist/testkit/scenario.d.ts +36 -2
  163. package/dist/testkit/scenario.d.ts.map +1 -1
  164. package/dist/testkit/scenario.js +98 -13
  165. package/dist/testkit/scenario.js.map +1 -1
  166. package/dist/testkit/timeline-recipe.d.ts.map +1 -1
  167. package/dist/testkit/timeline-recipe.js +3 -0
  168. package/dist/testkit/timeline-recipe.js.map +1 -1
  169. package/dist/testkit/tools.d.ts +15 -1
  170. package/dist/testkit/tools.d.ts.map +1 -1
  171. package/dist/testkit/tools.js +19 -0
  172. package/dist/testkit/tools.js.map +1 -1
  173. package/package.json +5 -1
@@ -0,0 +1,801 @@
1
+ /**
2
+ * A session: one record, the runs it holds, and the commands a client sends it
3
+ * (docs/protocol.md, "Commands"; decisions 44 and 83).
4
+ *
5
+ * The transport does not exist here. A session takes a validated command and
6
+ * answers with the response's data, so HTTP (step 6) and a WebSocket (step 8) are
7
+ * thin layers over the same code, and a test can drive it without a socket.
8
+ *
9
+ * A session owns one record and therefore one run id: a follow-up or a resume
10
+ * continues that run as a new segment, which is what the record's own header and
11
+ * the runtime's resume check allow, and what decision 44 means by a session
12
+ * holding many runs' worth of conversation. Only one run is ever being driven at
13
+ * a time, so a second command that would start work is `busy` rather than a rival.
14
+ *
15
+ * Events come from the record whenever they can. A live run reports every entry it
16
+ * saves, so the session reads the record and projects it after each one; what a
17
+ * client sees is therefore exactly what a reconnect would replay, in the same
18
+ * order, with the same `seq`, and the only events that travel live alone are the
19
+ * ones the record does not hold (`retry`, `tool_start`). Reading the whole record
20
+ * per write is the simple version; a long run reads a lot, and the note in
21
+ * `docs/implementation/notes.md` says so.
22
+ */
23
+ import { parkedReasonOf } from "../core/events.js";
24
+ import { isPlainObject } from "../core/json.js";
25
+ import { fail, ok } from "../core/result.js";
26
+ import { DEFAULT_ENTRY_CAP_BYTES, entryCapBytes } from "../core/run.js";
27
+ import { compactRecord, DEFAULT_KEEP_TOKENS, DEFAULT_SUMMARY_INSTRUCTIONS, } from "../core/compaction.js";
28
+ import { readResumeSeed } from "../core/resume.js";
29
+ import { createRuntime } from "../core/runtime.js";
30
+ import { createUsageTotal } from "../core/usage.js";
31
+ import { loadRecord } from "../record/load.js";
32
+ import { activePath } from "../record/replay.js";
33
+ import { fitEntry, utf8Length } from "../record/truncate.js";
34
+ import { eventsAfter, projectEvents } from "./events.js";
35
+ /** How many record entries one page of `get_messages` holds unless a client asks. */
36
+ const DEFAULT_PAGE_SIZE = 50;
37
+ /** A value this module built out of the record or its own answers, as response data. */
38
+ function data(value) {
39
+ return value;
40
+ }
41
+ /** JSON equality, because a client may send the same object with its keys in another order. */
42
+ function sameJson(left, right) {
43
+ if (left === undefined) {
44
+ return false;
45
+ }
46
+ if (Array.isArray(left) || Array.isArray(right)) {
47
+ return (Array.isArray(left) &&
48
+ Array.isArray(right) &&
49
+ left.length === right.length &&
50
+ left.every((value, index) => sameJson(value, right[index])));
51
+ }
52
+ if (isPlainObject(left) && isPlainObject(right)) {
53
+ const keys = Object.keys(left);
54
+ return (keys.length === Object.keys(right).length &&
55
+ keys.every((key) => Object.prototype.hasOwnProperty.call(right, key) &&
56
+ sameJson(left[key], right[key])));
57
+ }
58
+ return left === right;
59
+ }
60
+ export function createSession(options) {
61
+ const runtime = options.runtime ??
62
+ createRuntime({
63
+ storage: options.storage,
64
+ clock: options.clock,
65
+ ids: options.ids,
66
+ model: options.model,
67
+ host: options.host,
68
+ ...(options.tenant === undefined ? {} : { tenant: options.tenant }),
69
+ // A session is where a person is reachable, so its runs may ask (decision 35).
70
+ canAsk: true,
71
+ ...(options.modelName === undefined ? {} : { modelName: options.modelName }),
72
+ ...(options.waking === undefined ? {} : { waking: options.waking }),
73
+ });
74
+ /**
75
+ * The run this session has started, remembered from the moment the command
76
+ * answers. The record is the truth, but its header is written a few awaits after
77
+ * `start` returns, so without this a second `start` interleaving in that window
78
+ * would read an empty record and start a rival run (found in review).
79
+ */
80
+ let started;
81
+ /**
82
+ * Which command is writing the record: a decision, or a run being continued. Both
83
+ * are a read, a check and an append, and either arriving inside the other's window
84
+ * would chain from a parent that is about to move, so both are refused until the
85
+ * other is done (found in review). `runtime.active` cannot see a resume that is
86
+ * still reading the record, which is why the session tracks it here too.
87
+ */
88
+ let writing;
89
+ /** Command-less callers waiting their turn, which is how a wake is not lost. */
90
+ const waiting = new Set();
91
+ /** Claim the record for one command, or say why it is busy. */
92
+ const claim = (kind) => {
93
+ if (writing !== undefined) {
94
+ return fail("busy", writing === "decision"
95
+ ? "a decision is being written in this session"
96
+ : writing === "compact"
97
+ ? "a compaction is being written in this session"
98
+ : "a run is being continued in this session");
99
+ }
100
+ writing = kind;
101
+ return ok(undefined);
102
+ };
103
+ /**
104
+ * The same claim, waited for rather than refused. The host's alarm uses it: a wake
105
+ * has nobody to report `busy` to, and it may be the only thing that will ever
106
+ * deny a timed request, so losing it would strand the run (found in review).
107
+ */
108
+ const claimWhenFree = async (kind) => {
109
+ while (writing !== undefined) {
110
+ await new Promise((resolve) => {
111
+ waiting.add(resolve);
112
+ });
113
+ }
114
+ writing = kind;
115
+ };
116
+ /** Hand the record on, and let one waiter look again. */
117
+ const release = () => {
118
+ writing = undefined;
119
+ const next = waiting.values().next();
120
+ if (next.done !== true) {
121
+ waiting.delete(next.value);
122
+ next.value();
123
+ }
124
+ };
125
+ const subscribers = new Set();
126
+ /** Events with no record entry behind them, waiting for the next turn of the pump. */
127
+ let pendingLive = [];
128
+ /** One pump at a time, so record events and live events never overtake each other. */
129
+ let chain = Promise.resolve();
130
+ const deliver = (subscriber, event) => {
131
+ try {
132
+ subscriber.send(event);
133
+ }
134
+ catch {
135
+ // A listener is not allowed to break the session or starve the others.
136
+ }
137
+ };
138
+ const pump = async () => {
139
+ if (subscribers.size === 0) {
140
+ pendingLive = [];
141
+ return;
142
+ }
143
+ const read = await options.storage.read();
144
+ if (read.ok && read.value.length > 0) {
145
+ const loaded = loadRecord(read.value);
146
+ if (loaded.ok) {
147
+ const events = projectEvents(loaded.value.entries, {
148
+ session: options.id,
149
+ run: loaded.value.header.run,
150
+ });
151
+ for (const subscriber of subscribers) {
152
+ for (const event of eventsAfter(events, subscriber.after)) {
153
+ if (!subscribers.has(subscriber)) {
154
+ break;
155
+ }
156
+ deliver(subscriber, event);
157
+ subscriber.after = event.seq;
158
+ }
159
+ }
160
+ }
161
+ }
162
+ const live = pendingLive;
163
+ pendingLive = [];
164
+ for (const event of live) {
165
+ for (const subscriber of subscribers) {
166
+ deliver(subscriber, event);
167
+ }
168
+ }
169
+ };
170
+ const schedule = () => {
171
+ chain = chain.then(pump).catch(() => undefined);
172
+ };
173
+ /** Watch a run this session is driving, so its writes reach the clients. */
174
+ const listen = (handle) => {
175
+ handle.subscribe((event) => {
176
+ if (event.type === "retry") {
177
+ pendingLive.push({
178
+ type: "retry",
179
+ ts: event.ts,
180
+ session: options.id,
181
+ run: handle.runId,
182
+ attempt: event.attempt,
183
+ delayMs: event.delayMs,
184
+ });
185
+ }
186
+ else if (event.type === "tool_start") {
187
+ pendingLive.push({
188
+ type: "tool_start",
189
+ ts: event.ts,
190
+ session: options.id,
191
+ run: handle.runId,
192
+ callId: event.callId,
193
+ name: event.name,
194
+ });
195
+ }
196
+ schedule();
197
+ });
198
+ };
199
+ /** The record, when there is one: what a command is about. */
200
+ const seedOf = async () => {
201
+ const read = await options.storage.read();
202
+ if (!read.ok) {
203
+ return read;
204
+ }
205
+ if (read.value.length === 0) {
206
+ return ok(undefined);
207
+ }
208
+ const seed = readResumeSeed(read.value);
209
+ if (!seed.ok) {
210
+ return fail("internal", `this session's record could not be read: ${seed.error.message}`);
211
+ }
212
+ return ok(seed.value);
213
+ };
214
+ const otherSession = (session) => fail("not_found", `there is no session ${session} here`);
215
+ /** A message that continues the record without starting a rival run. */
216
+ const continueWith = async (seed, text) => {
217
+ const claimed = claim("run");
218
+ if (!claimed.ok) {
219
+ return claimed;
220
+ }
221
+ try {
222
+ return await continueRun(seed, text);
223
+ }
224
+ finally {
225
+ release();
226
+ }
227
+ };
228
+ /** Continue a record that is parked, when a person asks (CMD07). */
229
+ const resumeRun = async (seed) => {
230
+ const header = seed.record.header;
231
+ const waiting = pendingOf(seed);
232
+ if (waiting !== undefined) {
233
+ return fail("busy", `this run is waiting for a person to answer ${waiting.request}`);
234
+ }
235
+ const definition = options.recipes.get(header.task);
236
+ if (definition === undefined) {
237
+ return fail("not_found", `this session's task "${header.task}" is not one this host runs`);
238
+ }
239
+ const resumed = await runtime.resume({
240
+ runId: header.run,
241
+ task: header.task,
242
+ definition,
243
+ by: "person",
244
+ });
245
+ if (!resumed.ok) {
246
+ return resumed;
247
+ }
248
+ listen(resumed.value);
249
+ return ok(data({ session: options.id, run: header.run }));
250
+ };
251
+ const continueRun = async (seed, text) => {
252
+ const header = seed.record.header;
253
+ const definition = options.recipes.get(header.task);
254
+ if (definition === undefined) {
255
+ return fail("not_found", `this session's task "${header.task}" is not one this host runs`);
256
+ }
257
+ const resumed = await runtime.resume({
258
+ runId: header.run,
259
+ task: header.task,
260
+ definition,
261
+ by: "person",
262
+ followUp: text,
263
+ });
264
+ if (!resumed.ok) {
265
+ return resumed;
266
+ }
267
+ listen(resumed.value);
268
+ return ok(data({ session: options.id, run: header.run }));
269
+ };
270
+ const getState = (seed) => {
271
+ const header = seed?.record.header;
272
+ const status = seed?.status;
273
+ const usage = createUsageTotal();
274
+ for (const used of seed?.usages ?? []) {
275
+ usage.add(used);
276
+ }
277
+ // A summary's cost is part of what the run spent, so a client watching the
278
+ // spend sees it survive an interruption (CMP14).
279
+ for (const used of seed?.summaryUsages ?? []) {
280
+ usage.add(used);
281
+ }
282
+ const handle = header === undefined ? undefined : runtime.active(header.run);
283
+ const queue = handle?.pending() ?? { steers: 0, followUps: 0 };
284
+ const state = status === undefined ? "idle" : status.state === "resumed" ? "running" : status.state;
285
+ const parked = status?.state === "parked"
286
+ ? {
287
+ reason: parkedReasonOf(status.reason),
288
+ ...(status.detail === undefined ? {} : { detail: status.detail }),
289
+ }
290
+ : undefined;
291
+ return data({
292
+ session: options.id,
293
+ run: header?.run ?? null,
294
+ state,
295
+ ...(parked === undefined ? {} : { parked }),
296
+ turns: seed?.turns ?? 0,
297
+ usage: usage.total(),
298
+ queue,
299
+ pending: pendingOf(seed) === undefined ? 0 : 1,
300
+ });
301
+ };
302
+ /**
303
+ * A person asking for a compaction now (CMD20, decision 42).
304
+ *
305
+ * It is `busy` while a run is mid-step: the run compacts at its own gaps, and a
306
+ * second summary written under it would change the view in the middle of a step.
307
+ * Otherwise it summarizes the record, writes one `compaction` entry, and answers
308
+ * whether there was anything to cut.
309
+ */
310
+ const compactNow = async (command, seed) => {
311
+ const header = seed.record.header;
312
+ if (runtime.active(header.run) !== undefined) {
313
+ return fail("busy", "a run is active in this session, so compaction waits for its gap");
314
+ }
315
+ const definition = options.recipes.get(header.task);
316
+ if (definition === undefined) {
317
+ return fail("not_found", `this session's task "${header.task}" is not one this host runs`);
318
+ }
319
+ const settings = definition.compaction;
320
+ const summarizerModel = settings?.model ?? options.modelName;
321
+ const compacted = await compactRecord({
322
+ path: activePath(seed.record.entries),
323
+ parent: seed.record.entries.at(-1)?.id ?? null,
324
+ model: options.model,
325
+ clock: options.clock,
326
+ ids: options.ids,
327
+ instructions: settings?.instructions ?? DEFAULT_SUMMARY_INSTRUCTIONS,
328
+ keepTokens: settings?.keepTokens ?? DEFAULT_KEEP_TOKENS,
329
+ ...(summarizerModel === undefined ? {} : { modelName: summarizerModel }),
330
+ ...(command.instructions === undefined
331
+ ? {}
332
+ : { extraInstructions: command.instructions }),
333
+ });
334
+ if (!compacted.ok) {
335
+ return fail(compacted.error.code, compacted.error.message);
336
+ }
337
+ if (compacted.value === undefined) {
338
+ return ok(data({ session: options.id, run: header.run, compacted: false }));
339
+ }
340
+ const fitted = fitEntry(compacted.value.entry, entryCapBytes(options.storage));
341
+ if (fitted.refused !== undefined) {
342
+ return fail("internal", fitted.refused);
343
+ }
344
+ const saved = await options.storage.append(fitted.line);
345
+ if (!saved.ok) {
346
+ return saved;
347
+ }
348
+ // The entry is in the record now, so the subscribers get the same event a
349
+ // reconnect would replay.
350
+ schedule();
351
+ return ok(data({ session: options.id, run: header.run, compacted: true }));
352
+ };
353
+ /** The request the run is waiting on, when nothing has answered it yet. */
354
+ const pendingOf = (seed) => {
355
+ const request = seed?.pendingRequest;
356
+ return request !== undefined && seed?.answer === undefined ? request : undefined;
357
+ };
358
+ /** What a client needs to answer a request, without the record's own ids (REQ02). */
359
+ const pendingRequest = (request) => data({
360
+ request: request.request,
361
+ kind: request.kind,
362
+ title: request.title,
363
+ message: request.message,
364
+ ...(request.preview === undefined ? {} : { preview: request.preview }),
365
+ ...(request.callId === undefined ? {} : { callId: request.callId }),
366
+ ...(request.tool === undefined ? {} : { tool: request.tool }),
367
+ ...(request.args === undefined ? {} : { args: request.args }),
368
+ ...(request.risk === undefined ? {} : { risk: request.risk }),
369
+ ...(request.options === undefined ? {} : { options: request.options }),
370
+ ...(request.timeoutMs === undefined ? {} : { timeoutMs: request.timeoutMs }),
371
+ });
372
+ /** Write one decision, once the caller has the session to itself. */
373
+ const decideProposal = async (command, seed) => {
374
+ const header = seed.record.header;
375
+ const path = activePath(seed.record.entries);
376
+ const proposal = path.find((entry) => entry.type === "proposal" && entry.proposal === command.proposal);
377
+ if (proposal === undefined) {
378
+ return fail("not_found", `this session has no proposal ${command.proposal}`);
379
+ }
380
+ if (path.some((entry) => entry.type === "proposal_decided" && entry.proposal === command.proposal)) {
381
+ // One decision each, and the first one stands (decision 53).
382
+ return fail("conflict", "that proposal has already been decided");
383
+ }
384
+ const entry = {
385
+ type: "proposal_decided",
386
+ id: options.ids.next("e"),
387
+ parent: seed.parent,
388
+ ts: options.clock.now(),
389
+ proposal: command.proposal,
390
+ decision: command.decision,
391
+ };
392
+ if (command.note !== undefined) {
393
+ entry.note = command.note;
394
+ }
395
+ const fitted = fitEntry(entry, entryCapBytes(options.storage));
396
+ if (fitted.refused !== undefined) {
397
+ return fail("internal", fitted.refused);
398
+ }
399
+ const saved = await options.storage.append(fitted.line);
400
+ if (!saved.ok) {
401
+ return saved;
402
+ }
403
+ schedule();
404
+ return ok(data({
405
+ session: options.id,
406
+ run: header.run,
407
+ proposal: command.proposal,
408
+ decision: command.decision,
409
+ }));
410
+ };
411
+ const listPending = (seed) => {
412
+ const waiting = pendingOf(seed);
413
+ const path = activePath(seed.record.entries);
414
+ const decided = new Set(path.flatMap((entry) => (entry.type === "proposal_decided" ? [entry.proposal] : [])));
415
+ const open = path.flatMap((entry) => entry.type === "proposal" && !decided.has(entry.proposal) ? [entry] : []);
416
+ return ok(data({
417
+ session: options.id,
418
+ run: seed.record.header.run,
419
+ requests: waiting === undefined ? [] : [pendingRequest(waiting)],
420
+ proposals: open.map((proposal) => data({
421
+ proposal: proposal.proposal,
422
+ payload: proposal.payload,
423
+ evidence: proposal.evidence,
424
+ state: proposal.state,
425
+ })),
426
+ }));
427
+ };
428
+ const getMessages = (command, seed) => {
429
+ const path = activePath(seed.record.entries);
430
+ let branch = path;
431
+ if (command.entry !== undefined) {
432
+ const index = path.findIndex((entry) => entry.id === command.entry);
433
+ if (index < 0) {
434
+ return fail("bad_request", `this record has no entry ${command.entry}`);
435
+ }
436
+ branch = path.slice(0, index + 1);
437
+ }
438
+ let start = 0;
439
+ if (command.cursor !== undefined) {
440
+ const index = branch.findIndex((entry) => entry.id === command.cursor);
441
+ if (index < 0) {
442
+ return fail("bad_request", `this branch has no entry ${command.cursor}`);
443
+ }
444
+ start = index + 1;
445
+ }
446
+ // A page is capped in entries and in bytes, so a long record can never make a
447
+ // reply that is over the line cap (CMD12).
448
+ const pageSize = command.limit ?? options.pageSize ?? DEFAULT_PAGE_SIZE;
449
+ const maxBytes = options.maxPageBytes ?? DEFAULT_ENTRY_CAP_BYTES;
450
+ const entries = [];
451
+ let bytes = 0;
452
+ for (let index = start; index < branch.length; index += 1) {
453
+ const entry = branch[index];
454
+ const size = utf8Length(JSON.stringify(entry));
455
+ if (entries.length > 0 && (entries.length >= pageSize || bytes + size > maxBytes)) {
456
+ break;
457
+ }
458
+ entries.push(entry);
459
+ bytes += size;
460
+ }
461
+ const more = start + entries.length < branch.length;
462
+ const cursor = more ? (entries.at(-1)?.id ?? null) : null;
463
+ return ok(data({ session: options.id, run: seed.record.header.run, entries, cursor }));
464
+ };
465
+ /**
466
+ * Answer a request: check it is still open, write the person's decision, and
467
+ * continue the run. It runs under the session's write claim, so a decision or a
468
+ * second answer cannot chain from the same parent (found in review).
469
+ */
470
+ const answerRequest = async (answer) => {
471
+ const existing = await seedOf();
472
+ if (!existing.ok) {
473
+ return existing;
474
+ }
475
+ const seed = existing.value;
476
+ if (seed === undefined) {
477
+ return fail("not_found", "this session has no record yet");
478
+ }
479
+ const path = activePath(seed.record.entries);
480
+ const request = path.find((entry) => entry.type === "request" && entry.request === answer.request);
481
+ if (request === undefined) {
482
+ return fail("not_found", `this session has no request ${answer.request}`);
483
+ }
484
+ const earlier = path.find((entry) => entry.type === "request_answered" && entry.request === answer.request);
485
+ if (earlier !== undefined) {
486
+ if (earlier.timedOut === true) {
487
+ // The clock answered it, so the id has expired: decision 85's `not_found`,
488
+ // not a conflict with a request a person could still decide.
489
+ return fail("not_found", `the request ${answer.request} has expired`);
490
+ }
491
+ // One answer each, and the first one stands (decisions 34, 85).
492
+ return fail("conflict", "that request has already been answered");
493
+ }
494
+ if (request.kind === "choice" && answer.ok) {
495
+ // A choice is answered with the options it offered, so a client cannot
496
+ // answer with something the run never asked about (decision 34).
497
+ const offered = new Set((request.options ?? []).map((option) => option.id));
498
+ const unknown = (answer.ids ?? []).filter((id) => !offered.has(id));
499
+ if ((answer.ids ?? []).length === 0 || unknown.length > 0) {
500
+ return fail("bad_request", `that request offers ${[...offered].join(", ")}, so the answer has to be one of them`);
501
+ }
502
+ }
503
+ if (request.kind === "approve" && (answer.text !== undefined || answer.ids !== undefined)) {
504
+ // An approval is run or refused; a question's answer has no meaning here,
505
+ // and taking it as a result would skip the call it was about (APR07).
506
+ return fail("bad_request", "an approval is answered with ok and a note, not with a text or ids");
507
+ }
508
+ if (request.timeoutMs !== undefined &&
509
+ options.clock.now() >= request.ts + request.timeoutMs) {
510
+ // An id past its timeout is expired, and an expired id is not found.
511
+ return fail("not_found", `the request ${answer.request} has expired`);
512
+ }
513
+ const header = seed.record.header;
514
+ if (runtime.active(header.run) !== undefined) {
515
+ return fail("busy", "a run is already active in this session");
516
+ }
517
+ const definition = options.recipes.get(header.task);
518
+ if (definition === undefined) {
519
+ return fail("not_found", `this session's task "${header.task}" is not one this host runs`);
520
+ }
521
+ const entry = {
522
+ type: "request_answered",
523
+ id: options.ids.next("e"),
524
+ parent: seed.parent,
525
+ ts: options.clock.now(),
526
+ request: answer.request,
527
+ decision: answer.ok ? "approve" : "deny",
528
+ };
529
+ if (answer.note !== undefined) {
530
+ entry.note = answer.note;
531
+ }
532
+ if (answer.text !== undefined) {
533
+ entry.text = answer.text;
534
+ }
535
+ if (answer.ids !== undefined) {
536
+ entry.ids = answer.ids;
537
+ }
538
+ const fitted = fitEntry(entry, entryCapBytes(options.storage));
539
+ if (fitted.refused !== undefined) {
540
+ return fail("internal", fitted.refused);
541
+ }
542
+ const saved = await options.storage.append(fitted.line);
543
+ if (!saved.ok) {
544
+ return saved;
545
+ }
546
+ const resumed = await runtime.resume({
547
+ runId: header.run,
548
+ task: header.task,
549
+ definition,
550
+ by: "person",
551
+ });
552
+ if (!resumed.ok) {
553
+ return resumed;
554
+ }
555
+ listen(resumed.value);
556
+ return ok(data({ session: options.id, run: header.run }));
557
+ };
558
+ /** The host's alarm: continue the run it names, under the session's write claim. */
559
+ const wakeRun = async (runId) => {
560
+ const existing = await seedOf();
561
+ if (!existing.ok) {
562
+ return existing;
563
+ }
564
+ const seed = existing.value;
565
+ if (seed === undefined) {
566
+ return fail("not_found", "this session has no record to wake");
567
+ }
568
+ const header = seed.record.header;
569
+ if (header.run !== runId) {
570
+ return fail("not_found", `this session does not hold run ${runId}`);
571
+ }
572
+ const definition = options.recipes.get(header.task);
573
+ if (definition === undefined) {
574
+ return fail("not_found", `this session's task "${header.task}" is not one this host runs`);
575
+ }
576
+ const woken = await runtime.wake({ runId, task: header.task, definition });
577
+ if (!woken.ok) {
578
+ return woken;
579
+ }
580
+ listen(woken.value);
581
+ return ok(data({ session: options.id, run: runId }));
582
+ };
583
+ return {
584
+ id: options.id,
585
+ respond: async (answer) => {
586
+ const claimed = claim("run");
587
+ if (!claimed.ok) {
588
+ return claimed;
589
+ }
590
+ try {
591
+ return await answerRequest(answer);
592
+ }
593
+ finally {
594
+ release();
595
+ }
596
+ },
597
+ replay: async (after) => {
598
+ const read = await options.storage.read();
599
+ if (!read.ok) {
600
+ return read;
601
+ }
602
+ if (read.value.length === 0) {
603
+ return ok([]);
604
+ }
605
+ const loaded = loadRecord(read.value);
606
+ if (!loaded.ok) {
607
+ return fail("internal", `this session's record could not be read: ${loaded.error.message}`);
608
+ }
609
+ const events = projectEvents(loaded.value.entries, {
610
+ session: options.id,
611
+ run: loaded.value.header.run,
612
+ });
613
+ return ok(eventsAfter(events, after));
614
+ },
615
+ wake: async (runId) => {
616
+ await claimWhenFree("run");
617
+ try {
618
+ return await wakeRun(runId);
619
+ }
620
+ finally {
621
+ release();
622
+ }
623
+ },
624
+ follow: async (after, listener) => {
625
+ const subscriber = { after, send: listener };
626
+ subscribers.add(subscriber);
627
+ // The replay happens inside the pump, so a client cannot be sent a live
628
+ // event before the record events that came before it.
629
+ schedule();
630
+ await chain;
631
+ return ok(() => {
632
+ subscribers.delete(subscriber);
633
+ });
634
+ },
635
+ command: async (command) => {
636
+ if ("session" in command &&
637
+ command.session !== undefined &&
638
+ command.session !== options.id) {
639
+ return otherSession(command.session);
640
+ }
641
+ if (command.command === "start") {
642
+ const existing = await seedOf();
643
+ if (!existing.ok) {
644
+ return existing;
645
+ }
646
+ // Checked after the read and before anything that awaits, so two starts
647
+ // that both passed the read cannot both get past here.
648
+ const inFlight = started;
649
+ if (inFlight !== undefined) {
650
+ if (command.key === undefined) {
651
+ return fail("conflict", "this session is already running a task; a prompt or a follow_up continues it");
652
+ }
653
+ if (inFlight.task !== command.task ||
654
+ !sameJson(inFlight.input, command.input)) {
655
+ return fail("conflict", "that key belongs to a run with a different task or input");
656
+ }
657
+ return ok(data({ session: options.id, run: inFlight.runId }));
658
+ }
659
+ if (existing.value !== undefined) {
660
+ const header = existing.value.record.header;
661
+ if (command.key === undefined) {
662
+ return fail("conflict", "this session is already running a task; a prompt or a follow_up continues it");
663
+ }
664
+ if (header.task !== command.task ||
665
+ !sameJson(existing.value.input, command.input)) {
666
+ return fail("conflict", "that key belongs to a run with a different task or input");
667
+ }
668
+ return ok(data({ session: options.id, run: header.run }));
669
+ }
670
+ const definition = options.recipes.get(command.task);
671
+ if (definition === undefined) {
672
+ return fail("not_found", `there is no task called "${command.task}"`);
673
+ }
674
+ const runId = options.ids.next("r");
675
+ const beginning = runtime.start({
676
+ runId,
677
+ task: command.task,
678
+ input: command.input,
679
+ definition,
680
+ });
681
+ if (!beginning.ok) {
682
+ return beginning;
683
+ }
684
+ // From here to the return is synchronous, so no second start can pass the
685
+ // check above until this one has claimed the session.
686
+ started = { task: command.task, input: command.input, runId };
687
+ listen(beginning.value);
688
+ return ok(data({ session: options.id, run: runId }));
689
+ }
690
+ // A compaction asked for while the run it would compact is mid-step is
691
+ // refused before the record is read: the header may not be written yet, and
692
+ // "there is no record" would be a worse answer than "it is busy".
693
+ if (command.command === "compact" && started !== undefined) {
694
+ if (runtime.active(started.runId) !== undefined) {
695
+ return fail("busy", "a run is active in this session, so compaction waits for its gap");
696
+ }
697
+ }
698
+ const existing = await seedOf();
699
+ if (!existing.ok) {
700
+ return existing;
701
+ }
702
+ const seed = existing.value;
703
+ if (command.command === "get_state") {
704
+ return ok(getState(seed));
705
+ }
706
+ if (seed === undefined) {
707
+ return fail("not_found", "this session has no record yet");
708
+ }
709
+ const header = seed.record.header;
710
+ const active = runtime.active(header.run);
711
+ switch (command.command) {
712
+ case "get_messages":
713
+ return getMessages(command, seed);
714
+ case "compact": {
715
+ const claimed = claim("compact");
716
+ if (!claimed.ok) {
717
+ return claimed;
718
+ }
719
+ try {
720
+ return await compactNow(command, seed);
721
+ }
722
+ finally {
723
+ release();
724
+ }
725
+ }
726
+ case "list_pending":
727
+ return listPending(seed);
728
+ case "decide_proposal": {
729
+ if (runtime.active(header.run) !== undefined) {
730
+ // A run is writing to this record; a decision now would chain from a
731
+ // parent it is about to move past (decision 53's one decision).
732
+ return fail("busy", "a run is active in this session");
733
+ }
734
+ const claimed = claim("decision");
735
+ if (!claimed.ok) {
736
+ return claimed;
737
+ }
738
+ try {
739
+ return await decideProposal(command, seed);
740
+ }
741
+ finally {
742
+ release();
743
+ }
744
+ }
745
+ case "prompt":
746
+ case "follow_up": {
747
+ const waiting = pendingOf(seed);
748
+ if (active === undefined && waiting !== undefined) {
749
+ // Both would continue the record, which a run waiting for a person
750
+ // cannot do. Answering `ok` and writing nothing would lose the text.
751
+ return fail("busy", `this run is waiting for a person to answer ${waiting.request}, so a ${command.command} cannot be read yet`);
752
+ }
753
+ if (active !== undefined) {
754
+ if (command.command === "prompt" && !command.queue) {
755
+ return fail("busy", "a run is active in this session");
756
+ }
757
+ const queued = active.followUp(command.text);
758
+ if (!queued.ok) {
759
+ return queued;
760
+ }
761
+ return ok(data({ session: options.id, run: header.run }));
762
+ }
763
+ return continueWith(seed, command.text);
764
+ }
765
+ case "steer": {
766
+ if (active === undefined) {
767
+ return fail("conflict", "nothing is running in this session");
768
+ }
769
+ const steered = active.steer(command.text);
770
+ if (!steered.ok) {
771
+ return steered;
772
+ }
773
+ return ok(data({ session: options.id, run: header.run }));
774
+ }
775
+ case "abort": {
776
+ if (active === undefined) {
777
+ return fail("conflict", "nothing is running in this session");
778
+ }
779
+ active.abort();
780
+ return ok(data({ session: options.id, run: header.run }));
781
+ }
782
+ case "resume": {
783
+ if (active !== undefined) {
784
+ return fail("busy", "a run is already active in this session");
785
+ }
786
+ const claimed = claim("run");
787
+ if (!claimed.ok) {
788
+ return claimed;
789
+ }
790
+ try {
791
+ return await resumeRun(seed);
792
+ }
793
+ finally {
794
+ release();
795
+ }
796
+ }
797
+ }
798
+ },
799
+ };
800
+ }
801
+ //# sourceMappingURL=session.js.map