@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.ts ADDED
@@ -0,0 +1,910 @@
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
+
59
+ import {
60
+ type Bundle,
61
+ type Comp,
62
+ derivedEid,
63
+ type Eid,
64
+ type Graph,
65
+ mint,
66
+ type NamedTool,
67
+ namedTool,
68
+ type Ready,
69
+ signed,
70
+ Stale,
71
+ type Tool,
72
+ who,
73
+ } from '@yaks/graph'
74
+ import { token } from '@yaks/graph/sha256'
75
+ import { line } from '@yaks/query'
76
+ import { Busy, CallError, UnfinishedCall } from './errors.js'
77
+ export { UnfinishedCall } from './errors.js'
78
+ import { persist } from './persist.js'
79
+ import { invoke } from './invoke.js'
80
+ import {
81
+ answerOf,
82
+ measuring,
83
+ results,
84
+ toolEid,
85
+ toolRow,
86
+ worded,
87
+ } from './result.js'
88
+ import type { Clock } from 'jsr:@yaks/fp@0.2.36'
89
+ import type { Vocab } from 'jsr:@yaks/vocab@0.2.36'
90
+ import { type Registry, registryOf } from './registry.js'
91
+
92
+ // What each call is doing right now in this process, keyed per graph, not per
93
+ // runner: a second runner over the same graph that is asked for a call in
94
+ // flight finds the first's promise instead of racing it, and an effect finds
95
+ // the call taken.
96
+ let running = new WeakMap<Graph, Map<Eid, Promise<Bundle[]>>>()
97
+
98
+ /** A refusal as its answer says it: the code that classes it and its words. */
99
+ export type Refusal = { code: string; said: string; summary?: string }
100
+
101
+ type Defer = (delay: number, reason: string) => Promise<void>
102
+
103
+ /** What hears a refusal: the refusal, the call it answered and the tool. */
104
+ export type Refused = (
105
+ refusal: Refusal,
106
+ call: Bundle,
107
+ tool?: string,
108
+ ) => unknown
109
+
110
+ /** What a runner is built with. */
111
+ export type Opts = {
112
+ /** what it can run: a function makes them only once a call asks for a
113
+ * tool, so a process that runs none builds none */
114
+ tools: Tool[] | Registry | (() => Tool[] | Registry)
115
+ /** the graph the tools read and write, when that is not the graph the calls
116
+ * are recorded in (a server that keeps its call records separately) */
117
+ host?: Graph
118
+ /** where caught failures are reported with the original thrown value, the
119
+ * call and the tool it asked for, independently of recording its answer.
120
+ * A refusal (a `CallError`, or an error @yaks/graph's
121
+ * `status` puts below 500) is never reported. A report that answers a
122
+ * promise is awaited before the call's answer is. */
123
+ report?: (err: unknown, call: Bundle, tool?: string) => unknown
124
+ /** what hears each refusal a call is answered with, apart from
125
+ * {@link report}: arguments its schema refuses, a tool named that this
126
+ * runner lacks (answered by {@link otherwise}), the tool's own `CallError`,
127
+ * a write the graph refuses. It is told the code and words of the refusal,
128
+ * the call and the tool it asked for: the name the call keeps
129
+ * (`call.name`), or else the tool that answered. Awaited like a report; what it
130
+ * throws is reported, and never changes the call's answer. */
131
+ refused?: Refused
132
+ /** what answers a call naming a tool this runner does not have. Omitted,
133
+ * nothing does: the call is left for whichever runner has that tool. */
134
+ otherwise?: Tool
135
+ /** which calls are this runner's to run. One it does not take is left
136
+ * alone, the way a call naming a tool it lacks is: a transcript's calls,
137
+ * say, which the transcript's own runner runs in the order the model asked
138
+ * (@yaks/session). Omitted, it takes every call it has a tool for. */
139
+ takes?: (call: Bundle) => boolean
140
+ /** the clock a runner keeps: `result.ms` is measured by its `now`, and a
141
+ * write storage refused is tried again after its `after` (default
142
+ * {@link measuring}) */
143
+ clock?: Clock
144
+ /** the most characters an answer may take as JSON; past it the call is
145
+ * refused as `too_large` (default {@link MOST}) */
146
+ most?: number
147
+ /** which entity this runner runs as: its claims record it in
148
+ * `execution.by`, and a call held by anyone else is left alone — a
149
+ * transcript imported from elsewhere arrives already executed, held by the
150
+ * process that made the calls, and no boot pass here re-runs it. A holder
151
+ * that has written an `exit` row holds nothing: its calls are free. A claim
152
+ * naming this owner that this runner is not running is left alone too: it
153
+ * is running in another runner under the same name. Omitted, this runner
154
+ * claims anonymously and takes any call nobody else holds. */
155
+ owner?: Eid
156
+ /** whether a holder other than {@link owner} is known to have ended without
157
+ * writing its `exit` (a Durable Object reset under a call): its calls are
158
+ * free, as an exited holder's are. The host says; this package never
159
+ * looks. */
160
+ gone?: (holder: Eid) => boolean | Promise<boolean>
161
+ /** the program running these calls on this machine, as @yaks/process
162
+ * records one — `{pid, command, cwd}` — put on every call a tool is handed,
163
+ * for a tool that acts on the machine rather than the graph. The caller
164
+ * supplies it; this package touches no runtime API and never looks it up. */
165
+ process?: Comp
166
+ /** Extra bundles a direct caller is owed beside a tool's answer. A plugin
167
+ * may supply them without the tool or its transport knowing about them. */
168
+ reply?: Reply
169
+ /** record what a lone answer marks on the call's result, as a transcript
170
+ * keeps it, one entry per answer (@yaks/session): a refusal is
171
+ * `refusal{code}` beside `result{call}` and its words rather than an entity
172
+ * of its own, and a `$said` answer's components beside its words and source
173
+ * (an image it shows) are the result's ({@link ridden}). A defect keeps its
174
+ * own `exception` entity either way. */
175
+ onResult?: boolean
176
+ }
177
+
178
+ /** What a direct caller is owed beside a tool's answer: the call, what the
179
+ * tool answered, and what the call's own write applied, in; the bundles to add
180
+ * after that answer, out. `wrote` is the answer where the tool wrote and the
181
+ * write was kept, so an entity it created wears the `created` its write was
182
+ * stamped with, and it is empty for a read, a rehearsal or a refusal, whose
183
+ * answer is entities that were there already or were never written. */
184
+ export type Reply = (
185
+ call: Bundle,
186
+ answer: Bundle[],
187
+ wrote: Bundle[],
188
+ ) => Promise<Bundle[]>
189
+
190
+ /** The kind a written bundle made its entity, if it made one: a created
191
+ * entity's kind, or a kind that is a mark (@yaks/vocab `CompInfo.mark`) whose
192
+ * `at` this write stamped, so marked for the first time. What a {@link Reply}
193
+ * reads of `wrote` to find the entities its call made. */
194
+ export let became = (vocab: Vocab, b: Bundle): string | undefined => {
195
+ if (b.tombstone) return undefined
196
+ if (b.created) return vocab.kindOf(b)
197
+ return Object.keys(b).find((c) => {
198
+ let info = vocab.comp(c)
199
+ return info?.kind && info.mark && (b[c] as Comp | undefined)?.at
200
+ })
201
+ }
202
+
203
+ // What `work` answers, or what `instead` says once `cut` aborts first. An
204
+ // `instead` that says nothing leaves the answer to `work`.
205
+ let unless = (
206
+ work: Promise<Bundle[]>,
207
+ cut: AbortSignal | undefined,
208
+ instead: () => Bundle[] | undefined,
209
+ ): Promise<Bundle[]> => {
210
+ if (!cut) return work
211
+ let off!: () => void
212
+ let gone = new Promise<Bundle[]>((done) => {
213
+ off = () => {
214
+ let said = instead()
215
+ if (said) done(said)
216
+ }
217
+ if (cut.aborted) off()
218
+ else cut.addEventListener('abort', off, { once: true })
219
+ })
220
+ return Promise.race([work, gone]).finally(() =>
221
+ cut.removeEventListener('abort', off)
222
+ )
223
+ }
224
+
225
+ // What a caller let go of a call still running is told: where its answer will
226
+ // be kept, and what an interruption means for it.
227
+ let outrun = (id: Eid, tool: string): Bundle => ({
228
+ entity: { eid: '$said' },
229
+ content: {
230
+ body: `${tool} is still running as call ${id}, and this server is ` +
231
+ 'stopping. Its answer is kept on the call: read it with graph_query ' +
232
+ `.result.call=${id}. If the server ends before the tool returns, the ` +
233
+ 'call ends interrupted, and can be asked again.',
234
+ },
235
+ output: { source: id },
236
+ })
237
+
238
+ /** One admitted call, retaining its tool through execution while registration
239
+ * advertises the provider's current declaration at the stable tool identity. */
240
+ export type Invocation = {
241
+ tool: NamedTool
242
+ ensure: () => Promise<Bundle[]>
243
+ /** Run it recorded. Once `cut` aborts, a stopping server's request lets go
244
+ * of the call. One whose answer is kept is answered without its
245
+ * {@link Reply}: the write stands, and only the extras read beside it are
246
+ * dropped, as a stopping server drops its reads. One whose tool has not
247
+ * returned is answered with the call, claimed and unanswered
248
+ * ({@link pending}), and where its answer will be kept; the tool runs on,
249
+ * and a host that closes first ends it as interrupted. */
250
+ call: (o?: { cut?: AbortSignal }) => Promise<Bundle[]>
251
+ read: () => Promise<Bundle[]>
252
+ }
253
+
254
+ /** A live runner: the rules a sweep queries, and the functions a caller
255
+ * invokes. */
256
+ export type Runner = {
257
+ /** the queries a deferred call is found by — the two declared effects, by
258
+ * name */
259
+ rules: Ready[]
260
+ /** The shared discovery and lookup catalog. */
261
+ registry: Registry
262
+ admit: (asked: Bundle) => Invocation | undefined
263
+ /** the tools it runs, named */
264
+ tools: NamedTool[]
265
+ /** write the `tool` rows that calls point at: the named tools', or every
266
+ * tool's. Each row is written at most once per runner however many times it
267
+ * is asked for, so a request handler may call it on the way into every
268
+ * call, naming the one tool that call points at. Answers what the rows it
269
+ * asked about were written as. */
270
+ ensure: (names?: string[]) => Promise<Bundle[]>
271
+ /** invoke a tool: the call in, the answer's bundles out. The call is
272
+ * written claimed and runs here; an `$alias` eid is given a fresh one. */
273
+ call: (asked: Bundle) => Promise<Bundle[]>
274
+ /** Run a read-only tool without recording a call, claim, result or reply. */
275
+ read: (asked: Bundle) => Promise<Bundle[]>
276
+ /** run one call that is already in the graph: its answer if it has one, the
277
+ * same promise if it is in flight here, nothing if a live process holds it,
278
+ * and {@link UnfinishedCall} if it was claimed anonymously and never
279
+ * answered */
280
+ run: (
281
+ call: Eid,
282
+ opts?: { redrive?: boolean; defer?: Defer },
283
+ ) => Promise<Bundle[]>
284
+ /** run one call a rule selected, if it is this runner's to take: what an
285
+ * effect handler calls. A held call, including one in flight here, or one
286
+ * removed since selection returns an empty answer. */
287
+ due: (
288
+ call: Eid,
289
+ opts?: { redrive?: boolean; defer?: Defer },
290
+ ) => Promise<Bundle[]>
291
+ /** Explicit recovery over eligible call identities, including unanswered
292
+ * claims. Durable effect hosts recover recorded runs instead of sweeping. */
293
+ drive: (opts?: { redrive?: boolean }) => Promise<Bundle[]>
294
+ /** end every call this runner claimed and is still running, as
295
+ * `interrupted{code}` saying `why`: what a process that is ending
296
+ * before its tools returned writes, so no claim of its own is left to lapse
297
+ * and run again somewhere it was never asked. Given a `holder`, the calls
298
+ * that holder claimed and never answered instead, read from the graph: what
299
+ * is written for a process that ended without writing it itself. */
300
+ interrupt: (why: string, holder?: Eid) => Promise<Bundle[]>
301
+ /** Give an unstarted or abandoned, anonymously claimed call a result
302
+ * without invoking its tool. A claimed call's effects may have landed. */
303
+ interruptCall: (
304
+ call: Eid,
305
+ why: string,
306
+ answer?: Bundle[],
307
+ ) => Promise<Bundle[]>
308
+ }
309
+
310
+ /** The result and the answer a transcript keeps (`onResult`), from what a
311
+ * call `made` and how its result `end`s in those words: a lone refusal rides
312
+ * on the result and keeps no entity, and a lone `$said` answer's components
313
+ * beside its words and source move onto the result, where a reader of the
314
+ * transcript's entries finds them. Its value as data rides as `result{value}`:
315
+ * `output` on an entry says the model spoke it, and a result is the tool's.
316
+ *
317
+ * ```ts
318
+ * import { assertEquals } from '@std/assert'
319
+ * let end = () => [{ entity: { eid: 'r' }, result: { call: 'c' } }]
320
+ * let words = {
321
+ * entity: { eid: '$said' },
322
+ * content: { body: 'shown' },
323
+ * output: { source: 'c' },
324
+ * }
325
+ * assertEquals(ridden([{ ...words, files: { n: 1 } }], 'done', end), [
326
+ * [{ entity: { eid: 'r' }, result: { call: 'c' }, files: { n: 1 } }],
327
+ * [words],
328
+ * ])
329
+ * let valued = { ...words, output: { source: 'c', value: { n: 1 } } }
330
+ * assertEquals(ridden([valued], 'done', end), [
331
+ * [{ entity: { eid: 'r' }, result: { call: 'c', value: { n: 1 } } }],
332
+ * [valued],
333
+ * ])
334
+ * ```
335
+ */
336
+ export let ridden = (
337
+ made: Bundle[],
338
+ state: string,
339
+ end: (said: Bundle[]) => Bundle[],
340
+ ): [Bundle[], Bundle[]] => {
341
+ let [one, ...more] = made
342
+ if (!one || more.length) return [end(made), made]
343
+ if (state == 'failed' && one.refusal && !one.exception) {
344
+ let [result, ...rest] = end(made)
345
+ return [[{ ...result, refusal: one.refusal }, ...rest], []]
346
+ }
347
+ let carried = one.entity.eid == '$said'
348
+ ? Object.keys(one).filter((k) =>
349
+ !['entity', 'content', 'output'].includes(k) && !k.startsWith('$')
350
+ )
351
+ : []
352
+ let value = one.entity.eid == '$said'
353
+ ? (one.output as Comp | undefined)?.value
354
+ : undefined
355
+ if (!carried.length && value === undefined) return [end(made), made]
356
+ let words = Object.fromEntries(
357
+ Object.entries(one).filter(([k]) => !carried.includes(k)),
358
+ ) as Bundle
359
+ let [result, ...rest] = end([words])
360
+ return [
361
+ [
362
+ {
363
+ ...result,
364
+ ...Object.fromEntries(carried.map((k) => [k, one[k]])),
365
+ ...value === undefined
366
+ ? {}
367
+ : { result: { ...result.result as Comp, value } },
368
+ },
369
+ ...rest,
370
+ ],
371
+ [words],
372
+ ]
373
+ }
374
+
375
+ /** Whether the runner writes what `tool` answered, ending in `state`, or
376
+ * hands the answer back as the tool built it. A read-only tool's answer is
377
+ * entities that already exist, and writing them would patch every row the
378
+ * query found and move its `updated` stamp; an applied tool's host has written
379
+ * its own. So the runner writes only its bookkeeping for either. A failure is
380
+ * written whatever the tool was: an error is worth recording. */
381
+ export let keeps = (
382
+ tool: Pick<Tool, 'readOnly' | 'applied'>,
383
+ state: string,
384
+ ): boolean =>
385
+ (!tool.readOnly && !tool.applied) || state == 'failed' ||
386
+ state == 'interrupted'
387
+
388
+ /**
389
+ * Build a runner over a graph.
390
+ *
391
+ * ```ts ignore
392
+ * let r = runner(g, { tools })
393
+ * await r.ensure()
394
+ * // the call entity is the record; the answer is the tool's own bundles
395
+ * let id = mint()
396
+ * let landed = await r.call({
397
+ * entity: { eid: id },
398
+ * call: { to: toolEid('text_echo'), args: {} },
399
+ * })
400
+ * answerOf(landed, id)
401
+ * ```
402
+ *
403
+ * Nothing polls the graph for calls. A server that wants the deferred ones too
404
+ * handles the two effects ./vocab.json declares — `fx.handle({ [r.rule.name]:
405
+ * (e) => run.due(e.entity.eid) })` for each of `run.rules`. A durable effect
406
+ * pool recovers recorded runs after a crash; it needs no startup reconcile.
407
+ * `reconcile()` is explicit recovery for calls without a recorded effect.
408
+ */
409
+ export let runner = (g: Graph, opts: Opts): Runner => {
410
+ let made: Registry | undefined
411
+ let catalog = () => made ??= registryOf(opts.tools)
412
+ let otherwise = opts.otherwise && namedTool(opts.otherwise)
413
+ let clock = opts.clock ?? measuring
414
+ let now = () => clock.now()
415
+ let { rules: plans, held: claimed, ending } = results(g.vocab, now)
416
+ let inflight = running.get(g) ?? new Map<Eid, Promise<Bundle[]>>()
417
+ running.set(g, inflight)
418
+ // The calls this runner claimed and whose tool has not returned, with when
419
+ // each started: what an interruption ends.
420
+ let held = new Map<Eid, { call: Bundle; started: number }>()
421
+ // Whose claim a call carries, as this runner reads it. Unclaimed, or claimed
422
+ // with no owner named, is `free`. This owner's own claim is `mine`: one
423
+ // this runner is not running is running in another runner under the same
424
+ // name, or failed there, and either way the owner is not over. Another's
425
+ // claim is `theirs` — unless its row records an `exit`, which makes the
426
+ // claim `lapsed`: nothing is coming back to finish the call, so it is
427
+ // taken the way a re-run takes one, claiming over `running`; so does a
428
+ // holder the host's `gone` says is over. The holder
429
+ // entity is fetched whole rather than queried by `.exit`, so a graph that
430
+ // tracks no processes simply never finds one — this package reads a
431
+ // component by name and requires nothing of the vocabulary.
432
+ let whose = async (
433
+ call: Bundle,
434
+ ): Promise<'free' | 'mine' | 'lapsed' | 'theirs'> => {
435
+ let by = (call.execution as Comp | undefined)?.by
436
+ if (by == null) return 'free'
437
+ // An unnamed runner's own claim still owes the unfinished-call check.
438
+ if (!opts.owner && by == owner) return 'free'
439
+ if (by == opts.owner) return 'mine'
440
+ if (await opts.gone?.(by as Eid)) return 'lapsed'
441
+ let [holder] = await g.get([String(by)], ['exit'])
442
+ return holder?.exit ? 'lapsed' : 'theirs'
443
+ }
444
+ // Each tool's row, as the batch that stood it up (`ensure`): one entry per
445
+ // tool name, several names sharing the batch they were written in.
446
+ let stood = new WeakMap<NamedTool, Promise<Bundle[]>>()
447
+ let registering = Promise.resolve<Bundle[]>([])
448
+ // The rows of these tools that are missing or say something else, written.
449
+ let standing = (some: NamedTool[]): Promise<Bundle[]> =>
450
+ Promise.resolve(g.get(some.map((t) => toolEid(t.name)), ['tool'])).then(
451
+ (held) => {
452
+ let said = new Map(held.map((b) => [b.entity.eid, b.tool as Comp]))
453
+ let stale = some.filter((t) => {
454
+ let row = said.get(toolEid(t.name))
455
+ return row?.name != t.name || row?.description != t.description ||
456
+ row?.revision != t.revision
457
+ })
458
+ return stale.length ? g.apply(stale.map(toolRow)) : []
459
+ },
460
+ )
461
+
462
+ // The answer, read back out of the graph: the result entity the rule named,
463
+ // plus every entity recording that it came from this call. This is what a
464
+ // caller sees when another process ran the tool. A read-only tool's answer
465
+ // was never written, so only the result comes back for one, and the way to
466
+ // see the answer again is to call it again.
467
+ let recalled = async (id: Eid): Promise<Bundle[]> => {
468
+ let result = await g.read(line`.result.call=${id}&*`)
469
+ if (!result.length) return []
470
+ let made = await g.read(line`.output.source=${id}&*`)
471
+ return [...made, ...result]
472
+ }
473
+
474
+ // The claim this runner writes.
475
+ let owner = opts.owner ?? mint()
476
+ let claim = (): Comp => ({ by: owner })
477
+ // The tool a call names, as this runner has it. A call naming a tool this
478
+ // runner does not have is left alone: another runner may have that tool,
479
+ // and failing the call here would be this runner's verdict on somebody
480
+ // else's work.
481
+ let toolOf = (call: Bundle): NamedTool | undefined =>
482
+ opts.takes && !opts.takes(call)
483
+ ? undefined
484
+ : catalog().get(String((call.call as Comp).to)) ?? otherwise
485
+ // One promise per call in flight in this process, in the map before the
486
+ // work starts, so nothing the work sets off finds the call untaken.
487
+ let tracked = (id: Eid, go: () => Promise<Bundle[]>): Promise<Bundle[]> => {
488
+ let pending = Promise.resolve().then(go)
489
+ .finally(() => inflight.delete(id))
490
+ inflight.set(id, pending)
491
+ return pending
492
+ }
493
+
494
+ // A call written and claimed in one batch, then run here. The claim is its
495
+ // own bundle: the call is the caller's, the claim is the runner's
496
+ // bookkeeping and carries no identity. A call somebody claimed first (only
497
+ // a named one can be) reads the way `run` reads it.
498
+ let born = (
499
+ asked: Bundle,
500
+ admitted?: NamedTool,
501
+ cut?: AbortSignal,
502
+ ): Promise<Bundle[]> => {
503
+ let id = asked.entity.eid.startsWith('$') ? mint() : asked.entity.eid
504
+ let call = { ...asked, entity: { ...asked.entity, eid: id } }
505
+ let tool = admitted ?? toolOf(call)
506
+ let work = tracked(id, async () => {
507
+ if (!tool) {
508
+ await g.apply([call])
509
+ return []
510
+ }
511
+ try {
512
+ await g.apply([call, {
513
+ entity: { eid: id },
514
+ execution: claim(),
515
+ $was: { execution: { by: null } },
516
+ }])
517
+ } catch (error) {
518
+ if (error instanceof Stale) return perform(id, {})
519
+ throw error
520
+ }
521
+ let [stored] = await g.get([id])
522
+ return execute(stored, tool, true, false, cut)
523
+ })
524
+ if (!tool) return work
525
+ // Let go at the cut while the tool is running: what goes wrong with it
526
+ // from then on has no caller to hear it, and is reported. A call the
527
+ // host's close ended meanwhile answers Stale, and is over. One whose tool
528
+ // has returned answers as it is, without its reply.
529
+ return unless(work, cut, () => {
530
+ if (!held.has(id)) return undefined
531
+ work.catch((error) =>
532
+ error instanceof Stale
533
+ ? undefined
534
+ : opts.report?.(error, call, tool.name)
535
+ )
536
+ return [
537
+ { entity: { eid: id }, execution: claim() },
538
+ outrun(id, tool.name),
539
+ ]
540
+ })
541
+ }
542
+
543
+ let perform = async (
544
+ id: Eid,
545
+ o: { redrive?: boolean; due?: boolean; defer?: Defer },
546
+ ): Promise<Bundle[]> => {
547
+ let [call] = await g.get([id])
548
+ if (!call?.call) {
549
+ if (o.due) return []
550
+ throw new CallError('call', 'Not a call: ' + id)
551
+ }
552
+ // A recurring call is not one invocation: it is the row that keeps asking
553
+ // for one. Each firing writes its own call entity, with an id derived from
554
+ // the schedule and the instant it fired, and that new call is what runs —
555
+ // so a finished call is never re-run, the record shows how many times the
556
+ // schedule fired, and the schedule itself stays a standing request. A wake
557
+ // recurs by its `every` or by its `while` (@yaks/wake). A one-shot has
558
+ // nothing to advance and runs in place.
559
+ let wake = call.wake as Comp | undefined
560
+ let went = (call.fired as Comp | undefined)?.at
561
+ if ((wake?.every || (wake?.while as unknown[] | null)?.length) && went) {
562
+ let asked = call.call as Comp
563
+ let [each] = signed([{
564
+ entity: { eid: derivedEid(`call ${id} ${went}`) },
565
+ call: { to: asked.to, args: asked.args, source: id },
566
+ }], who(call))
567
+ return born(each)
568
+ }
569
+ let held = await recalled(id)
570
+ if (held.length) return held
571
+ if (call.interrupted) return []
572
+ // A live process's claim is not this runner's to take, redrive or not,
573
+ // its own owner's included: a claim this runner is not running is running
574
+ // in another runner under the same name. A lapsed one is taken here and now,
575
+ // without waiting for a boot sweep.
576
+ let hold = await whose(call)
577
+ if (hold == 'theirs' || hold == 'mine') return []
578
+ let redrive = o.redrive || hold == 'lapsed'
579
+ // A durable run may have put its claim down while waiting. The empty
580
+ // execution record keeps call_ready from creating a second effect.
581
+ if (call.execution && !redrive && !o.defer) {
582
+ if (o.due) return []
583
+ throw new UnfinishedCall(id)
584
+ }
585
+ let tool = toolOf(call)
586
+ if (!tool) return []
587
+ let c = call.call as Comp
588
+ // The claim. A runner that loses it to another has nothing to run.
589
+ try {
590
+ await g.apply([{
591
+ entity: { eid: id },
592
+ execution: claim(),
593
+ $was: {
594
+ execution: {
595
+ by: redrive ? token((call.execution as Comp)?.by) : null,
596
+ },
597
+ call: Object.fromEntries(
598
+ g.vocab.props('call').filter((p) => p != 'id')
599
+ .map((p) => [p, token(c[p])]),
600
+ ),
601
+ },
602
+ }])
603
+ } catch (error) {
604
+ if (error instanceof Stale) return []
605
+ throw error
606
+ }
607
+ return execute(
608
+ { ...call, execution: claim() },
609
+ tool,
610
+ false,
611
+ false,
612
+ undefined,
613
+ o.defer,
614
+ )
615
+ }
616
+
617
+ // Running a claimed call: the tool, its answer, and the record of both.
618
+ let execute = async (
619
+ call: Bundle,
620
+ tool: NamedTool,
621
+ direct = false,
622
+ unrecorded = false,
623
+ cut?: AbortSignal,
624
+ defer?: Defer,
625
+ ): Promise<Bundle[]> => {
626
+ let id = call.entity.eid
627
+ let started = now()
628
+ held.set(id, { call, started })
629
+ // Writing the answer, where `keeps` says to. A rehearsal's answer is what
630
+ // a write would have been, and is not written either.
631
+ let land = async (
632
+ made: Bundle[],
633
+ state: string,
634
+ keep = keeps(tool, state),
635
+ code?: string,
636
+ ): Promise<Bundle[]> => {
637
+ let words: Bundle[] = []
638
+ let end = (said: Bundle[]) => ending(call, started, state, words = said)
639
+ let ended: Bundle[]
640
+ ;[ended, made] = opts.onResult
641
+ ? ridden(made, state, end)
642
+ : [end(made), made]
643
+ if (unrecorded) return [...made, ...ended]
644
+ let bundles = [
645
+ ...(keep ? made : []),
646
+ ...ended,
647
+ ...code ? [{ entity: { eid: id }, interrupted: { code } }] : [],
648
+ ]
649
+ // An answer that is written is worded as it was written, in the same
650
+ // transaction: each alias under the eid it became, stamped, with no
651
+ // request keys on it, as a caller reading the result later reads it.
652
+ let result = ended.find((b) => b.result)!.entity
653
+ let receipt = keep && words === made
654
+ ? (applied: Bundle[]) => [{
655
+ entity: result,
656
+ content: { body: worded(answerOf(applied, id)) },
657
+ }]
658
+ : undefined
659
+ // A retry reports the storage error separately from the call's failure,
660
+ // which was reported at its catch boundary before recording the answer.
661
+ // The exception's properties are stamped: only its catcher writes them.
662
+ let trusted = made.some((b) => b.exception)
663
+ let landed = await persist(
664
+ () =>
665
+ g.apply(bundles, {
666
+ ...trusted ? { trusted } : {},
667
+ ...receipt ? { receipt } : {},
668
+ }),
669
+ (e) => opts.report?.(e, call, tool.name),
670
+ clock,
671
+ )
672
+ return keep ? landed : [...made, ...landed]
673
+ }
674
+ let wrote: Bundle[] = []
675
+ let answered: Bundle[]
676
+ try {
677
+ answered = await invoke(
678
+ call,
679
+ tool,
680
+ g,
681
+ opts,
682
+ async (made, state, keep, code) => {
683
+ let out = await land(made, state, keep, code)
684
+ if (state == 'done' && keeps(tool, state) && keep !== false) {
685
+ wrote = answerOf(out, id)
686
+ }
687
+ return out
688
+ },
689
+ !!defer,
690
+ )
691
+ } catch (error) {
692
+ if (!defer || !(error instanceof Busy)) throw error
693
+ await g.apply([{
694
+ entity: { eid: id },
695
+ execution: { by: null },
696
+ $was: { execution: { by: token(owner) } },
697
+ }])
698
+ await defer(error.after, error.message)
699
+ return []
700
+ } finally {
701
+ held.delete(id)
702
+ }
703
+ if (unrecorded || !direct || !opts.reply || cut?.aborted) return answered
704
+ try {
705
+ return [
706
+ ...answered,
707
+ ...await unless(
708
+ opts.reply(call, answerOf(answered, id), wrote),
709
+ cut,
710
+ () => [],
711
+ ),
712
+ ]
713
+ } catch (error) {
714
+ await opts.report?.(error, call, tool.name)
715
+ return answered
716
+ }
717
+ }
718
+
719
+ let run: Runner['run'] = (id, o = {}) =>
720
+ inflight.get(id) ?? tracked(id, () => perform(id, o))
721
+
722
+ let due = async (
723
+ id: Eid,
724
+ o: { redrive?: boolean; defer?: Defer } = {},
725
+ ): Promise<Bundle[]> =>
726
+ inflight.has(id)
727
+ ? []
728
+ : await tracked(id, () => perform(id, { ...o, due: true }))
729
+
730
+ // Explicit recovery selects identities only. A due call is read in perform;
731
+ // projecting it here would load its components and computed lifecycle twice.
732
+ // Durable hosts instead recover their recorded effect rows, without drive.
733
+ let queued = async (): Promise<Eid[]> => {
734
+ let out = new Set<Eid>()
735
+ for (let p of plans) {
736
+ let { filter } = p.plan.patterns[0]
737
+ for (let b of await g.rows(filter)) out.add(b.eid as Eid)
738
+ }
739
+ for (let b of claimed ? await g.rows(claimed) : []) out.add(b.eid as Eid)
740
+ return [...out]
741
+ }
742
+
743
+ let drive = async (o: { redrive?: boolean } = {}): Promise<Bundle[]> => {
744
+ let out: Bundle[] = []
745
+ for (let id of await queued()) {
746
+ try {
747
+ out.push(...await due(id, o))
748
+ } catch (error) {
749
+ if (opts.report) {
750
+ let [call] = await g.get([id])
751
+ let to = String((call?.call as Comp | undefined)?.to)
752
+ await opts.report(error, call, catalog().get(to)?.name)
753
+ }
754
+ }
755
+ }
756
+ return out
757
+ }
758
+
759
+ let interruptCall = async (
760
+ id: Eid,
761
+ why: string,
762
+ answer?: Bundle[],
763
+ ): Promise<Bundle[]> => {
764
+ let [call] = await g.get([id])
765
+ if (!call?.call) throw new CallError('call', 'Not a call: ' + id)
766
+ let prior = await recalled(id)
767
+ if (prior.length) return prior
768
+ let execution = call.execution as Comp | undefined
769
+ if (execution && (call.interrupted || execution.by != null)) {
770
+ throw new UnfinishedCall(id)
771
+ }
772
+ let fault: Bundle = {
773
+ entity: { eid: '$fault' },
774
+ content: { body: why },
775
+ output: { source: id },
776
+ ...(g.vocab.comp('notice') ? { notice: {} } : {}),
777
+ }
778
+ let said = execution && answer ? answer : [fault]
779
+ let state = execution && answer ? 'done' : 'interrupted'
780
+ let end = (said: Bundle[]) =>
781
+ ending(call, undefined, state, said, execution ? 'running' : null)
782
+ let ended: Bundle[]
783
+ ;[ended, said] = opts.onResult
784
+ ? ridden(said, state, end)
785
+ : [end(said), said]
786
+ try {
787
+ return await g.apply([...said, ...ended])
788
+ } catch (error) {
789
+ if (error instanceof Stale) {
790
+ let prior = await recalled(id)
791
+ if (prior.length) return prior
792
+ throw new UnfinishedCall(id)
793
+ }
794
+ throw error
795
+ }
796
+ }
797
+
798
+ let ensure = (asked: NamedTool[]) => {
799
+ let fresh = asked.filter((t) => !stood.has(t))
800
+ if (fresh.length) {
801
+ let bundles = registering.catch(() => []).then(() =>
802
+ standing(fresh.map((t) => catalog().get(t.name) ?? t))
803
+ ).catch((error) => {
804
+ for (let t of fresh) {
805
+ if (stood.get(t) === bundles) stood.delete(t)
806
+ }
807
+ throw error
808
+ })
809
+ registering = bundles
810
+ for (let t of fresh) stood.set(t, bundles)
811
+ }
812
+ let batches = new Set(asked.map((t) => stood.get(t)!))
813
+ return Promise.all(batches).then((all) => all.flat())
814
+ }
815
+ let read = async (asked: Bundle, tool = toolOf(asked)) => {
816
+ if (!tool?.readOnly) {
817
+ throw new CallError('read', 'a read needs a read-only tool')
818
+ }
819
+ return await execute(asked, tool, false, true)
820
+ }
821
+
822
+ return {
823
+ rules: plans,
824
+ get registry() {
825
+ return catalog()
826
+ },
827
+ admit: (asked) => {
828
+ let tool = toolOf(asked)
829
+ return tool && {
830
+ tool,
831
+ ensure: () => ensure([catalog().get(tool.name) ?? tool]),
832
+ call: (o) => born(asked, tool, o?.cut),
833
+ read: () => read(asked, tool),
834
+ }
835
+ },
836
+ get tools() {
837
+ return catalog().list()
838
+ },
839
+ // Once per tool per runner, however many callers ask, and only the rows
840
+ // that are missing or say something else: a tool row is the same row
841
+ // every time (its id is derived from the name), and writing it again would
842
+ // move an `updated` stamp for nothing — on every process that opens the
843
+ // graph. A caller that names the tool a call points at stands up that one
844
+ // row, which is what a server building a runner per request needs.
845
+ ensure: (names) =>
846
+ ensure(catalog().list().filter((t) => !names || names.includes(t.name))),
847
+ // A direct read has no stored lifecycle and owes no write reply.
848
+ read,
849
+ // Recorded work is written claimed before the tool runs.
850
+ call: async (asked) => {
851
+ if (!asked.call) throw new CallError('call', 'a call needs a call')
852
+ return await born(asked)
853
+ },
854
+ run,
855
+ due,
856
+ drive,
857
+ // One write per call: a call whose tool returned meanwhile has moved its
858
+ // claim on, and its own answer stands.
859
+ interrupt: async (why, holder) => {
860
+ let out: Bundle[] = []
861
+ let cut: { call: Bundle; started?: number }[] = holder == null
862
+ ? [...held.values()]
863
+ : (await g.read(line`.execution.by=${holder}&!results&.call&*`))
864
+ .map((call) => ({ call }))
865
+ for (let { call, started } of cut) {
866
+ let id = call.entity.eid
867
+ let fault: Bundle = {
868
+ entity: { eid: '$fault' },
869
+ content: { body: why },
870
+ output: { source: id },
871
+ ...(g.vocab.comp('notice') ? { notice: {} } : {}),
872
+ }
873
+ try {
874
+ out.push(
875
+ ...await g.apply([
876
+ fault,
877
+ ...ending(call, started, 'interrupted', [fault]),
878
+ ]),
879
+ )
880
+ } catch (error) {
881
+ if (!(error instanceof Stale)) throw error
882
+ }
883
+ }
884
+ return out
885
+ },
886
+ interruptCall,
887
+ }
888
+ }
889
+
890
+ /** Explicitly recover eligible calls and unanswered claims. A durable effect
891
+ * host recovers its recorded runs instead; it needs no startup scan. */
892
+ export let reconcile = (r: Runner): Promise<Bundle[]> =>
893
+ r.drive({ redrive: true })
894
+
895
+ export {
896
+ answerOf,
897
+ faulted,
898
+ HELD,
899
+ MOST,
900
+ pending,
901
+ READY,
902
+ RULES,
903
+ structured,
904
+ texts,
905
+ toolEid,
906
+ toolRow,
907
+ WOKEN,
908
+ worded,
909
+ WORDS,
910
+ } from './result.js'