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