@yaks/tools 0.0.0-stage → 0.2.36

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 (138) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +870 -2
  3. package/_dist/access.d.ts +3 -0
  4. package/_dist/access.d.ts.map +1 -0
  5. package/_dist/app-view.d.ts +27 -0
  6. package/_dist/app-view.d.ts.map +1 -0
  7. package/_dist/args.d.ts +23 -0
  8. package/_dist/args.d.ts.map +1 -0
  9. package/_dist/check.d.ts +32 -0
  10. package/_dist/check.d.ts.map +1 -0
  11. package/_dist/declared.d.ts +66 -0
  12. package/_dist/declared.d.ts.map +1 -0
  13. package/_dist/display.d.ts +2 -0
  14. package/_dist/display.d.ts.map +1 -0
  15. package/_dist/errors.d.ts +46 -0
  16. package/_dist/errors.d.ts.map +1 -0
  17. package/_dist/fault.d.ts +4 -0
  18. package/_dist/fault.d.ts.map +1 -0
  19. package/_dist/invoke.d.ts +13 -0
  20. package/_dist/invoke.d.ts.map +1 -0
  21. package/_dist/mod.d.ts +31 -0
  22. package/_dist/mod.d.ts.map +1 -0
  23. package/_dist/outlast.d.ts +89 -0
  24. package/_dist/outlast.d.ts.map +1 -0
  25. package/_dist/persist.d.ts +5 -0
  26. package/_dist/persist.d.ts.map +1 -0
  27. package/_dist/read.d.ts +4 -0
  28. package/_dist/read.d.ts.map +1 -0
  29. package/_dist/readable.d.ts +59 -0
  30. package/_dist/readable.d.ts.map +1 -0
  31. package/_dist/registry.d.ts +53 -0
  32. package/_dist/registry.d.ts.map +1 -0
  33. package/_dist/result.d.ts +154 -0
  34. package/_dist/result.d.ts.map +1 -0
  35. package/_dist/routes.d.ts +11 -0
  36. package/_dist/routes.d.ts.map +1 -0
  37. package/_dist/runner.d.ts +161 -0
  38. package/_dist/runner.d.ts.map +1 -0
  39. package/_dist/said.d.ts +4 -0
  40. package/_dist/said.d.ts.map +1 -0
  41. package/_dist/schema.d.ts +76 -0
  42. package/_dist/schema.d.ts.map +1 -0
  43. package/_dist/state.d.ts +9 -0
  44. package/_dist/state.d.ts.map +1 -0
  45. package/_dist/title.d.ts +20 -0
  46. package/_dist/title.d.ts.map +1 -0
  47. package/_dist/value.d.ts +43 -0
  48. package/_dist/value.d.ts.map +1 -0
  49. package/_dist/views.d.ts +5 -0
  50. package/_dist/views.d.ts.map +1 -0
  51. package/_dist/vocab.d.ts +9 -0
  52. package/_dist/vocab.d.ts.map +1 -0
  53. package/_dist/watch.d.ts +28 -0
  54. package/_dist/watch.d.ts.map +1 -0
  55. package/access.js +3 -0
  56. package/access.js.map +1 -0
  57. package/access.ts +11 -0
  58. package/app-view.js +26 -0
  59. package/app-view.js.map +1 -0
  60. package/app-view.ts +41 -0
  61. package/args.js +136 -0
  62. package/args.js.map +1 -0
  63. package/args.ts +187 -0
  64. package/body.js +14 -0
  65. package/body.js.map +1 -0
  66. package/body.ts +15 -0
  67. package/check.js +67 -0
  68. package/check.js.map +1 -0
  69. package/check.ts +92 -0
  70. package/declared.js +529 -0
  71. package/declared.js.map +1 -0
  72. package/declared.ts +719 -0
  73. package/deno.json +1 -0
  74. package/display.js +21 -0
  75. package/display.js.map +1 -0
  76. package/display.ts +39 -0
  77. package/errors.js +99 -0
  78. package/errors.js.map +1 -0
  79. package/errors.ts +127 -0
  80. package/fault.js +17 -0
  81. package/fault.js.map +1 -0
  82. package/fault.ts +24 -0
  83. package/invoke.js +207 -0
  84. package/invoke.js.map +1 -0
  85. package/invoke.ts +210 -0
  86. package/mod.js +31 -0
  87. package/mod.js.map +1 -0
  88. package/mod.ts +78 -0
  89. package/outlast.js +416 -0
  90. package/outlast.js.map +1 -0
  91. package/outlast.ts +551 -0
  92. package/package.json +109 -4
  93. package/persist.js +18 -0
  94. package/persist.js.map +1 -0
  95. package/persist.ts +26 -0
  96. package/read.js +50 -0
  97. package/read.js.map +1 -0
  98. package/read.ts +58 -0
  99. package/readable.js +118 -0
  100. package/readable.js.map +1 -0
  101. package/readable.ts +134 -0
  102. package/registry.js +162 -0
  103. package/registry.js.map +1 -0
  104. package/registry.ts +207 -0
  105. package/result.js +497 -0
  106. package/result.js.map +1 -0
  107. package/result.ts +540 -0
  108. package/routes.js +46 -0
  109. package/routes.js.map +1 -0
  110. package/routes.ts +50 -0
  111. package/runner.js +748 -0
  112. package/runner.js.map +1 -0
  113. package/runner.ts +910 -0
  114. package/said.js +15 -0
  115. package/said.js.map +1 -0
  116. package/said.ts +12 -0
  117. package/schema.js +137 -0
  118. package/schema.js.map +1 -0
  119. package/schema.ts +134 -0
  120. package/state.js +69 -0
  121. package/state.js.map +1 -0
  122. package/state.ts +108 -0
  123. package/title.js +222 -0
  124. package/title.js.map +1 -0
  125. package/title.ts +257 -0
  126. package/value.js +57 -0
  127. package/value.js.map +1 -0
  128. package/value.ts +74 -0
  129. package/views.js +131 -0
  130. package/views.js.map +1 -0
  131. package/views.ts +125 -0
  132. package/vocab.js +22 -0
  133. package/vocab.js.map +1 -0
  134. package/vocab.json +268 -0
  135. package/vocab.ts +22 -0
  136. package/watch.js +64 -0
  137. package/watch.js.map +1 -0
  138. package/watch.ts +74 -0
package/runner.js ADDED
@@ -0,0 +1,748 @@
1
+ // The runner: the one place a tool function is called, and the record it
2
+ // leaves behind. A tool is a function `(call, graph) => bundles`, handed the
3
+ // call entity and nothing else about the request. A caller can invoke one
4
+ // directly and get its bundles back; what this file adds is the stored record,
5
+ // which is why callers normally go through here: the `call` entity recording
6
+ // what was asked, the `result{call, ms}` recording what came back, and the
7
+ // `execution{state}` recording that a run is in flight.
8
+ //
9
+ // The call a tool is handed is the stored one, completed: its arguments
10
+ // checked against the tool's schema and the entities they name resolved to
11
+ // eids (./args.ts), `who(call)` saying who decided the request even
12
+ // where the graph stamps nothing, and `process{pid, command, cwd}` naming the
13
+ // program running the tool on this machine. A session identifies its author,
14
+ // not its checkout: sub-agents can share a session and connection. This is a
15
+ // bundle, not a row — the stored call never wears `process`.
16
+ //
17
+ // The result entity is emitted by the declared effect's match (./vocab.json,
18
+ // @yaks/graph `emitted`), so its id is derived from the match — `call_ready(<the call>)` —
19
+ // and the same call names the same result entity in this process, in another
20
+ // process, or a year later. Running a call twice patches one entity, never
21
+ // two.
22
+ //
23
+ // Finding a call another process wrote — one nobody claimed, one scheduled for
24
+ // later — is not this file's job. That is an effect, and ./vocab.json declares
25
+ // two (`call_ready`, `call_woken`), each a query over calls; a host that runs
26
+ // effects handles both with `run.due` (@yaks/effects `handle`), one line each,
27
+ // nothing more. A call written claimed owes neither: the caller is running it.
28
+ // `drive()` runs those same two queries once, and asks for every claimed call
29
+ // with no answer besides, for explicit recovery without a durable effect pool.
30
+ //
31
+ // At most once, and how a crash is recovered: `execution{state, by}` on the
32
+ // call is the claim. The runner writes `running` with a `$was` precondition
33
+ // that the property was absent, so a second server loses the race instead of
34
+ // running the tool twice; it writes `done` or `failed` when the result is
35
+ // applied. A call asked through `call()` is written already claimed, in the
36
+ // same batch: the caller asking is the one waiting for the answer, so the
37
+ // tool runs where it asked, and every other runner (an effect of the same
38
+ // commit, another thread of the process, another process) finds the call held
39
+ // from the moment it exists. A call left `running` by a process that died has
40
+ // no result. Its recorded effect retries `due`; an explicitly requested
41
+ // `reconcile()` also finds claimed calls, including ones written already
42
+ // claimed that owed no effect. `by` records whose claim it is:
43
+ // a runner leaves a live process's claim alone, its own owner's included,
44
+ // since a claim this runner is not running is running in another runner under
45
+ // the same name. That is also what a transcript imported from another
46
+ // machine needs: every call in it arrives already executed. The exception is
47
+ // a holder that has finished: a process
48
+ // writes its `exit` row in the last transaction it will ever write, so a call
49
+ // it left `running` has nobody coming back to finish it. That claim has
50
+ // lapsed, and the next sweep takes it the way a re-run takes one — which is
51
+ // what makes a crash recoverable now that a restarted process is a new entity
52
+ // rather than a reused name.
53
+ //
54
+ // The identity is the caller's. The bundles a tool returns are stamped with
55
+ // whoever wrote the call, never with the process running it, so authorization
56
+ // is decided about the caller. The runner's own bookkeeping — the result and
57
+ // the execution rows — belongs to the server and carries no identity at all.
58
+ import { derivedEid, mint, namedTool, signed, Stale, who } from "@yaks/graph";
59
+ import { token } from "@yaks/graph/sha256";
60
+ import { line } from "@yaks/query";
61
+ import { Busy, CallError, UnfinishedCall } from "./errors.js";
62
+ export { UnfinishedCall } from "./errors.js";
63
+ import { persist } from "./persist.js";
64
+ import { invoke } from "./invoke.js";
65
+ import { answerOf, measuring, results, toolEid, toolRow, worded } from "./result.js";
66
+ import { registryOf } from "./registry.js";
67
+ // What each call is doing right now in this process, keyed per graph, not per
68
+ // runner: a second runner over the same graph that is asked for a call in
69
+ // flight finds the first's promise instead of racing it, and an effect finds
70
+ // the call taken.
71
+ let running = new WeakMap();
72
+ /** The kind a written bundle made its entity, if it made one: a created
73
+ * entity's kind, or a kind that is a mark (@yaks/vocab `CompInfo.mark`) whose
74
+ * `at` this write stamped, so marked for the first time. What a {@link Reply}
75
+ * reads of `wrote` to find the entities its call made. */ export let became = (vocab, b)=>{
76
+ if (b.tombstone) return undefined;
77
+ if (b.created) return vocab.kindOf(b);
78
+ return Object.keys(b).find((c)=>{
79
+ let info = vocab.comp(c);
80
+ return info?.kind && info.mark && b[c]?.at;
81
+ });
82
+ };
83
+ // What `work` answers, or what `instead` says once `cut` aborts first. An
84
+ // `instead` that says nothing leaves the answer to `work`.
85
+ let unless = (work, cut, instead)=>{
86
+ if (!cut) return work;
87
+ let off;
88
+ let gone = new Promise((done)=>{
89
+ off = ()=>{
90
+ let said = instead();
91
+ if (said) done(said);
92
+ };
93
+ if (cut.aborted) off();
94
+ else cut.addEventListener('abort', off, {
95
+ once: true
96
+ });
97
+ });
98
+ return Promise.race([
99
+ work,
100
+ gone
101
+ ]).finally(()=>cut.removeEventListener('abort', off));
102
+ };
103
+ // What a caller let go of a call still running is told: where its answer will
104
+ // be kept, and what an interruption means for it.
105
+ let outrun = (id, tool)=>({
106
+ entity: {
107
+ eid: '$said'
108
+ },
109
+ content: {
110
+ body: `${tool} is still running as call ${id}, and this server is ` + 'stopping. Its answer is kept on the call: read it with graph_query ' + `.result.call=${id}. If the server ends before the tool returns, the ` + 'call ends interrupted, and can be asked again.'
111
+ },
112
+ output: {
113
+ source: id
114
+ }
115
+ });
116
+ /** The result and the answer a transcript keeps (`onResult`), from what a
117
+ * call `made` and how its result `end`s in those words: a lone refusal rides
118
+ * on the result and keeps no entity, and a lone `$said` answer's components
119
+ * beside its words and source move onto the result, where a reader of the
120
+ * transcript's entries finds them. Its value as data rides as `result{value}`:
121
+ * `output` on an entry says the model spoke it, and a result is the tool's.
122
+ *
123
+ * ```ts
124
+ * import { assertEquals } from '@std/assert'
125
+ * let end = () => [{ entity: { eid: 'r' }, result: { call: 'c' } }]
126
+ * let words = {
127
+ * entity: { eid: '$said' },
128
+ * content: { body: 'shown' },
129
+ * output: { source: 'c' },
130
+ * }
131
+ * assertEquals(ridden([{ ...words, files: { n: 1 } }], 'done', end), [
132
+ * [{ entity: { eid: 'r' }, result: { call: 'c' }, files: { n: 1 } }],
133
+ * [words],
134
+ * ])
135
+ * let valued = { ...words, output: { source: 'c', value: { n: 1 } } }
136
+ * assertEquals(ridden([valued], 'done', end), [
137
+ * [{ entity: { eid: 'r' }, result: { call: 'c', value: { n: 1 } } }],
138
+ * [valued],
139
+ * ])
140
+ * ```
141
+ */ export let ridden = (made, state, end)=>{
142
+ let [one, ...more] = made;
143
+ if (!one || more.length) return [
144
+ end(made),
145
+ made
146
+ ];
147
+ if (state == 'failed' && one.refusal && !one.exception) {
148
+ let [result, ...rest] = end(made);
149
+ return [
150
+ [
151
+ {
152
+ ...result,
153
+ refusal: one.refusal
154
+ },
155
+ ...rest
156
+ ],
157
+ []
158
+ ];
159
+ }
160
+ let carried = one.entity.eid == '$said' ? Object.keys(one).filter((k)=>![
161
+ 'entity',
162
+ 'content',
163
+ 'output'
164
+ ].includes(k) && !k.startsWith('$')) : [];
165
+ let value = one.entity.eid == '$said' ? one.output?.value : undefined;
166
+ if (!carried.length && value === undefined) return [
167
+ end(made),
168
+ made
169
+ ];
170
+ let words = Object.fromEntries(Object.entries(one).filter(([k])=>!carried.includes(k)));
171
+ let [result, ...rest] = end([
172
+ words
173
+ ]);
174
+ return [
175
+ [
176
+ {
177
+ ...result,
178
+ ...Object.fromEntries(carried.map((k)=>[
179
+ k,
180
+ one[k]
181
+ ])),
182
+ ...value === undefined ? {} : {
183
+ result: {
184
+ ...result.result,
185
+ value
186
+ }
187
+ }
188
+ },
189
+ ...rest
190
+ ],
191
+ [
192
+ words
193
+ ]
194
+ ];
195
+ };
196
+ /** Whether the runner writes what `tool` answered, ending in `state`, or
197
+ * hands the answer back as the tool built it. A read-only tool's answer is
198
+ * entities that already exist, and writing them would patch every row the
199
+ * query found and move its `updated` stamp; an applied tool's host has written
200
+ * its own. So the runner writes only its bookkeeping for either. A failure is
201
+ * written whatever the tool was: an error is worth recording. */ export let keeps = (tool, state)=>!tool.readOnly && !tool.applied || state == 'failed' || state == 'interrupted';
202
+ /**
203
+ * Build a runner over a graph.
204
+ *
205
+ * ```ts ignore
206
+ * let r = runner(g, { tools })
207
+ * await r.ensure()
208
+ * // the call entity is the record; the answer is the tool's own bundles
209
+ * let id = mint()
210
+ * let landed = await r.call({
211
+ * entity: { eid: id },
212
+ * call: { to: toolEid('text_echo'), args: {} },
213
+ * })
214
+ * answerOf(landed, id)
215
+ * ```
216
+ *
217
+ * Nothing polls the graph for calls. A server that wants the deferred ones too
218
+ * handles the two effects ./vocab.json declares — `fx.handle({ [r.rule.name]:
219
+ * (e) => run.due(e.entity.eid) })` for each of `run.rules`. A durable effect
220
+ * pool recovers recorded runs after a crash; it needs no startup reconcile.
221
+ * `reconcile()` is explicit recovery for calls without a recorded effect.
222
+ */ export let runner = (g, opts)=>{
223
+ let made;
224
+ let catalog = ()=>made ??= registryOf(opts.tools);
225
+ let otherwise = opts.otherwise && namedTool(opts.otherwise);
226
+ let clock = opts.clock ?? measuring;
227
+ let now = ()=>clock.now();
228
+ let { rules: plans, held: claimed, ending } = results(g.vocab, now);
229
+ let inflight = running.get(g) ?? new Map();
230
+ running.set(g, inflight);
231
+ // The calls this runner claimed and whose tool has not returned, with when
232
+ // each started: what an interruption ends.
233
+ let held = new Map();
234
+ // Whose claim a call carries, as this runner reads it. Unclaimed, or claimed
235
+ // with no owner named, is `free`. This owner's own claim is `mine`: one
236
+ // this runner is not running is running in another runner under the same
237
+ // name, or failed there, and either way the owner is not over. Another's
238
+ // claim is `theirs` — unless its row records an `exit`, which makes the
239
+ // claim `lapsed`: nothing is coming back to finish the call, so it is
240
+ // taken the way a re-run takes one, claiming over `running`; so does a
241
+ // holder the host's `gone` says is over. The holder
242
+ // entity is fetched whole rather than queried by `.exit`, so a graph that
243
+ // tracks no processes simply never finds one — this package reads a
244
+ // component by name and requires nothing of the vocabulary.
245
+ let whose = async (call)=>{
246
+ let by = call.execution?.by;
247
+ if (by == null) return 'free';
248
+ // An unnamed runner's own claim still owes the unfinished-call check.
249
+ if (!opts.owner && by == owner) return 'free';
250
+ if (by == opts.owner) return 'mine';
251
+ if (await opts.gone?.(by)) return 'lapsed';
252
+ let [holder] = await g.get([
253
+ String(by)
254
+ ], [
255
+ 'exit'
256
+ ]);
257
+ return holder?.exit ? 'lapsed' : 'theirs';
258
+ };
259
+ // Each tool's row, as the batch that stood it up (`ensure`): one entry per
260
+ // tool name, several names sharing the batch they were written in.
261
+ let stood = new WeakMap();
262
+ let registering = Promise.resolve([]);
263
+ // The rows of these tools that are missing or say something else, written.
264
+ let standing = (some)=>Promise.resolve(g.get(some.map((t)=>toolEid(t.name)), [
265
+ 'tool'
266
+ ])).then((held)=>{
267
+ let said = new Map(held.map((b)=>[
268
+ b.entity.eid,
269
+ b.tool
270
+ ]));
271
+ let stale = some.filter((t)=>{
272
+ let row = said.get(toolEid(t.name));
273
+ return row?.name != t.name || row?.description != t.description || row?.revision != t.revision;
274
+ });
275
+ return stale.length ? g.apply(stale.map(toolRow)) : [];
276
+ });
277
+ // The answer, read back out of the graph: the result entity the rule named,
278
+ // plus every entity recording that it came from this call. This is what a
279
+ // caller sees when another process ran the tool. A read-only tool's answer
280
+ // was never written, so only the result comes back for one, and the way to
281
+ // see the answer again is to call it again.
282
+ let recalled = async (id)=>{
283
+ let result = await g.read(line`.result.call=${id}&*`);
284
+ if (!result.length) return [];
285
+ let made = await g.read(line`.output.source=${id}&*`);
286
+ return [
287
+ ...made,
288
+ ...result
289
+ ];
290
+ };
291
+ // The claim this runner writes.
292
+ let owner = opts.owner ?? mint();
293
+ let claim = ()=>({
294
+ by: owner
295
+ });
296
+ // The tool a call names, as this runner has it. A call naming a tool this
297
+ // runner does not have is left alone: another runner may have that tool,
298
+ // and failing the call here would be this runner's verdict on somebody
299
+ // else's work.
300
+ let toolOf = (call)=>opts.takes && !opts.takes(call) ? undefined : catalog().get(String(call.call.to)) ?? otherwise;
301
+ // One promise per call in flight in this process, in the map before the
302
+ // work starts, so nothing the work sets off finds the call untaken.
303
+ let tracked = (id, go)=>{
304
+ let pending = Promise.resolve().then(go).finally(()=>inflight.delete(id));
305
+ inflight.set(id, pending);
306
+ return pending;
307
+ };
308
+ // A call written and claimed in one batch, then run here. The claim is its
309
+ // own bundle: the call is the caller's, the claim is the runner's
310
+ // bookkeeping and carries no identity. A call somebody claimed first (only
311
+ // a named one can be) reads the way `run` reads it.
312
+ let born = (asked, admitted, cut)=>{
313
+ let id = asked.entity.eid.startsWith('$') ? mint() : asked.entity.eid;
314
+ let call = {
315
+ ...asked,
316
+ entity: {
317
+ ...asked.entity,
318
+ eid: id
319
+ }
320
+ };
321
+ let tool = admitted ?? toolOf(call);
322
+ let work = tracked(id, async ()=>{
323
+ if (!tool) {
324
+ await g.apply([
325
+ call
326
+ ]);
327
+ return [];
328
+ }
329
+ try {
330
+ await g.apply([
331
+ call,
332
+ {
333
+ entity: {
334
+ eid: id
335
+ },
336
+ execution: claim(),
337
+ $was: {
338
+ execution: {
339
+ by: null
340
+ }
341
+ }
342
+ }
343
+ ]);
344
+ } catch (error) {
345
+ if (error instanceof Stale) return perform(id, {});
346
+ throw error;
347
+ }
348
+ let [stored] = await g.get([
349
+ id
350
+ ]);
351
+ return execute(stored, tool, true, false, cut);
352
+ });
353
+ if (!tool) return work;
354
+ // Let go at the cut while the tool is running: what goes wrong with it
355
+ // from then on has no caller to hear it, and is reported. A call the
356
+ // host's close ended meanwhile answers Stale, and is over. One whose tool
357
+ // has returned answers as it is, without its reply.
358
+ return unless(work, cut, ()=>{
359
+ if (!held.has(id)) return undefined;
360
+ work.catch((error)=>error instanceof Stale ? undefined : opts.report?.(error, call, tool.name));
361
+ return [
362
+ {
363
+ entity: {
364
+ eid: id
365
+ },
366
+ execution: claim()
367
+ },
368
+ outrun(id, tool.name)
369
+ ];
370
+ });
371
+ };
372
+ let perform = async (id, o)=>{
373
+ let [call] = await g.get([
374
+ id
375
+ ]);
376
+ if (!call?.call) {
377
+ if (o.due) return [];
378
+ throw new CallError('call', 'Not a call: ' + id);
379
+ }
380
+ // A recurring call is not one invocation: it is the row that keeps asking
381
+ // for one. Each firing writes its own call entity, with an id derived from
382
+ // the schedule and the instant it fired, and that new call is what runs —
383
+ // so a finished call is never re-run, the record shows how many times the
384
+ // schedule fired, and the schedule itself stays a standing request. A wake
385
+ // recurs by its `every` or by its `while` (@yaks/wake). A one-shot has
386
+ // nothing to advance and runs in place.
387
+ let wake = call.wake;
388
+ let went = call.fired?.at;
389
+ if ((wake?.every || wake?.while?.length) && went) {
390
+ let asked = call.call;
391
+ let [each] = signed([
392
+ {
393
+ entity: {
394
+ eid: derivedEid(`call ${id} ${went}`)
395
+ },
396
+ call: {
397
+ to: asked.to,
398
+ args: asked.args,
399
+ source: id
400
+ }
401
+ }
402
+ ], who(call));
403
+ return born(each);
404
+ }
405
+ let held = await recalled(id);
406
+ if (held.length) return held;
407
+ if (call.interrupted) return [];
408
+ // A live process's claim is not this runner's to take, redrive or not,
409
+ // its own owner's included: a claim this runner is not running is running
410
+ // in another runner under the same name. A lapsed one is taken here and now,
411
+ // without waiting for a boot sweep.
412
+ let hold = await whose(call);
413
+ if (hold == 'theirs' || hold == 'mine') return [];
414
+ let redrive = o.redrive || hold == 'lapsed';
415
+ // A durable run may have put its claim down while waiting. The empty
416
+ // execution record keeps call_ready from creating a second effect.
417
+ if (call.execution && !redrive && !o.defer) {
418
+ if (o.due) return [];
419
+ throw new UnfinishedCall(id);
420
+ }
421
+ let tool = toolOf(call);
422
+ if (!tool) return [];
423
+ let c = call.call;
424
+ // The claim. A runner that loses it to another has nothing to run.
425
+ try {
426
+ await g.apply([
427
+ {
428
+ entity: {
429
+ eid: id
430
+ },
431
+ execution: claim(),
432
+ $was: {
433
+ execution: {
434
+ by: redrive ? token(call.execution?.by) : null
435
+ },
436
+ call: Object.fromEntries(g.vocab.props('call').filter((p)=>p != 'id').map((p)=>[
437
+ p,
438
+ token(c[p])
439
+ ]))
440
+ }
441
+ }
442
+ ]);
443
+ } catch (error) {
444
+ if (error instanceof Stale) return [];
445
+ throw error;
446
+ }
447
+ return execute({
448
+ ...call,
449
+ execution: claim()
450
+ }, tool, false, false, undefined, o.defer);
451
+ };
452
+ // Running a claimed call: the tool, its answer, and the record of both.
453
+ let execute = async (call, tool, direct = false, unrecorded = false, cut, defer)=>{
454
+ let id = call.entity.eid;
455
+ let started = now();
456
+ held.set(id, {
457
+ call,
458
+ started
459
+ });
460
+ // Writing the answer, where `keeps` says to. A rehearsal's answer is what
461
+ // a write would have been, and is not written either.
462
+ let land = async (made, state, keep = keeps(tool, state), code)=>{
463
+ let words = [];
464
+ let end = (said)=>ending(call, started, state, words = said);
465
+ let ended;
466
+ [ended, made] = opts.onResult ? ridden(made, state, end) : [
467
+ end(made),
468
+ made
469
+ ];
470
+ if (unrecorded) return [
471
+ ...made,
472
+ ...ended
473
+ ];
474
+ let bundles = [
475
+ ...keep ? made : [],
476
+ ...ended,
477
+ ...code ? [
478
+ {
479
+ entity: {
480
+ eid: id
481
+ },
482
+ interrupted: {
483
+ code
484
+ }
485
+ }
486
+ ] : []
487
+ ];
488
+ // An answer that is written is worded as it was written, in the same
489
+ // transaction: each alias under the eid it became, stamped, with no
490
+ // request keys on it, as a caller reading the result later reads it.
491
+ let result = ended.find((b)=>b.result).entity;
492
+ let receipt = keep && words === made ? (applied)=>[
493
+ {
494
+ entity: result,
495
+ content: {
496
+ body: worded(answerOf(applied, id))
497
+ }
498
+ }
499
+ ] : undefined;
500
+ // A retry reports the storage error separately from the call's failure,
501
+ // which was reported at its catch boundary before recording the answer.
502
+ // The exception's properties are stamped: only its catcher writes them.
503
+ let trusted = made.some((b)=>b.exception);
504
+ let landed = await persist(()=>g.apply(bundles, {
505
+ ...trusted ? {
506
+ trusted
507
+ } : {},
508
+ ...receipt ? {
509
+ receipt
510
+ } : {}
511
+ }), (e)=>opts.report?.(e, call, tool.name), clock);
512
+ return keep ? landed : [
513
+ ...made,
514
+ ...landed
515
+ ];
516
+ };
517
+ let wrote = [];
518
+ let answered;
519
+ try {
520
+ answered = await invoke(call, tool, g, opts, async (made, state, keep, code)=>{
521
+ let out = await land(made, state, keep, code);
522
+ if (state == 'done' && keeps(tool, state) && keep !== false) {
523
+ wrote = answerOf(out, id);
524
+ }
525
+ return out;
526
+ }, !!defer);
527
+ } catch (error) {
528
+ if (!defer || !(error instanceof Busy)) throw error;
529
+ await g.apply([
530
+ {
531
+ entity: {
532
+ eid: id
533
+ },
534
+ execution: {
535
+ by: null
536
+ },
537
+ $was: {
538
+ execution: {
539
+ by: token(owner)
540
+ }
541
+ }
542
+ }
543
+ ]);
544
+ await defer(error.after, error.message);
545
+ return [];
546
+ } finally{
547
+ held.delete(id);
548
+ }
549
+ if (unrecorded || !direct || !opts.reply || cut?.aborted) return answered;
550
+ try {
551
+ return [
552
+ ...answered,
553
+ ...await unless(opts.reply(call, answerOf(answered, id), wrote), cut, ()=>[])
554
+ ];
555
+ } catch (error) {
556
+ await opts.report?.(error, call, tool.name);
557
+ return answered;
558
+ }
559
+ };
560
+ let run = (id, o = {})=>inflight.get(id) ?? tracked(id, ()=>perform(id, o));
561
+ let due = async (id, o = {})=>inflight.has(id) ? [] : await tracked(id, ()=>perform(id, {
562
+ ...o,
563
+ due: true
564
+ }));
565
+ // Explicit recovery selects identities only. A due call is read in perform;
566
+ // projecting it here would load its components and computed lifecycle twice.
567
+ // Durable hosts instead recover their recorded effect rows, without drive.
568
+ let queued = async ()=>{
569
+ let out = new Set();
570
+ for (let p of plans){
571
+ let { filter } = p.plan.patterns[0];
572
+ for (let b of (await g.rows(filter)))out.add(b.eid);
573
+ }
574
+ for (let b of claimed ? await g.rows(claimed) : [])out.add(b.eid);
575
+ return [
576
+ ...out
577
+ ];
578
+ };
579
+ let drive = async (o = {})=>{
580
+ let out = [];
581
+ for (let id of (await queued())){
582
+ try {
583
+ out.push(...await due(id, o));
584
+ } catch (error) {
585
+ if (opts.report) {
586
+ let [call] = await g.get([
587
+ id
588
+ ]);
589
+ let to = String(call?.call?.to);
590
+ await opts.report(error, call, catalog().get(to)?.name);
591
+ }
592
+ }
593
+ }
594
+ return out;
595
+ };
596
+ let interruptCall = async (id, why, answer)=>{
597
+ let [call] = await g.get([
598
+ id
599
+ ]);
600
+ if (!call?.call) throw new CallError('call', 'Not a call: ' + id);
601
+ let prior = await recalled(id);
602
+ if (prior.length) return prior;
603
+ let execution = call.execution;
604
+ if (execution && (call.interrupted || execution.by != null)) {
605
+ throw new UnfinishedCall(id);
606
+ }
607
+ let fault = {
608
+ entity: {
609
+ eid: '$fault'
610
+ },
611
+ content: {
612
+ body: why
613
+ },
614
+ output: {
615
+ source: id
616
+ },
617
+ ...g.vocab.comp('notice') ? {
618
+ notice: {}
619
+ } : {}
620
+ };
621
+ let said = execution && answer ? answer : [
622
+ fault
623
+ ];
624
+ let state = execution && answer ? 'done' : 'interrupted';
625
+ let end = (said)=>ending(call, undefined, state, said, execution ? 'running' : null);
626
+ let ended;
627
+ [ended, said] = opts.onResult ? ridden(said, state, end) : [
628
+ end(said),
629
+ said
630
+ ];
631
+ try {
632
+ return await g.apply([
633
+ ...said,
634
+ ...ended
635
+ ]);
636
+ } catch (error) {
637
+ if (error instanceof Stale) {
638
+ let prior = await recalled(id);
639
+ if (prior.length) return prior;
640
+ throw new UnfinishedCall(id);
641
+ }
642
+ throw error;
643
+ }
644
+ };
645
+ let ensure = (asked)=>{
646
+ let fresh = asked.filter((t)=>!stood.has(t));
647
+ if (fresh.length) {
648
+ let bundles = registering.catch(()=>[]).then(()=>standing(fresh.map((t)=>catalog().get(t.name) ?? t))).catch((error)=>{
649
+ for (let t of fresh){
650
+ if (stood.get(t) === bundles) stood.delete(t);
651
+ }
652
+ throw error;
653
+ });
654
+ registering = bundles;
655
+ for (let t of fresh)stood.set(t, bundles);
656
+ }
657
+ let batches = new Set(asked.map((t)=>stood.get(t)));
658
+ return Promise.all(batches).then((all)=>all.flat());
659
+ };
660
+ let read = async (asked, tool = toolOf(asked))=>{
661
+ if (!tool?.readOnly) {
662
+ throw new CallError('read', 'a read needs a read-only tool');
663
+ }
664
+ return await execute(asked, tool, false, true);
665
+ };
666
+ return {
667
+ rules: plans,
668
+ get registry () {
669
+ return catalog();
670
+ },
671
+ admit: (asked)=>{
672
+ let tool = toolOf(asked);
673
+ return tool && {
674
+ tool,
675
+ ensure: ()=>ensure([
676
+ catalog().get(tool.name) ?? tool
677
+ ]),
678
+ call: (o)=>born(asked, tool, o?.cut),
679
+ read: ()=>read(asked, tool)
680
+ };
681
+ },
682
+ get tools () {
683
+ return catalog().list();
684
+ },
685
+ // Once per tool per runner, however many callers ask, and only the rows
686
+ // that are missing or say something else: a tool row is the same row
687
+ // every time (its id is derived from the name), and writing it again would
688
+ // move an `updated` stamp for nothing — on every process that opens the
689
+ // graph. A caller that names the tool a call points at stands up that one
690
+ // row, which is what a server building a runner per request needs.
691
+ ensure: (names)=>ensure(catalog().list().filter((t)=>!names || names.includes(t.name))),
692
+ // A direct read has no stored lifecycle and owes no write reply.
693
+ read,
694
+ // Recorded work is written claimed before the tool runs.
695
+ call: async (asked)=>{
696
+ if (!asked.call) throw new CallError('call', 'a call needs a call');
697
+ return await born(asked);
698
+ },
699
+ run,
700
+ due,
701
+ drive,
702
+ // One write per call: a call whose tool returned meanwhile has moved its
703
+ // claim on, and its own answer stands.
704
+ interrupt: async (why, holder)=>{
705
+ let out = [];
706
+ let cut = holder == null ? [
707
+ ...held.values()
708
+ ] : (await g.read(line`.execution.by=${holder}&!results&.call&*`)).map((call)=>({
709
+ call
710
+ }));
711
+ for (let { call, started } of cut){
712
+ let id = call.entity.eid;
713
+ let fault = {
714
+ entity: {
715
+ eid: '$fault'
716
+ },
717
+ content: {
718
+ body: why
719
+ },
720
+ output: {
721
+ source: id
722
+ },
723
+ ...g.vocab.comp('notice') ? {
724
+ notice: {}
725
+ } : {}
726
+ };
727
+ try {
728
+ out.push(...await g.apply([
729
+ fault,
730
+ ...ending(call, started, 'interrupted', [
731
+ fault
732
+ ])
733
+ ]));
734
+ } catch (error) {
735
+ if (!(error instanceof Stale)) throw error;
736
+ }
737
+ }
738
+ return out;
739
+ },
740
+ interruptCall
741
+ };
742
+ };
743
+ /** Explicitly recover eligible calls and unanswered claims. A durable effect
744
+ * host recovers its recorded runs instead; it needs no startup scan. */ export let reconcile = (r)=>r.drive({
745
+ redrive: true
746
+ });
747
+ export { answerOf, faulted, HELD, MOST, pending, READY, RULES, structured, texts, toolEid, toolRow, WOKEN, worded, WORDS } from "./result.js";
748
+ //# sourceMappingURL=runner.js.map