@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/result.ts ADDED
@@ -0,0 +1,540 @@
1
+ // Tool identities and invocation receipts, shared by recorded work and reads.
2
+ import type { Bundle, Comp, Declared, Eid, Ready, Tool } from 'jsr:@yaks/graph@0.2.36'
3
+ import { identityEid } from '@yaks/graph/identity'
4
+ import { namedTool } from '@yaks/graph/call'
5
+ import { asked, emitted, ready } from '@yaks/graph/declared'
6
+ import { token } from '@yaks/graph/sha256'
7
+ import { PROVENANCE } from '@yaks/graph/provenance'
8
+ import { effectsIn, type Vocab } from '@yaks/vocab'
9
+ import { toolsDoc } from './vocab.js'
10
+ import { executionState } from './state.js'
11
+ import { json, valueIn } from './value.js'
12
+ import { type Clock, system } from '@yaks/fp'
13
+
14
+ /** A runner's clock unless it is given one: the runtime's timers, and
15
+ * `performance.now`, which the wall clock's adjustments never move, for how
16
+ * long a call took. */
17
+ export let measuring: Clock = { ...system, now: () => performance.now() }
18
+
19
+ /** The two effects this package declares, as written in the vocabulary: the
20
+ * call that is due now, and the one that is due once its wake has fired —
21
+ * each a query the runner also asks on its own, for what a crash left. */
22
+ export let RULES: Declared[] = effectsIn(toolsDoc)
23
+ .flatMap((e) => e.match ? [{ name: e.name, match: e.match }] : [])
24
+
25
+ /** Every call claimed and not yet answered: the identities explicit recovery
26
+ * asks for beside the rules, which owe nothing for a claimed call. A call its
27
+ * writer runs by an effect of its own (`tool_async`, @yaks/session) is that
28
+ * effect's to recover, as it is that effect's to run (`call_ready`). */
29
+ export let HELD = '$call .call, .execution, !results, !tool_async'
30
+
31
+ /** The rule that selects a call due now — the one whose emit names the result
32
+ * entity. */
33
+ export let READY = 'call_ready'
34
+
35
+ /** The rule that selects a deferred call once its wake has fired. */
36
+ export let WOKEN = 'call_woken'
37
+
38
+ // Each name's id, derived once: it is a hash, and a server that builds a
39
+ // runner per request names every tool it has each time.
40
+ let eids = new Map<string, Eid>()
41
+ let names = new Map<Eid, string>()
42
+
43
+ /** The entity id a call points at for a tool of this name: the id the
44
+ * vocabulary's `identity` on `tool.name` derives, so a graph's tool rows are
45
+ * the same rows every time a runner is built. */
46
+ export let toolEid = (name: string): Eid => {
47
+ let eid = eids.get(name)
48
+ if (!eid) {
49
+ eids.set(name, eid = identityEid('tool', [name]))
50
+ names.set(eid, name)
51
+ }
52
+ return eid
53
+ }
54
+
55
+ // An id already derived in this process needs no walk through a catalog.
56
+ export let toolNameAt = (eid: Eid): string | undefined => names.get(eid)
57
+
58
+ /** The row a registered tool advertises to stored calls and builders. */
59
+ export let toolRow = (tool: Tool): Bundle => {
60
+ let named = namedTool(tool)
61
+ return {
62
+ entity: { eid: toolEid(named.name) },
63
+ tool: {
64
+ name: named.name,
65
+ description: named.description,
66
+ revision: named.revision ?? null,
67
+ },
68
+ }
69
+ }
70
+
71
+ /** The most characters of an answer's text {@link worded} says: the copy on
72
+ * the result entity, what a model reads over MCP, a transcript's line. What
73
+ * lies past it is counted, not said — the answer itself is the bundles. */
74
+ export let WORDS = 256 * 1024
75
+
76
+ /** The most characters an answer may take as JSON before the runner refuses
77
+ * it as `too_large`: far below the longest string a JavaScript engine can
78
+ * build, so a door that sends an answer whole (MCP, `/apply`, `--json`) never
79
+ * fails to. */
80
+ export let MOST = 64 * 1024 * 1024
81
+
82
+ // JSON.stringify(answer, null, 2), said one bundle at a time.
83
+ let inset = (b: Bundle) =>
84
+ ' ' + JSON.stringify(b, null, 2).replaceAll('\n', '\n ')
85
+
86
+ // The most characters a text property is said in its JSON string: one that
87
+ // runs longer, or breaks lines, is prose, and `worded` says it as plain text
88
+ // beside its bundle.
89
+ let PROSE = 200
90
+
91
+ // A component's string a model reads better as plain text than escaped inside
92
+ // a JSON string: one that breaks lines or runs long, holding no control
93
+ // character but its line breaks and tabs, since a result must not command a
94
+ // terminal.
95
+ let prose = (v: unknown): v is string =>
96
+ typeof v == 'string' && (v.includes('\n') || v.length > PROSE) &&
97
+ // deno-lint-ignore no-control-regex -- control characters stay escaped
98
+ !/[\x00-\x08\x0b-\x1f\x7f-\x9f]/.test(v)
99
+
100
+ // A data bundle with its prose held out: each such property says, in its
101
+ // JSON string, the tag its block opens with, and the blocks follow, one per
102
+ // property, so the JSON still parses and the prose reads as written.
103
+ let heldOut = (b: Bundle): { json: Bundle; blocks: string[] } => {
104
+ let blocks: string[] = []
105
+ let json: Record<string, unknown> = { ...b }
106
+ for (let [k, c] of Object.entries(b)) {
107
+ if (k == 'entity' || k[0] == '$' || !c || typeof c != 'object') continue
108
+ let long = Object.entries(c as Comp).filter(([, v]) => prose(v))
109
+ if (!long.length || Array.isArray(c)) continue
110
+ let comp: Comp = { ...c as Comp }
111
+ for (let [p, v] of long as [string, string][]) {
112
+ let tag = `${k}.${p} ${b.entity.eid}`
113
+ comp[p] = `<${tag}>`
114
+ blocks.push(`<${tag}>\n${v}${v.endsWith('\n') ? '' : '\n'}</${k}.${p}>`)
115
+ }
116
+ json[k] = comp
117
+ }
118
+ return { json: json as Bundle, blocks }
119
+ }
120
+
121
+ // Pieces said in turn while they fit in `most` characters, and how many of
122
+ // the `n` are past them counted: a piece is made only once it is reached, so
123
+ // an answer of any size words in bounded time and space.
124
+ let capped = (pieces: Iterable<string>, n: number, most: number) => {
125
+ let text = ''
126
+ let i = 0
127
+ for (let s of pieces) {
128
+ if (text.length + s.length > most) {
129
+ return {
130
+ cut: true,
131
+ text: `${text}${s.slice(0, most - text.length)}\n… ${n - i} of ${n} ` +
132
+ `not said: an answer is worded in ${most} characters`,
133
+ }
134
+ }
135
+ text += s
136
+ i++
137
+ }
138
+ return { cut: false, text }
139
+ }
140
+
141
+ // A search answer carries a query-only hit, not the entity's whole body: the
142
+ // id it is called by (its human id where it has one, @yaks/graph/hit), the
143
+ // kind, title and words that found it, and, for a neighbour of something a
144
+ // call just made, the entity it is `near` (a possible twin), `related` to (a
145
+ // resource of another kind or further off) or was `said` before on (a
146
+ // person's earlier words or answered decision, with `by` naming them), its
147
+ // `status`, and for a comment the `target` it is on. Say that hit as one
148
+ // line for an MCP reader; structuredContent keeps its fields.
149
+ let hitOf = (b: Bundle): Comp | null => {
150
+ let hit = b.hit as Comp | undefined
151
+ return hit && typeof hit == 'object' && typeof hit.kind == 'string' &&
152
+ typeof hit.snippet == 'string'
153
+ ? hit
154
+ : null
155
+ }
156
+
157
+ let hitLine = (b: Bundle, hit: Comp): string => {
158
+ // deno-lint-ignore no-control-regex -- the search markers are intentional
159
+ let mark = /\x01([^\x02]*)\x02/g
160
+ // deno-lint-ignore no-control-regex -- a result must not command a terminal
161
+ let ctrl = /[\x00-\x1f\x7f-\x9f]/g
162
+ let clean = (s: string) => s.replace(/\s+/g, ' ').replace(ctrl, '').trim()
163
+ let said = (k: string) => typeof hit[k] == 'string' ? clean(hit[k]) : ''
164
+ let id = said('id') || b.entity.eid
165
+ let title = said('title')
166
+ let status = said('status')
167
+ let target = said('target')
168
+ let near = said('near')
169
+ let related = said('related')
170
+ let source = hit.source == 'meaning' ? ' (meaning)' : ''
171
+ let snippet = clean(String(hit.snippet).replace(mark, '*$1*'))
172
+ let before = said('said')
173
+ let of = near
174
+ ? `near ${near}: `
175
+ : related
176
+ ? `related to ${related}: `
177
+ : before
178
+ ? `${said('by') || 'said'} earlier, on ${before}: `
179
+ : ''
180
+ return `${of}${id}${title ? ` ${title}` : ''} · ${clean(String(hit.kind))}${
181
+ status ? ` ${status}` : ''
182
+ }${target ? ` on ${target}` : ''}${source}${snippet ? ` — ${snippet}` : ''}`
183
+ }
184
+
185
+ // The spine every written row has: its entity and the provenance the graph
186
+ // keeps about its writes.
187
+ let SPINE = new Set(['entity', ...PROVENANCE])
188
+
189
+ // What a tool's text answer carries: the spine, its words, the call it
190
+ // answers, and a fault's `refusal` or `exception`. An entity carrying more (a
191
+ // transcript entry, a comment, a memory, a row a tool made) is data, and its
192
+ // words alone would drop which one it is and who wrote it.
193
+ let SPOKEN = new Set([
194
+ ...SPINE,
195
+ 'content',
196
+ 'output',
197
+ 'refusal',
198
+ 'exception',
199
+ 'heard',
200
+ ])
201
+
202
+ // A bundle said as a line of its own: the words a call said, its value, or a
203
+ // hit. Words are what a tool answered under a name of its own (`$said`) or
204
+ // aimed at the call (`output{source}`, which a text answer keeps once it is
205
+ // written): a row the answer read or wrote is data even when words are all it
206
+ // holds, since its words alone would drop which entity it is. A value
207
+ // answered without words (./value.ts `valued`) is said as its JSON:
208
+ // the value travels once, and a door that sends text writes it. Null for
209
+ // data, said whole.
210
+ let line = (b: Bundle): string | null => {
211
+ let body = (b.content as Comp | undefined)?.body
212
+ let value = (b.output as Comp | undefined)?.value
213
+ if (
214
+ (b.entity.eid[0] == '$' || !!b.output) &&
215
+ Object.keys(b).every((k) => k[0] == '$' || SPOKEN.has(k))
216
+ ) {
217
+ if (typeof body == 'string') return body
218
+ if (value !== undefined && !b.content) {
219
+ return json(value)
220
+ }
221
+ }
222
+ let hit = hitOf(b)
223
+ return hit ? hitLine(b, hit) : null
224
+ }
225
+
226
+ /**
227
+ * A tool's answer as text: each bundle as a line where it is one — a text
228
+ * answer's `content{body}`, or a compact `hit` line for a search result — and
229
+ * the rest as JSON, each run of data bundles one JSON array, so the data in an
230
+ * answer always parses and the lines between read as lines. An answer of data
231
+ * alone is one array, `JSON.stringify(answer, null, 2)`. A component's prose
232
+ * (a string that breaks lines or runs past 200 characters, such as a
233
+ * `doc.body`) is said as plain text: its JSON string holds the tag of a block
234
+ * that follows the bundle, which ends the array. An entity that carries words
235
+ * among other components (a transcript entry, a comment) is data: said whole,
236
+ * its eid and its writer with its words. It is copied onto the result entity
237
+ * as `content{body}` so a model, a terminal and a transcript all read the
238
+ * answer the same way. It says at most `most` characters, each bundle only
239
+ * once it is reached, and counts the rest, so an answer of any size words in
240
+ * bounded time and space.
241
+ *
242
+ * ```ts
243
+ * import { assertEquals } from '@std/assert'
244
+ * let said = (body: string) => ({
245
+ * entity: { eid: '$said' },
246
+ * content: { body },
247
+ * output: { source: 'c1' },
248
+ * })
249
+ * assertEquals(worded([said('one'), said('two')]), 'one\ntwo')
250
+ * let value = { entity: { eid: '$said' }, output: { value: { n: 1 } } }
251
+ * assertEquals(worded([value]), '{"n":1}')
252
+ * let entry = { ...said('hi'), entry: { session: 's', seq: 2 } }
253
+ * assertEquals(
254
+ * worded([said('one'), entry, said('two')]),
255
+ * 'one\n' + JSON.stringify([entry], null, 2) + '\ntwo',
256
+ * )
257
+ * let task = { entity: { eid: 't1' }, doc: { body: 'Two\n"lines"' } }
258
+ * assertEquals(
259
+ * worded([task]),
260
+ * JSON.stringify([{ ...task, doc: { body: '<doc.body t1>' } }], null, 2) +
261
+ * '\n<doc.body t1>\nTwo\n"lines"\n</doc.body>',
262
+ * )
263
+ * assertEquals(
264
+ * worded([said('one'), said('two'), said('three')], 5),
265
+ * 'one\nt\n… 2 of 3 not said: an answer is worded in 5 characters',
266
+ * )
267
+ * ```
268
+ */
269
+ export let worded = (answer: Bundle[], most = WORDS): string => {
270
+ if (!answer.length) return '[]'
271
+ // A leading run's `[` is outside the budget, as the closing line is: the
272
+ // budget is the answer's own characters.
273
+ let open = ''
274
+ let run = false
275
+ let pieces = function* () {
276
+ for (let [i, b] of answer.entries()) {
277
+ let words = line(b)
278
+ if (words != null) {
279
+ yield (run ? '\n]' : '') + (i ? '\n' : '') + words
280
+ run = false
281
+ continue
282
+ }
283
+ let { json, blocks } = heldOut(b)
284
+ if (!i) open = '[\n'
285
+ let s = (run ? ',\n' : i ? '\n[\n' : '') + inset(json)
286
+ run = !blocks.length
287
+ yield run ? s : `${s}\n]\n${blocks.join('\n')}`
288
+ }
289
+ }
290
+ let { cut, text } = capped(pieces(), answer.length, most)
291
+ return open + text + (!cut && run ? '\n]' : '')
292
+ }
293
+
294
+ let pendingResult = (answer: Bundle[]) => {
295
+ let value = valueIn(answer)
296
+ if (value?.running !== true || typeof value.result_handle != 'string') return
297
+ let spoken = answer.some((b) =>
298
+ (b.output as Comp | undefined)?.value === value && line(b) != null
299
+ )
300
+ if (spoken) return { running: true, result_handle: value.result_handle }
301
+ }
302
+
303
+ /**
304
+ * A tool's answer as the texts a door that sends several sends (MCP's content
305
+ * blocks): its data first, as JSON, then the prose held out of it, then the
306
+ * lines said beside it, so a reader that parses the first text finds the data
307
+ * and nothing glued onto it. An answer of one kind without prose is one text,
308
+ * {@link worded}.
309
+ *
310
+ * ```ts
311
+ * import { assertEquals } from '@std/assert'
312
+ * let row = { entity: { eid: 't1' }, doc: { title: 'Mossvale' } }
313
+ * let note = { entity: { eid: '$said' }, content: { body: 'Checked.' } }
314
+ * assertEquals(texts([row, note]), [JSON.stringify([row], null, 2), 'Checked.'])
315
+ * assertEquals(texts([row]), [worded([row])])
316
+ * let task = { entity: { eid: 't2' }, doc: { body: 'One\ntwo' } }
317
+ * assertEquals(texts([task]), [
318
+ * JSON.stringify([{ ...task, doc: { body: '<doc.body t2>' } }], null, 2),
319
+ * '<doc.body t2>\nOne\ntwo\n</doc.body>',
320
+ * ])
321
+ * ```
322
+ */
323
+ export let texts = (answer: Bundle[], most = WORDS): string[] => {
324
+ let pending = pendingResult(answer)
325
+ return pending
326
+ ? [json(pending), ...bundleTexts(answer, most)]
327
+ : bundleTexts(answer, most)
328
+ }
329
+
330
+ let bundleTexts = (answer: Bundle[], most: number): string[] => {
331
+ let words = answer.filter((b) => line(b) != null)
332
+ let data = answer.filter((b) => line(b) == null).map(heldOut)
333
+ let long = data.filter((d) => d.blocks.length)
334
+ if (!data.length || (!words.length && !long.length)) {
335
+ return [worded(answer, most)]
336
+ }
337
+ let blocks = long.map((d, i) => (i ? '\n' : '') + d.blocks.join('\n'))
338
+ return [
339
+ worded(data.map((d) => d.json), most),
340
+ ...long.length ? [capped(blocks, long.length, most).text] : [],
341
+ ...words.length ? [worded(words, most)] : [],
342
+ ]
343
+ }
344
+
345
+ /**
346
+ * A tool's answer as data, for a reader that parses rather than reads: the
347
+ * bundles under `result`, or, from a tool that declares an `outputSchema`
348
+ * because its answer is not entities, the {@link valueIn} it answered in that
349
+ * shape. A refusal carries no such value, and is its bundles like any other.
350
+ * MCP sends this as `structuredContent`; `yak … --json` prints it.
351
+ */
352
+ export let structured = (
353
+ tool: { outputSchema?: Record<string, unknown> },
354
+ answer: Bundle[],
355
+ ): Record<string, unknown> =>
356
+ (tool.outputSchema ? valueIn(answer) : undefined) ??
357
+ { result: answer, ...pendingResult(answer) }
358
+
359
+ // A bundle that says nothing once its value and images are taken out: the
360
+ // spine, and the call it was aimed at.
361
+ let bare = (b: Bundle): boolean =>
362
+ Object.entries(b).every(([k, c]) =>
363
+ SPINE.has(k) || k[0] == '$' || c === undefined ||
364
+ (k == 'output' && Object.keys(c ?? {}).every((p) => p == 'source'))
365
+ )
366
+
367
+ /**
368
+ * What a tool's {@link texts} say that its {@link structured} answer does not
369
+ * hold, worded, for a door that sends both to a reader that reads only the
370
+ * data. An answer of entities holds every bundle under `result`, so nothing;
371
+ * a value holds only itself, so the words beside it and every other bundle
372
+ * are said here. Images are sent as images, not words.
373
+ *
374
+ * ```ts
375
+ * import { assertEquals } from '@std/assert'
376
+ * let schema = { outputSchema: { type: 'object' } }
377
+ * let said = {
378
+ * entity: { eid: '$said' },
379
+ * content: { body: 'Two components.' },
380
+ * output: { source: 'c1', value: { n: 2 } },
381
+ * }
382
+ * assertEquals(aside(schema, [said]), 'Two components.')
383
+ * assertEquals(aside(schema, [{ ...said, content: undefined }]), undefined)
384
+ * assertEquals(aside({}, [said]), undefined)
385
+ * ```
386
+ */
387
+ export let aside = (
388
+ tool: { outputSchema?: Record<string, unknown> },
389
+ answer: Bundle[],
390
+ most = WORDS,
391
+ ): string | undefined => {
392
+ let value = tool.outputSchema ? valueIn(answer) : undefined
393
+ if (value === undefined) return undefined
394
+ let rest = answer.flatMap((b) => {
395
+ if (!b.output) return [b]
396
+ let { value: v, images: _, ...output } = b.output as Comp
397
+ let left = {
398
+ ...b,
399
+ output: v === value || v === undefined ? output : { ...output, value: v },
400
+ }
401
+ return bare(left) ? [] : [left]
402
+ })
403
+ return rest.length ? bundleTexts(rest, most).join('\n') : undefined
404
+ }
405
+
406
+ // The runner's own record of one call, told apart from the answer by identity,
407
+ // never by shape: a tool that reads transcripts answers other calls and their
408
+ // results, and those are the answer.
409
+ let owned = (call: Eid) => (b: Bundle): boolean =>
410
+ b.entity.eid == call || (b.result as Comp | undefined)?.call == call
411
+
412
+ /**
413
+ * Did this call fail? Read from the runner's own record — `execution{state}`
414
+ * on the call — rather than guessed from the shape of the answer: a tool that
415
+ * queries for broken rows (or failed calls) returns entities carrying `error`,
416
+ * `exception` and `execution`, and reporting faults is not itself a fault.
417
+ */
418
+ export let faulted = (landed: Bundle[], call: Eid): boolean => {
419
+ let row = landed.find((b) => b.entity.eid == call)
420
+ return !!row && ['failed', 'interrupted'].includes(
421
+ executionState(row, landed) ?? '',
422
+ )
423
+ }
424
+
425
+ /**
426
+ * Is the call still running in what came back? A stopping server answers a
427
+ * call whose tool has not returned with the call as it stands, claimed and
428
+ * unanswered, and where its answer will be kept (@yaks/tools
429
+ * `Invocation.call`). Read from the runner's own record, as {@link faulted}.
430
+ */
431
+ export let pending = (landed: Bundle[], call: Eid): boolean => {
432
+ let row = landed.find((b) => b.entity.eid == call)
433
+ return !!row && executionState(row, landed) == 'running'
434
+ }
435
+
436
+ /**
437
+ * The fault a failed call left, aimed at it: its `refusal{code}`, its
438
+ * `exception` or its interruption's `notice`, beside the words it said. None
439
+ * for a call that answered, however its answer is shaped ({@link faulted}).
440
+ */
441
+ export let faultOf = (landed: Bundle[], call: Eid): Bundle | undefined =>
442
+ faulted(landed, call)
443
+ ? landed.find((b) =>
444
+ (b.output as Comp | undefined)?.source == call &&
445
+ !!(b.refusal || b.exception || b.notice)
446
+ )
447
+ : undefined
448
+
449
+ /**
450
+ * What a call answered, for display: the tool's own bundles, without the
451
+ * runner's record of this call — the call itself and its result, which
452
+ * carries a copy of the answer's text so a transcript can show one line per
453
+ * result; a caller rendering the answer itself would otherwise show it twice.
454
+ */
455
+ export let answerOf = (landed: Bundle[], call: Eid): Bundle[] =>
456
+ landed.filter((b) => !owned(call)(b))
457
+
458
+ /** Plan invocation receipts from the declared rules, including their stable IDs. */
459
+ export let results = (
460
+ vocab: Vocab,
461
+ now: () => number,
462
+ ): {
463
+ rules: Ready[]
464
+ /** {@link HELD}, as this graph can query it, or nothing where a graph
465
+ * records no claims */
466
+ held?: Ready['plan']['patterns'][number]['filter']
467
+ ending: (
468
+ call: Bundle,
469
+ started: number | undefined,
470
+ state: string,
471
+ said: Bundle[],
472
+ before?: string | null,
473
+ ) => Bundle[]
474
+ } => {
475
+ // The rules as this graph can query them (@yaks/graph `asked`). A graph that
476
+ // schedules nothing never loaded the wake components: there `!wake` matches
477
+ // everything and drops out, and `call_woken`, which requires them, never
478
+ // matches — one rule text, correct in both graphs.
479
+ let plans: Ready[] = ready(RULES)
480
+ .map((p) => ({ ...p, plan: asked(p.plan, vocab) }))
481
+ .filter((p): p is Ready => !!p.plan)
482
+ let answering = plans.find((p) => p.rule.name == READY)!
483
+ let woken = plans.find((p) => p.rule.name == WOKEN)
484
+ // HELD as this graph can query it, the way the rules are asked.
485
+ // A graph that records no claims (no `execution`) holds none.
486
+ let held = asked(ready([{ name: 'held', match: HELD }])[0].plan, vocab)
487
+ ?.patterns[0].filter
488
+ // The result entity, built the way the rule would write it: one match of
489
+ // `call_ready`, emitted. Its id is derived from that match, so it is the
490
+ // same entity however many times a call is run.
491
+ let attached = (id: Eid, ms?: number, sleeps = false): Bundle => {
492
+ let rule = sleeps && woken ? woken : answering
493
+ let name = rule.plan.patterns[0].entity!
494
+ let [made] = emitted(rule, {
495
+ entities: [id, null],
496
+ vars: { [name]: id },
497
+ }, vocab)
498
+ return {
499
+ ...made,
500
+ result: { ...made.result as Comp, ...ms == null ? {} : { ms } },
501
+ }
502
+ }
503
+
504
+ // What ends a claimed call: the result the rule names, worded from what it
505
+ // said, and the claim moved on from `running`, refused if another hand
506
+ // moved it first.
507
+ // How long it ran is left out where nobody saw it start.
508
+ let ending = (
509
+ call: Bundle,
510
+ started: number | undefined,
511
+ state: string,
512
+ said: Bundle[],
513
+ before: string | null = 'running',
514
+ ): Bundle[] => [
515
+ {
516
+ ...attached(
517
+ call.entity.eid,
518
+ started == null ? undefined : Math.round(now() - started),
519
+ !!call.wake,
520
+ ),
521
+ content: { body: worded(said) },
522
+ $was: { result: { call: null } },
523
+ },
524
+ {
525
+ entity: { eid: call.entity.eid },
526
+ execution: { by: (call.execution as Comp)?.by ?? null },
527
+ ...(state == 'interrupted' ? { interrupted: { code: 'transport' } } : {}),
528
+ $was: {
529
+ execution: {
530
+ by: before == null ? null : token((call.execution as Comp)?.by),
531
+ },
532
+ },
533
+ },
534
+ ]
535
+
536
+ return { rules: plans, held, ending }
537
+ }
538
+
539
+ export { said } from './said.js'
540
+ export { display } from './display.js'
package/routes.js ADDED
@@ -0,0 +1,46 @@
1
+ // A declared tool at an HTTP door. The host resolves the tool and caller;
2
+ // this reads the invocation and answers its result or expected refusal.
3
+ import { parsed } from "./args.js";
4
+ import { CallError, refused } from "./errors.js";
5
+ let object = (v)=>!!v && typeof v == 'object' && !Array.isArray(v);
6
+ /** POST `{name,args,at?}` to one caller-scoped command runner. */ let command = (run)=>async (req)=>{
7
+ if (req.method != 'POST') {
8
+ return Response.json({
9
+ error: {
10
+ code: 'method_not_allowed',
11
+ message: 'command takes POST'
12
+ }
13
+ }, {
14
+ status: 405
15
+ });
16
+ }
17
+ try {
18
+ let body = await req.json().catch(()=>{
19
+ throw new CallError('arguments', 'command body must be JSON');
20
+ });
21
+ if (!object(body)) {
22
+ throw new CallError('arguments', 'command body must be an object');
23
+ }
24
+ if (typeof body.name != 'string' || !body.name) {
25
+ throw new CallError('arguments', 'command needs a name');
26
+ }
27
+ if (body.at != null && typeof body.at != 'string') {
28
+ throw new CallError('arguments', 'command at must be a string');
29
+ }
30
+ let out = await run(body.name, parsed(body.args), body.at ?? undefined);
31
+ return Response.json({
32
+ ...out,
33
+ ok: true
34
+ });
35
+ } catch (e) {
36
+ return refused(e);
37
+ }
38
+ };
39
+ /** One HTTP route for a host that offers declared command invocation. */ export let routes = (host)=>host.command ? [
40
+ {
41
+ method: 'POST',
42
+ path: '/command',
43
+ handle: command(host.command)
44
+ }
45
+ ] : [];
46
+ //# sourceMappingURL=routes.js.map
package/routes.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"routes.js","sources":["./routes.ts"],"names":[],"mappings":"AAAA,0EAA0E;AAC1E,wEAAwE;AACxE,SAAS,MAAM,oBAAmB;AAClC,SAAS,SAAS,EAAE,OAAO,sBAAqB;AAIhD,IAAI,SAAS,CAAC,IACZ,CAAC,CAAC,KAAK,OAAO,KAAK,YAAY,CAAC,MAAM,OAAO,CAAC;AAUhD,gEAAgE,GAChE,IAAI,UAAU,CAAC,MAAsB,OAAO;IAC1C,IAAI,IAAI,MAAM,IAAI,QAAQ;MACxB,OAAO,SAAS,IAAI,CAAC;QACnB,OAAO;UAAE,MAAM;UAAsB,SAAS;QAAqB;MACrE,GAAG;QAAE,QAAQ;MAAI;IACnB;IACA,IAAI;MACF,IAAI,OAAgB,MAAM,IAAI,IAAI,GAAG,KAAK,CAAC;QACzC,MAAM,IAAI,UAAU,aAAa;MACnC;MACA,IAAI,CAAC,OAAO,OAAO;QACjB,MAAM,IAAI,UAAU,aAAa;MACnC;MACA,IAAI,OAAO,KAAK,IAAI,IAAI,YAAY,CAAC,KAAK,IAAI,EAAE;QAC9C,MAAM,IAAI,UAAU,aAAa;MACnC;MACA,IAAI,KAAK,EAAE,IAAI,QAAQ,OAAO,KAAK,EAAE,IAAI,UAAU;QACjD,MAAM,IAAI,UAAU,aAAa;MACnC;MACA,IAAI,MAAM,MAAM,IAAI,KAAK,IAAI,EAAE,OAAO,KAAK,IAAI,GAAG,KAAK,EAAE,IAAI;MAC7D,OAAO,SAAS,IAAI,CAAC;QAAE,GAAG,GAAG;QAAE,IAAI;MAAK;IAC1C,EAAE,OAAO,GAAG;MACV,OAAO,QAAQ;IACjB;EACF;AAEA,uEAAuE,GACvE,OAAO,IAAI,SAAS,CAAC,OACnB,KAAK,OAAO,GACR;IAAC;MAAE,QAAQ;MAAQ,MAAM;MAAY,QAAQ,QAAQ,KAAK,OAAO;IAAE;GAAE,GACrE,EAAE,CAAA"}
package/routes.ts ADDED
@@ -0,0 +1,50 @@
1
+ // A declared tool at an HTTP door. The host resolves the tool and caller;
2
+ // this reads the invocation and answers its result or expected refusal.
3
+ import { parsed } from './args.js'
4
+ import { CallError, refused } from './errors.js'
5
+
6
+ type Handler = (request: Request) => Response | Promise<Response>
7
+ type Route = { method: string; path: string; handle: Handler }
8
+ let object = (v: unknown): v is Record<string, unknown> =>
9
+ !!v && typeof v == 'object' && !Array.isArray(v)
10
+
11
+ // What runs a command: by its name and arguments, and `at`, where the
12
+ // caller named where it is.
13
+ type Run = (
14
+ name: string,
15
+ args: Record<string, unknown>,
16
+ at?: string,
17
+ ) => Promise<Record<string, unknown>>
18
+
19
+ /** POST `{name,args,at?}` to one caller-scoped command runner. */
20
+ let command = (run: Run): Handler => async (req) => {
21
+ if (req.method != 'POST') {
22
+ return Response.json({
23
+ error: { code: 'method_not_allowed', message: 'command takes POST' },
24
+ }, { status: 405 })
25
+ }
26
+ try {
27
+ let body: unknown = await req.json().catch(() => {
28
+ throw new CallError('arguments', 'command body must be JSON')
29
+ })
30
+ if (!object(body)) {
31
+ throw new CallError('arguments', 'command body must be an object')
32
+ }
33
+ if (typeof body.name != 'string' || !body.name) {
34
+ throw new CallError('arguments', 'command needs a name')
35
+ }
36
+ if (body.at != null && typeof body.at != 'string') {
37
+ throw new CallError('arguments', 'command at must be a string')
38
+ }
39
+ let out = await run(body.name, parsed(body.args), body.at ?? undefined)
40
+ return Response.json({ ...out, ok: true })
41
+ } catch (e) {
42
+ return refused(e)
43
+ }
44
+ }
45
+
46
+ /** One HTTP route for a host that offers declared command invocation. */
47
+ export let routes = (host: { command?: Run }): Route[] =>
48
+ host.command
49
+ ? [{ method: 'POST', path: '/command', handle: command(host.command) }]
50
+ : []