@yaks/host 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 (69) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +306 -2
  3. package/_dist/anatomy.d.ts +35 -0
  4. package/_dist/anatomy.d.ts.map +1 -0
  5. package/_dist/assembly.d.ts +94 -0
  6. package/_dist/assembly.d.ts.map +1 -0
  7. package/_dist/config.d.ts +150 -0
  8. package/_dist/config.d.ts.map +1 -0
  9. package/_dist/documents.d.ts +9 -0
  10. package/_dist/documents.d.ts.map +1 -0
  11. package/_dist/facets.d.ts +164 -0
  12. package/_dist/facets.d.ts.map +1 -0
  13. package/_dist/keepers.d.ts +15 -0
  14. package/_dist/keepers.d.ts.map +1 -0
  15. package/_dist/keywords.d.ts +3 -0
  16. package/_dist/keywords.d.ts.map +1 -0
  17. package/_dist/lending.d.ts +34 -0
  18. package/_dist/lending.d.ts.map +1 -0
  19. package/_dist/mod.d.ts +260 -0
  20. package/_dist/mod.d.ts.map +1 -0
  21. package/_dist/payments.d.ts +501 -0
  22. package/_dist/payments.d.ts.map +1 -0
  23. package/_dist/roles.d.ts +10 -0
  24. package/_dist/roles.d.ts.map +1 -0
  25. package/_dist/senders.d.ts +180 -0
  26. package/_dist/senders.d.ts.map +1 -0
  27. package/_dist/words.d.ts +27 -0
  28. package/_dist/words.d.ts.map +1 -0
  29. package/anatomy.js +432 -0
  30. package/anatomy.js.map +1 -0
  31. package/anatomy.ts +439 -0
  32. package/assembly.js +737 -0
  33. package/assembly.js.map +1 -0
  34. package/assembly.ts +930 -0
  35. package/config.js +149 -0
  36. package/config.js.map +1 -0
  37. package/config.ts +287 -0
  38. package/deno.json +1 -0
  39. package/documents.js +80 -0
  40. package/documents.js.map +1 -0
  41. package/documents.ts +105 -0
  42. package/facets.js +2 -0
  43. package/facets.js.map +1 -0
  44. package/facets.ts +236 -0
  45. package/keepers.js +7 -0
  46. package/keepers.js.map +1 -0
  47. package/keepers.ts +17 -0
  48. package/keywords.js +24 -0
  49. package/keywords.js.map +1 -0
  50. package/keywords.ts +25 -0
  51. package/lending.js +46 -0
  52. package/lending.js.map +1 -0
  53. package/lending.ts +77 -0
  54. package/mod.js +5 -0
  55. package/mod.js.map +1 -0
  56. package/mod.ts +356 -0
  57. package/package.json +79 -4
  58. package/payments.js +66 -0
  59. package/payments.js.map +1 -0
  60. package/payments.ts +665 -0
  61. package/roles.js +22 -0
  62. package/roles.js.map +1 -0
  63. package/roles.ts +18 -0
  64. package/senders.js +58 -0
  65. package/senders.js.map +1 -0
  66. package/senders.ts +272 -0
  67. package/words.js +134 -0
  68. package/words.js.map +1 -0
  69. package/words.ts +210 -0
package/assembly.ts ADDED
@@ -0,0 +1,930 @@
1
+ /** Assemble a graph from role-selected facets and capabilities lent by its host. */
2
+ import type {
3
+ Actor,
4
+ Bundle,
5
+ Comp,
6
+ Graph,
7
+ GraphBranches,
8
+ NamedTool,
9
+ Plugin,
10
+ } from '@yaks/graph'
11
+ import { type graph, namesBetween, toolIn, transactionIn } from '@yaks/graph'
12
+ import { after, type Clock, groupBy, id } from '@yaks/fp'
13
+ import { toolName } from '@yaks/graph/call'
14
+ import { loadTools, type Search, tier } from '@yaks/graph/tools'
15
+ import type { Reply, Runner, runner } from '@yaks/tools'
16
+ import { type Registry, registry } from '@yaks/tools/registry'
17
+ import { CallError } from '@yaks/tools/errors'
18
+ import { toolsIn } from '@yaks/vocab/tools'
19
+ import { effectsIn } from '@yaks/vocab'
20
+ import type { VocabDoc } from '@yaks/vocab'
21
+ import type { Effects, Handlers, Rank } from 'jsr:@yaks/effects@0.2.36'
22
+ import {
23
+ answering as operationHandler,
24
+ type Operation,
25
+ } from '@yaks/effects/invocation'
26
+ import type { Extension, History, Stmt } from 'jsr:@yaks/sql@0.2.36'
27
+ import { gather } from '@yaks/ui/contributions'
28
+ import type {
29
+ Arrived,
30
+ Authenticate,
31
+ Filter,
32
+ Handler,
33
+ Offers,
34
+ Route,
35
+ Told,
36
+ } from 'jsr:@yaks/api@0.2.36'
37
+ import type { Feed, Host, Role } from './mod.ts'
38
+ import {
39
+ type Config,
40
+ type Configured,
41
+ configured,
42
+ type Options,
43
+ } from './config.js'
44
+ import type { Duty, FacetName, Load, Meaning } from './facets.ts'
45
+ import { type Composition, compositionAnatomy } from './anatomy.js'
46
+ import { common, ROLES } from './roles.js'
47
+ import { type Taken, taking, type Words, wordsOf } from './words.js'
48
+ import { selected } from './documents.js'
49
+ import { lending } from './lending.js'
50
+
51
+ /** The parts built from facets, rather than lent by a concrete host. */
52
+ type Built =
53
+ | 'anatomy'
54
+ | 'observe'
55
+ | 'config'
56
+ | 'roles'
57
+ | 'vocab'
58
+ | 'derived'
59
+ | 'storage'
60
+ | 'graph'
61
+ | 'fx'
62
+ | 'ui'
63
+ | 'who'
64
+ | 'feed'
65
+ | 'handler'
66
+ | 'routes'
67
+ | 'filters'
68
+ | 'tools'
69
+ | 'registry'
70
+ | 'search'
71
+ | 'reply'
72
+ | 'runner'
73
+ | 'defer'
74
+
75
+ /** Storage and runtime capabilities; the assembly owns neither their IO nor lifetime. */
76
+ export type Binding = {
77
+ host: Omit<Host, Built>
78
+ storage: (
79
+ host: Host,
80
+ extend: Extension[],
81
+ words: Words,
82
+ history?: History,
83
+ ) => Host['storage']
84
+ effects: (host: Host, disabled: string[]) => Effects
85
+ /** The concrete host's implementations of callable effects. */
86
+ operations?: (host: Host) => Record<string, Operation>
87
+ /** Host clause compilers follow the plugins' compilers. */
88
+ extend?: (host: Host) => Extension[]
89
+ /** Construct the graph with any additional hooks and options the host owns. */
90
+ graph?: typeof graph
91
+ /** The branches of the host's store, each with the graph its own host
92
+ * composes over it (@yaks/graph `GraphBranches`), asked once the store is
93
+ * bound. */
94
+ branches?: (host: Host) => GraphBranches | undefined
95
+ /** Suppress the assembled plugins' post-commit effects on a branch.
96
+ * Observers attached to the bound graph can still see its commits. */
97
+ unobserved?: boolean
98
+ /** Bring the store to its composed schema, given the statements the graph
99
+ * plugins need beside the store's own, after extensions have bound and
100
+ * before graph plugins are asked. A reader leaves it out. */
101
+ schema?: (host: Host, stmts: Stmt[]) => void
102
+ /** The host's graph-dependent capabilities, before effect and tool factories. */
103
+ ready?: (host: Host) => void
104
+ /** Combine the host's text index with its meaning index, where it has one
105
+ * ({@link Host.meaning}). */
106
+ search?: (host: Host) => Search | undefined
107
+ /** Operations supplied by the concrete host beside graph and plugin tools. */
108
+ tools?: {
109
+ package: string
110
+ offer: (host: Host) => NamedTool[]
111
+ /** What the offer is made from: the registry and its runner are made
112
+ * again when it moves. */
113
+ revision?: () => unknown
114
+ /** Whether the graph's generic tools are offered beside it (they are by
115
+ * default). A host whose callers reach the graph through doors of its own
116
+ * offers only its own and its plugins'. */
117
+ generic?: boolean
118
+ }
119
+ /** How the host's runner runs calls, beside what the assembly gives it:
120
+ * the graph its records are written through, where that is not the host's
121
+ * (a store whose door guards what it is sent records calls as itself),
122
+ * which calls are its to run, and where its failures go. */
123
+ calls?: (host: Host) => {
124
+ records?: Graph
125
+ takes?: (call: Bundle) => boolean
126
+ report?: (error: unknown, call: Bundle, tool?: string) => unknown
127
+ }
128
+ actor?: Actor | null
129
+ process?: Comp
130
+ readOnly?: boolean
131
+ /** The clock the host keeps: its graph's and its runner's (default each
132
+ * one's own). */
133
+ clock?: Clock
134
+ /** Per-host capabilities added to a configured occurrence's options. */
135
+ options?: (plugin: string, options: Options) => Options
136
+ /** Loading and binding evidence belongs to this host, never the shared plan. */
137
+ observed?: Composition
138
+ }
139
+ export type Assembly = {
140
+ words: Words
141
+ /** The plugins whose graph facet says, under its options, that a store this
142
+ * host writes requires it (GraphFacet `required`): what a writing host
143
+ * records in the store beside its schema. */
144
+ required: string[]
145
+ /** Bind the loaded facets to the host's capabilities. Services are returned for its scheduler. */
146
+ bind: (binding: Binding) => {
147
+ host: Host
148
+ services: Duty[]
149
+ /** Interrupt calls already admitted by this host, without constructing a runner. */
150
+ interrupt: (why: string) => Promise<Bundle[]>
151
+ /** Await after draining admitted work, before closing graph or reporter. */
152
+ close: () => Promise<void>
153
+ }
154
+ }
155
+ export type AssemblyOpts = {
156
+ /** Read factories admit no imperative work; loaded before binding. */
157
+ readOnly?: boolean
158
+ /** Resolved plugin options, when the concrete host has a vault. */
159
+ plugins?: Configured[]
160
+ /** Already-loaded vocabulary, shared with the concrete host's schema plan. */
161
+ words?: Words
162
+ /** The graph's own vocabulary. Its component declarations shadow plugins. */
163
+ docs?: VocabDoc[]
164
+ observed?: Composition
165
+ part?: (name: string) => void
166
+ }
167
+ // At most one plugin may name the caller; two would mean the answer depends on
168
+ // import order, which is not an answer. A plugin whose options give it nobody
169
+ // to ask answers none. Whoever it is, this PROCESS is the fallback: a request
170
+ // no plugin claimed is this machine's own writing, not nobody's.
171
+ let doorman = (
172
+ graphs: Taken<'graph'>,
173
+ host: Host,
174
+ self: Actor | null,
175
+ ): Authenticate => {
176
+ let asks = graphs.flatMap(([r, options]) =>
177
+ r.authenticate?.(host, options ?? {}) ?? []
178
+ )
179
+ if (asks.length > 1) {
180
+ throw new CallError(
181
+ 'config',
182
+ `${asks.length} plugins authenticate — a door has one`,
183
+ )
184
+ }
185
+ let [ask] = asks
186
+ return ask
187
+ ? async (request, message) => (await ask(request, message)) ?? self
188
+ : () => self
189
+ }
190
+
191
+ // A plugin's `./effects` handling a name no vocabulary declares: code that
192
+ // would never run, since nothing owes it.
193
+ let undeclared = (plugin: string, name: string) =>
194
+ new CallError('config', `${plugin} handles ${name}, which nothing declares`)
195
+
196
+ // Two plugins' `./effects` handling one name: a run is done once, by one.
197
+ let twice = (name: string, plugins: string[]) =>
198
+ new CallError('config', `${name} is handled by both ${plugins.join(' and ')}`)
199
+
200
+ let withoutEffects = (plugin: Plugin): Plugin => {
201
+ let { effect: _, ...hooks } = plugin.hooks ?? {}
202
+ return {
203
+ ...plugin,
204
+ hooks,
205
+ rules: plugin.rules?.filter((rule) => rule.phase != 'effect'),
206
+ }
207
+ }
208
+
209
+ // Each release a host deferred, last first, every one run though an earlier
210
+ // throws; one failure is thrown as itself, several together. Safari lacks
211
+ // AsyncDisposableStack, and a host is shipped to browsers.
212
+ let released = async (releases: (() => void | Promise<void>)[]) => {
213
+ let failed: unknown[] = []
214
+ for (let release of releases.toReversed()) {
215
+ try {
216
+ await release()
217
+ } catch (e) {
218
+ failed.push(e)
219
+ }
220
+ }
221
+ if (failed.length == 1) throw failed[0]
222
+ if (failed.length) throw new AggregateError(failed, 'releases failed')
223
+ }
224
+
225
+ /** The role-selected modules, loaded before a host opens its transaction. */
226
+ export type Prepared = {
227
+ vocab: Taken<'vocab'>
228
+ graph: Taken<'graph'>
229
+ effects: Taken<'effects'>
230
+ routes: Taken<'routes'>
231
+ ui: Taken<'ui'>
232
+ service: Taken<'service'>
233
+ factories: { graph: typeof graph; runner: typeof runner }
234
+ }
235
+
236
+ /** Import only the facets a host serves; binding the result performs no imports. */
237
+ export let prepare = async (
238
+ config: Config,
239
+ roles: readonly Role[],
240
+ load: Load,
241
+ opts: AssemblyOpts = {},
242
+ ): Promise<Prepared> => {
243
+ if (!roles.includes('graph')) {
244
+ throw new CallError(
245
+ 'config',
246
+ 'a host opens a graph — its roles include graph',
247
+ )
248
+ }
249
+ let plugins = opts.plugins ?? configured(config)
250
+ let services = roles.filter((r) => !common(r))
251
+ for (let r of services) {
252
+ if (!plugins.some(([p]) => p == r)) {
253
+ throw new CallError(
254
+ 'config',
255
+ `no plugin ${r} in this config serves that role`,
256
+ )
257
+ }
258
+ }
259
+ let observed = opts.observed
260
+ let observedLoad: Load = async (plugin, name) => {
261
+ observed?.attempted(plugin, name)
262
+ let loaded = await load(plugin, name)
263
+ observed?.loaded(plugin, name, loaded !== null)
264
+ return loaded
265
+ }
266
+ let take = <F extends FacetName>(role: Role, name: F): Promise<Taken<F>> =>
267
+ roles.includes(role)
268
+ ? taking(plugins, name, observedLoad)
269
+ : Promise.resolve([])
270
+ opts.part?.('facets')
271
+ await load.together?.(plugins.flatMap(([plugin, , , facets]) =>
272
+ [
273
+ 'vocab' as const,
274
+ 'graph' as const,
275
+ ...roles.includes('effects') ? ['effects'] as const : [],
276
+ ...roles.includes('web') ? ['routes', 'ui'] as const : [],
277
+ ...services.includes(plugin) ? ['service'] as const : [],
278
+ ].filter((name) => facets === undefined || facets.includes(name)).map((
279
+ name,
280
+ ) => [plugin, name] as const)
281
+ ))
282
+ let [vocab, graph, effects, routes, ui, service, factories] = await Promise
283
+ .all([
284
+ take('graph', 'vocab'),
285
+ take('graph', 'graph'),
286
+ take('effects', 'effects'),
287
+ take('web', 'routes'),
288
+ take('web', 'ui'),
289
+ taking(
290
+ plugins.filter(([p]) => services.includes(p)),
291
+ 'service',
292
+ observedLoad,
293
+ ),
294
+ opts.readOnly
295
+ ? Promise.all([import('@yaks/graph/read'), import('@yaks/tools/read')])
296
+ .then(([g, t]) => ({ graph: g.graph, runner: t.reader }))
297
+ : Promise.all([import('@yaks/graph'), import('@yaks/tools')]).then((
298
+ [g, t],
299
+ ) => ({ graph: g.graph, runner: t.runner })),
300
+ ])
301
+ return { vocab, graph, effects, routes, ui, service, factories }
302
+ }
303
+
304
+ /** Pure assembly of imported facets; its binding runs inside the host's transaction. */
305
+ export let assemble = (
306
+ config: Config,
307
+ roles: readonly Role[],
308
+ load: Load,
309
+ prepared: Prepared,
310
+ opts: AssemblyOpts = {},
311
+ ): Assembly => {
312
+ let plugins = opts.plugins ?? configured(config)
313
+ let part = opts.part
314
+ let modules = <F extends FacetName>(name: F): Taken<F> => {
315
+ let loaded = prepared[name as keyof Prepared] as Taken<F>
316
+ // Each configured occurrence keeps its own options, including repeated
317
+ // selections of one package. Facets may be absent, so module positions
318
+ // alone cannot identify their configured entries.
319
+ let key = (plugin: string, names?: string[], facets?: FacetName[]) =>
320
+ JSON.stringify([
321
+ plugin,
322
+ names && [...new Set(names)].sort(),
323
+ facets && [...new Set(facets)].sort(),
324
+ ])
325
+ let options = groupBy(
326
+ plugins,
327
+ ([plugin, , names, facets]) => key(plugin, names, facets),
328
+ )
329
+ return loaded.map(([mod, original, plugin, names, facets]) => {
330
+ let entry = options.get(key(plugin, names, facets))?.shift()
331
+ return [mod, entry?.[1] ?? original, plugin, names, facets]
332
+ })
333
+ }
334
+ let vocabs = modules('vocab')
335
+ let imported = {
336
+ graph: modules('graph'),
337
+ effects: roles.includes('effects') ? modules('effects') : [],
338
+ routes: roles.includes('web') ? modules('routes') : [],
339
+ ui: roles.includes('web') ? modules('ui') : [],
340
+ service: modules('service'),
341
+ }
342
+ part?.('vocabulary')
343
+ let words = opts.words ?? wordsOf(vocabs, opts.docs)
344
+ let { docs, vocab, derived } = words
345
+ let contributions = vocabs.map(([v, options, plugin, names, facets]) => {
346
+ let docs = selected(v.docs ?? [], names, plugin)
347
+ return { docs, options, plugin, facets, effects: effectsIn(docs) }
348
+ })
349
+ let declared = new Set(effectsIn(docs).map((e) => e.name))
350
+ let original = new Set(
351
+ vocabs.flatMap(([v]) => effectsIn(v.docs ?? []).map((e) => e.name)),
352
+ )
353
+ let omissions = imported.effects.map(([, options, plugin, names]) => {
354
+ let vocabulary = vocabs.find(([, o, p, n]) =>
355
+ p == plugin && o === options && n === names
356
+ )
357
+ return new Set(
358
+ names === undefined ? [] : effectsIn(vocabulary?.[0].docs ?? [])
359
+ .filter((e) => !names.includes(e.name)).map((e) => e.name),
360
+ )
361
+ })
362
+
363
+ let required = [
364
+ ...new Set(
365
+ imported.graph.filter(([r, options]) => r.required?.(options))
366
+ .map(([, , plugin]) => plugin),
367
+ ),
368
+ ]
369
+
370
+ return {
371
+ words,
372
+ required,
373
+ bind: (binding) => {
374
+ let releases: (() => void | Promise<void>)[] = []
375
+ let closing: Promise<void> | undefined
376
+ let observed = binding.observed ?? opts.observed ?? compositionAnatomy(
377
+ plugins.map(([name, , , facets]) => ({ name, facets })),
378
+ roles,
379
+ ROLES,
380
+ )
381
+ let observedLoad: Load = async (plugin, name) => {
382
+ observed.attempted(plugin, name)
383
+ let loaded = await load(plugin, name)
384
+ observed.loaded(plugin, name, loaded !== null)
385
+ return loaded
386
+ }
387
+ let boundOptions = new Map<Options, Map<string, Options>>()
388
+ let optionsOf = (plugin: string, options: Options): Options => {
389
+ if (!binding.options) return options
390
+ let by = boundOptions.get(options)
391
+ if (!by) boundOptions.set(options, by = new Map())
392
+ let bound = by.get(plugin)
393
+ if (!bound) by.set(plugin, bound = binding.options(plugin, options))
394
+ return bound
395
+ }
396
+ let bound = <F extends FacetName>(
397
+ name: F,
398
+ loaded: Taken<F>,
399
+ ): Taken<F> => {
400
+ for (let [plugin, , , facets] of plugins) {
401
+ if (facets !== undefined && !facets.includes(name)) continue
402
+ observed.attempted(plugin, name)
403
+ observed.loaded(plugin, name, loaded.some(([, , p]) => p == plugin))
404
+ }
405
+ return loaded.map((
406
+ [mod, options, plugin, names, facets],
407
+ ) => [mod, optionsOf(plugin, options), plugin, names, facets])
408
+ }
409
+ let graphs = bound('graph', imported.graph)
410
+ let watched = roles.includes('effects')
411
+ ? bound('effects', imported.effects)
412
+ : []
413
+ let served = roles.includes('web') ? bound('routes', imported.routes) : []
414
+ let dressed = roles.includes('web') ? bound('ui', imported.ui) : []
415
+ let running = bound('service', imported.service)
416
+ bound('vocab', vocabs)
417
+ part?.('anatomy')
418
+ observed.declarations(docs, vocab)
419
+ let { host: lent, actor: self, process, readOnly, clock } = binding
420
+ let g: Graph | undefined
421
+ let store: Host['storage'] | undefined
422
+ let watching: Effects | undefined
423
+ let answering: Handler | undefined
424
+ let paths: Route[] = []
425
+ let filters: Filter[] = []
426
+ let arrivals: Arrived[] = []
427
+ let offering: Offers[] = []
428
+ let telling: Told[] = []
429
+ let made: Registry | undefined
430
+ let ranked: Search | undefined
431
+ let meant: Meaning | undefined = lent.meaning
432
+ let preloading: (() => Promise<void>) | undefined
433
+ let replying: Reply | undefined
434
+ let calls: Runner | undefined
435
+ // What the binding's tools were made from, when they were made: one
436
+ // that moved makes the registry and its runner again.
437
+ let revised: unknown
438
+ let current = () => {
439
+ let at = binding.tools?.revision?.()
440
+ if (at === revised) return
441
+ revised = at
442
+ made = calls = undefined
443
+ }
444
+ let makeTools: (() => Registry) | undefined
445
+ let makeRunner: (() => Runner) | undefined
446
+ let toolPart = part
447
+ let host: Host = {
448
+ ...lent,
449
+ defer: (release) => void releases.push(release),
450
+ config,
451
+ roles,
452
+ get vocab() {
453
+ return g?.vocab ?? vocab
454
+ },
455
+ derived,
456
+ anatomy: () => {
457
+ if (makeTools) host.tools
458
+ return observed.read()
459
+ },
460
+ observe: observed.observe,
461
+ ui: gather(dressed.map(([facet]) => facet)),
462
+ // A link's word on a request settles who it is from: nobody through a
463
+ // link is this process's own writing, as nobody anywhere else is.
464
+ who: (request, message) =>
465
+ arrivals.length
466
+ ? (async () => {
467
+ for (let from of arrivals) {
468
+ let actor = await from(request)
469
+ if (actor !== undefined) return actor ?? self ?? null
470
+ }
471
+ return authenticate(request, message)
472
+ })()
473
+ : authenticate(request, message),
474
+ offers: (request) => {
475
+ for (let narrowed of offering) {
476
+ let tools = narrowed(request)
477
+ if (tools) return tools
478
+ }
479
+ },
480
+ // A link that fails to say what a request is told tells it nothing and
481
+ // is reported: what a door is told first never costs it its answer.
482
+ told: async (request) => {
483
+ for (let tell of telling) {
484
+ let said = await (async () => await tell(request))().catch(
485
+ (error) =>
486
+ void host.report?.(error, {
487
+ during: {
488
+ request: new URL(request.url).pathname,
489
+ process: host.me,
490
+ },
491
+ }),
492
+ )
493
+ if (said !== undefined) return said
494
+ }
495
+ },
496
+ // Present only when a plugin's options keep one: a host without it polls its
497
+ // store's revision instead (@yaks/api routes), so another process's
498
+ // commits still reach its subscriptions.
499
+ get feed(): Feed | undefined {
500
+ let feeds = graphs.flatMap(([r, options]) =>
501
+ r.feed?.(host, options) ?? []
502
+ )
503
+ return feeds.length
504
+ ? (each) => {
505
+ let stops = feeds.map((feed) => feed(each))
506
+ return () => stops.forEach((stop) => stop())
507
+ }
508
+ : undefined
509
+ },
510
+ get storage() {
511
+ if (!store) throw new Error('the store is not open yet')
512
+ return g?.storage ?? store
513
+ },
514
+ get graph() {
515
+ if (!g) throw new Error('the graph is not open yet')
516
+ return g
517
+ },
518
+ get fx() {
519
+ if (!watching) throw new Error('the effects are not built yet')
520
+ return watching
521
+ },
522
+ get tools() {
523
+ return host.registry.list()
524
+ },
525
+ get registry() {
526
+ if (!makeTools) throw new Error('the tools are not built yet')
527
+ current()
528
+ return made ??= makeTools()
529
+ },
530
+ get runner() {
531
+ if (!makeRunner) throw new Error('the tool runner is not built yet')
532
+ current()
533
+ return calls ??= makeRunner()
534
+ },
535
+ get handler() {
536
+ return answering
537
+ },
538
+ get routes() {
539
+ return paths
540
+ },
541
+ get filters() {
542
+ return filters
543
+ },
544
+ get search() {
545
+ return ranked
546
+ },
547
+ get meaning() {
548
+ return meant
549
+ },
550
+ get preload() {
551
+ return preloading
552
+ },
553
+ get reply() {
554
+ return replying
555
+ },
556
+ }
557
+ let forPackage = (label: string): Host => {
558
+ let ns = { label }
559
+ if (vocab.in(ns) === vocab) return host
560
+ return Object.create(host, {
561
+ vocab: { get: () => (g?.vocab ?? vocab).in(ns) },
562
+ graph: { get: () => host.graph.in(ns) },
563
+ })
564
+ }
565
+ for (let [ui, , plugin] of dressed) {
566
+ observed.observe({
567
+ package: plugin,
568
+ facet: 'ui',
569
+ loaded: true,
570
+ bound: true,
571
+ value: ui,
572
+ })
573
+ }
574
+ let authenticate = doorman(graphs, host, self ?? null)
575
+ let senders = lending(graphs, host, 'senders', lent.senders)
576
+ if (senders) host.senders = senders
577
+ let texters = lending(graphs, host, 'texters', lent.texters)
578
+ if (texters) host.texters = texters
579
+ let chatters = lending(graphs, host, 'chatters', lent.chatters)
580
+ if (chatters) host.chatters = chatters
581
+ let embedders = lending(graphs, host, 'embedders', lent.embedders)
582
+ if (embedders) host.embedders = embedders
583
+ let keepers = lending(graphs, host, 'keepers', lent.keepers)
584
+ if (keepers) host.keepers = keepers
585
+ part?.('storage')
586
+ let extend: Extension[] = []
587
+ let history = graphs.map(([r, options]) => r.history?.(options))
588
+ .find((h) => h)
589
+ store = binding.storage(host, extend, words, history)
590
+ part?.('extensions')
591
+ extend.push(
592
+ ...graphs.flatMap(([r, options]) => r.extend?.(host, options) ?? []),
593
+ )
594
+ extend.push(...binding.extend?.(host) ?? [])
595
+ part?.('schema')
596
+ binding.schema?.(
597
+ host,
598
+ graphs.flatMap(([r, options]) => r.schema?.(host, options) ?? []),
599
+ )
600
+ part?.('effects')
601
+ let fx = watching = binding.effects(
602
+ host,
603
+ contributions.flatMap(({ effects, options, plugin }) =>
604
+ effects.filter((e) =>
605
+ e.option && optionsOf(plugin, options)[e.option] !== true
606
+ )
607
+ .map((e) => e.name)
608
+ ),
609
+ )
610
+ part?.('plugins')
611
+ let onGraph = binding.unobserved ? withoutEffects : id
612
+ let contributed = graphs.flatMap(([r, options, plugin]) => {
613
+ // Vocabulary facets and graph-owned documents are the declarations.
614
+ // A graph plugin's legacy document must not reintroduce words or rules
615
+ // that selection omitted, or that the graph's own declarations shadow.
616
+ let made = (r.plugins?.(forPackage(plugin), options) ?? []).map((p) =>
617
+ onGraph({
618
+ ...p,
619
+ vocab: [],
620
+ namespace: { label: plugin },
621
+ })
622
+ )
623
+ observed.graph(plugin, made)
624
+ return made
625
+ })
626
+ let effectPlugin = onGraph(fx)
627
+ observed.graph('@yaks/effects', [effectPlugin])
628
+ // A numbered entity is printed as an id a person types back (`T-7`), and a
629
+ // graph that reads none back takes `T-7` for an eid and mints an entity of
630
+ // that name. So a config that numbers entities names a plugin that
631
+ // resolves them.
632
+ let graphing = roles.includes('graph')
633
+ if (config.numbers && graphing && !contributed.some((p) => p.address)) {
634
+ throw new CallError(
635
+ 'config',
636
+ '`numbers` prints ids like T-7, and no plugin in this config reads ' +
637
+ 'one back — add @yaks/id to plugins',
638
+ )
639
+ }
640
+ part?.('graph')
641
+ let branching = binding.branches?.(host)
642
+ g = (binding.graph ?? prepared.factories.graph)({
643
+ storage: host.storage,
644
+ vocab,
645
+ // A write no request attributed is the host's own: its rules, its
646
+ // effects, its start-up passes and the bulk loads it is handed are all
647
+ // stored attributed to this process.
648
+ ...(self ? { actor: self } : {}),
649
+ ...clock ? { clock } : {},
650
+ plugins: [...contributed, effectPlugin],
651
+ ...lent.reader ? { reader: lent.reader } : {},
652
+ ...branching ? { branches: branching } : {},
653
+ })
654
+ binding.ready?.(host)
655
+ part?.('bindings')
656
+ observed.graphed()
657
+ let effecting = roles.includes('effects')
658
+ observed.effects(new Map(), effecting)
659
+ if (effecting) {
660
+ let code: Handlers = {}
661
+ let by = new Map<string, string>()
662
+ for (let [i, [mod, options, plugin]] of watched.entries()) {
663
+ let omitted = omissions[i]
664
+ for (
665
+ let [name, run] of Object.entries(
666
+ mod.effects?.(forPackage(plugin), options) ?? {},
667
+ )
668
+ ) {
669
+ // A selected-out declaration is intentionally absent, even where
670
+ // another plugin lends its handler. An unknown name is still a typo.
671
+ if (
672
+ omitted.has(name) || !declared.has(name) && original.has(name)
673
+ ) {
674
+ continue
675
+ }
676
+ if (!declared.has(name)) throw undeclared(plugin, name)
677
+ if (by.has(name)) throw twice(name, [by.get(name)!, plugin])
678
+ by.set(name, plugin)
679
+ let bound: Handlers[string] = (event, tx, write, attempt) => {
680
+ let local = host.graph.in({ label: plugin })
681
+ let names = namesBetween(g!.vocab, local.vocab)
682
+ let inward = namesBetween(local.vocab, g!.vocab)
683
+ let name = names.comp(event.name)
684
+ return run(
685
+ {
686
+ ...event,
687
+ name,
688
+ touched: event.touched?.map(names.comp),
689
+ before: event.before && names.read([event.before])[0],
690
+ comp: event.comp && names.read([{
691
+ entity: event.entity,
692
+ [event.name]: event.comp,
693
+ }])[0][name] as Comp,
694
+ },
695
+ transactionIn(tx, g!.vocab, local.vocab),
696
+ (bs) => after(write(inward.write(bs)), names.read),
697
+ attempt,
698
+ )
699
+ }
700
+ // A queue's rank reads the plugin's own names, as its code does.
701
+ let own = (run as { rank?: Rank }).rank
702
+ let rank: Rank | undefined = own && ((runs, tx) => {
703
+ let local = host.graph.in({ label: plugin }).vocab
704
+ return own(
705
+ namesBetween(g!.vocab, local).read(runs),
706
+ transactionIn(tx, g!.vocab, local),
707
+ )
708
+ })
709
+ // The concrete host uses annotations such as maintenance to
710
+ // distinguish housekeeping from app activity.
711
+ code[name] = Object.assign(bound, run, rank ? { rank } : {})
712
+ }
713
+ }
714
+ let operations = new Set(
715
+ effectsIn(vocab.docs).filter((e) => e.call).map((e) => e.name),
716
+ )
717
+ for (
718
+ let [name, run] of Object.entries(binding.operations?.(host) ?? {})
719
+ ) {
720
+ if (!operations.has(name)) continue
721
+ if (by.has(name)) throw twice('host', [by.get(name)!, name])
722
+ code[name] = operationHandler(name, run)
723
+ by.set(name, 'host')
724
+ }
725
+ fx.handle(code)
726
+ observed.effects(by, true)
727
+ }
728
+ part?.('search')
729
+ // One meaning index: the one a plugin offers, or the one the host lends.
730
+ let meanings = [
731
+ ...(meant ? [meant] : []),
732
+ ...graphs.flatMap(([r, options]) =>
733
+ r.meaning ? [r.meaning(host, options)] : []
734
+ ),
735
+ ]
736
+ if (meanings.length > 1) {
737
+ throw new CallError(
738
+ 'config',
739
+ 'more than one meaning index answers search',
740
+ )
741
+ }
742
+ // A host with a reader searches through it too, where it searches at all.
743
+ meant = meanings[0] && (lent.reader?.meaning ?? meanings[0])
744
+ let loads = graphs.flatMap(([r, options]) =>
745
+ r.preload ? [r.preload(host, options)] : []
746
+ )
747
+ if (loads.length) {
748
+ preloading = async () => {
749
+ for (let load of loads) await load()
750
+ }
751
+ }
752
+ ranked = binding.search?.(host)
753
+ ranked = ranked && (lent.reader?.search ?? ranked)
754
+ // The generic tools belong to this graph, not to any transport: they are
755
+ // declared in @yaks/graph's own vocabulary and implemented there, and a
756
+ // host has a graph whether or not anything is listening. So the tier is
757
+ // assembled here beside the plugins' own, in the form the vocabulary
758
+ // declares, and a transport that needs them in its own form restates them
759
+ // (@yaks/mcp `core`).
760
+ //
761
+ // A plugin's own tools are listed from its vocabulary and run by its
762
+ // `./tools`, imported the first time one of them is called.
763
+ makeTools = () => {
764
+ toolPart?.('tools')
765
+ let sources = new Map<string, NamedTool[]>()
766
+ if (binding.tools?.generic !== false) {
767
+ let generic = tier({ search: ranked, keywords: vocab.keywords })
768
+ observed.tier(generic)
769
+ sources.set('@yaks/graph', generic)
770
+ }
771
+ if (binding.tools) {
772
+ let own = binding.tools.offer(host)
773
+ observed.tier(own, binding.tools.package)
774
+ sources.set(binding.tools.package, own)
775
+ }
776
+ for (let { docs, options, plugin, facets } of contributions) {
777
+ if (facets !== undefined && !facets.includes('tools')) continue
778
+ let tools = loadTools(docs, async () => {
779
+ let code = await observedLoad(plugin, 'tools')
780
+ let runs =
781
+ code?.runs?.(forPackage(plugin), optionsOf(plugin, options)) ?? {}
782
+ let declarations = toolsIn(docs)
783
+ let names = declarations.map((d) => d.name ?? toolName(d))
784
+ let joined = declarations.filter((d) =>
785
+ typeof (runs[d.name ?? toolName(d)] ??
786
+ runs[[d.noun, d.verb].filter(Boolean).join('_')]) ==
787
+ 'function'
788
+ ).map((d) => d.name ?? toolName(d))
789
+ // loadTools joins the whole module; a missing run rejects that join.
790
+ observed.runs(
791
+ plugin,
792
+ joined,
793
+ joined.length == names.length ? joined : [],
794
+ )
795
+ return runs
796
+ }).map((tool) => ({ ...tool, ...toolIn(tool, plugin) }))
797
+ sources.set(plugin, [...sources.get(plugin) ?? [], ...tools])
798
+ }
799
+ return registry([...sources].map(([name, tools]) => ({ name, tools })))
800
+ }
801
+ let replies = graphs.flatMap(([r, options]) =>
802
+ r.reply ? [r.reply(host, options)] : []
803
+ )
804
+ replying = replies.length
805
+ ? async (call, answer, wrote) =>
806
+ (await Promise.all(replies.map((r) => r(call, answer, wrote)))).flat()
807
+ : undefined
808
+ // The one tool runner over this graph. A caller runs a tool and the runner
809
+ // records the request and the result as it goes; what the two effects
810
+ // @yaks/tools declares add, in a process serving `effects`, is the calls
811
+ // nobody is waiting on — one written through `/apply`, or one whose
812
+ // scheduled wake has now fired. A call this graph has no tool for is left
813
+ // alone for whoever does have it. The `tool` rows a call points at are
814
+ // written on the first call and at start-up, never while assembling: a
815
+ // one-shot command opens a host to ask one question and should not write
816
+ // just to say hello.
817
+ makeRunner = () => {
818
+ toolPart?.('runner')
819
+ let own = binding.calls?.(host) ?? {}
820
+ return prepared.factories.runner(own.records ?? g!, {
821
+ // Tools read and write the host's graph, whatever records the calls.
822
+ ...own.records ? { host: g! } : {},
823
+ ...own.takes ? { takes: own.takes } : {},
824
+ // Built by the first call that asks for a tool: effects need the
825
+ // runner as the graph opens, and most openings run no tool.
826
+ tools: () => host.registry,
827
+ // This host owns the calls it claims, so the start-up pass re-runs its
828
+ // own interrupted calls and leaves alone another runner's, or those an
829
+ // imported transcript recorded as already run.
830
+ ...(self ? { owner: self.by } : {}),
831
+ // This process, on every call it runs, for a tool that acts on the
832
+ // machine rather than the graph: `yak land` fast-forwards the checkout
833
+ // the person typed in, because the tool runs in the same process that
834
+ // read the command line (local.ts). A host answering HTTP reports its
835
+ // own, which is the accurate answer — a call arriving over HTTP acts on
836
+ // the machine that received it.
837
+ ...process ? { process } : {},
838
+ ...clock ? { clock } : {},
839
+ report: own.report ??
840
+ ((error, call, tool) =>
841
+ readOnly ? console.error(error) : host.report?.(error, {
842
+ actor: call.$actor ?? self ?? undefined,
843
+ during: {
844
+ entity: call.entity.eid,
845
+ kind: 'call',
846
+ process: host.me,
847
+ },
848
+ tags: { tool },
849
+ })),
850
+ ...replying ? { reply: replying } : {},
851
+ })
852
+ }
853
+ // A graph-only caller can read and write without paying to build tools
854
+ // it never asks for. Effects need the runner now to register owed calls;
855
+ // every other caller reaches the same construction through Host.
856
+ if (effecting) {
857
+ let run = host.runner
858
+ // The runner standing when the run is due: one the binding's tools
859
+ // moved since is made again.
860
+ let due: Handlers[string] = (e, _tx, _write, attempt) =>
861
+ host.runner.due(e.entity.eid, { defer: attempt?.defer })
862
+ fx.handle(
863
+ Object.fromEntries(
864
+ run.rules.filter((r) => declared.has(r.rule.name)).map((
865
+ r,
866
+ ) => [r.rule.name, due]),
867
+ ),
868
+ )
869
+ observed.due(run.rules.map((r) => r.rule.name))
870
+ }
871
+ // Which listed plugin hosts the routes — turns them into the one handler
872
+ // this host answers with (@yaks/api). Two would be two answers to one
873
+ // request, which is not an answer. None means nothing here serves HTTP, so
874
+ // the other plugins are never asked for routes: a facet whose whole
875
+ // purpose is a listener that does not exist is a facet this host ignores.
876
+ // `served` is empty in a process that does not serve `web`.
877
+ let hosts = served.filter(([r]) => r.handler)
878
+ if (hosts.length > 1) {
879
+ throw new CallError(
880
+ 'config',
881
+ `${hosts.length} plugins host routes — a host has one`,
882
+ )
883
+ }
884
+ let [mod, options] = hosts[0] ?? []
885
+ if (mod?.handler) {
886
+ paths = served.flatMap(([r, o, plugin]) => {
887
+ let made = r.routes?.(host, o) ?? []
888
+ observed.routes(plugin, made)
889
+ return made
890
+ })
891
+ filters = served.flatMap(([r, o]) =>
892
+ r.filter ? [r.filter(host, o)] : []
893
+ )
894
+ arrivals = served.flatMap(([r, o]) =>
895
+ r.arrived ? [r.arrived(host, o)] : []
896
+ )
897
+ offering = served.flatMap(([r, o]) =>
898
+ r.offers ? [r.offers(host, o)] : []
899
+ )
900
+ telling = served.flatMap(([r, o]) => r.told ? [r.told(host, o)] : [])
901
+ answering = mod.handler(host, options ?? {})
902
+ observed.binding(hosts[0][2], 'routes')
903
+ }
904
+ let duties: Duty[] = running.map(([mod, options, plugin]): Duty => {
905
+ observed.binding(plugin, 'service')
906
+ return {
907
+ name: plugin,
908
+ run: (signal) => mod.service!(host, options, signal),
909
+ }
910
+ })
911
+ // Deferred capabilities run after composition's timing spans have ended.
912
+ toolPart = undefined
913
+ return {
914
+ host,
915
+ services: duties,
916
+ interrupt: async (why) => await calls?.interrupt(why) ?? [],
917
+ close: () => closing ??= released(releases),
918
+ }
919
+ },
920
+ }
921
+ }
922
+
923
+ /** Load only the roles served, then assemble once the host can lend storage. */
924
+ export let assembly = async (
925
+ config: Config,
926
+ roles: readonly Role[],
927
+ load: Load,
928
+ opts: AssemblyOpts = {},
929
+ ): Promise<Assembly> =>
930
+ assemble(config, roles, load, await prepare(config, roles, load, opts), opts)