@yaks/cli 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 (331) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +1059 -2
  3. package/_dist/account-forward.d.ts +12 -0
  4. package/_dist/account-forward.d.ts.map +1 -0
  5. package/_dist/accounts.d.ts +23 -0
  6. package/_dist/accounts.d.ts.map +1 -0
  7. package/_dist/answer.d.ts +88 -0
  8. package/_dist/answer.d.ts.map +1 -0
  9. package/_dist/apply.d.ts +17 -0
  10. package/_dist/apply.d.ts.map +1 -0
  11. package/_dist/args.d.ts +86 -0
  12. package/_dist/args.d.ts.map +1 -0
  13. package/_dist/commands.d.ts +15 -0
  14. package/_dist/commands.d.ts.map +1 -0
  15. package/_dist/complete.d.ts +15 -0
  16. package/_dist/complete.d.ts.map +1 -0
  17. package/_dist/config.d.ts +37 -0
  18. package/_dist/config.d.ts.map +1 -0
  19. package/_dist/dependencies.d.ts +6 -0
  20. package/_dist/dependencies.d.ts.map +1 -0
  21. package/_dist/facets.d.ts +71 -0
  22. package/_dist/facets.d.ts.map +1 -0
  23. package/_dist/grammar.d.ts +5 -0
  24. package/_dist/grammar.d.ts.map +1 -0
  25. package/_dist/host.d.ts +164 -0
  26. package/_dist/host.d.ts.map +1 -0
  27. package/_dist/install.d.ts +43 -0
  28. package/_dist/install.d.ts.map +1 -0
  29. package/_dist/main.d.ts +16 -0
  30. package/_dist/main.d.ts.map +1 -0
  31. package/_dist/memo.d.ts +60 -0
  32. package/_dist/memo.d.ts.map +1 -0
  33. package/_dist/mod.d.ts +46 -0
  34. package/_dist/mod.d.ts.map +1 -0
  35. package/_dist/page.d.ts +73 -0
  36. package/_dist/page.d.ts.map +1 -0
  37. package/_dist/platform.d.ts +27 -0
  38. package/_dist/platform.d.ts.map +1 -0
  39. package/_dist/reader.d.ts +10 -0
  40. package/_dist/reader.d.ts.map +1 -0
  41. package/_dist/release.d.ts +48 -0
  42. package/_dist/release.d.ts.map +1 -0
  43. package/_dist/remote.d.ts +13 -0
  44. package/_dist/remote.d.ts.map +1 -0
  45. package/_dist/reported.d.ts +11 -0
  46. package/_dist/reported.d.ts.map +1 -0
  47. package/_dist/roles.d.ts +2 -0
  48. package/_dist/roles.d.ts.map +1 -0
  49. package/_dist/roster.d.ts +41 -0
  50. package/_dist/roster.d.ts.map +1 -0
  51. package/_dist/rpc.d.ts +29 -0
  52. package/_dist/rpc.d.ts.map +1 -0
  53. package/_dist/run.d.ts +164 -0
  54. package/_dist/run.d.ts.map +1 -0
  55. package/_dist/runtime.d.ts +4 -0
  56. package/_dist/runtime.d.ts.map +1 -0
  57. package/_dist/searching.d.ts +7 -0
  58. package/_dist/searching.d.ts.map +1 -0
  59. package/_dist/show.d.ts +22 -0
  60. package/_dist/show.d.ts.map +1 -0
  61. package/_dist/store.d.ts +25 -0
  62. package/_dist/store.d.ts.map +1 -0
  63. package/_dist/terminal.d.ts +17 -0
  64. package/_dist/terminal.d.ts.map +1 -0
  65. package/_dist/tool.d.ts +55 -0
  66. package/_dist/tool.d.ts.map +1 -0
  67. package/_dist/tty.d.ts +3 -0
  68. package/_dist/tty.d.ts.map +1 -0
  69. package/_dist/vault.d.ts +9 -0
  70. package/_dist/vault.d.ts.map +1 -0
  71. package/_dist/words.d.ts +11 -0
  72. package/_dist/words.d.ts.map +1 -0
  73. package/_dist/yak.d.ts +10 -0
  74. package/_dist/yak.d.ts.map +1 -0
  75. package/account-forward.js +40 -0
  76. package/account-forward.js.map +1 -0
  77. package/account-forward.ts +50 -0
  78. package/accounts.js +162 -0
  79. package/accounts.js.map +1 -0
  80. package/accounts.ts +228 -0
  81. package/answer.js +394 -0
  82. package/answer.js.map +1 -0
  83. package/answer.ts +569 -0
  84. package/apply.js +49 -0
  85. package/apply.js.map +1 -0
  86. package/apply.ts +54 -0
  87. package/args.js +420 -0
  88. package/args.js.map +1 -0
  89. package/args.ts +494 -0
  90. package/code.js +209 -0
  91. package/code.js.map +1 -0
  92. package/code.ts +227 -0
  93. package/commands.js +131 -0
  94. package/commands.js.map +1 -0
  95. package/commands.ts +142 -0
  96. package/complete.js +104 -0
  97. package/complete.js.map +1 -0
  98. package/complete.ts +152 -0
  99. package/config.js +125 -0
  100. package/config.js.map +1 -0
  101. package/config.ts +180 -0
  102. package/declarations.js +67 -0
  103. package/declarations.js.map +1 -0
  104. package/declarations.ts +84 -0
  105. package/deno.json +1 -0
  106. package/dependencies.js +126 -0
  107. package/dependencies.js.map +1 -0
  108. package/dependencies.ts +141 -0
  109. package/derive.js +102 -0
  110. package/derive.js.map +1 -0
  111. package/derive.ts +125 -0
  112. package/drain.js +83 -0
  113. package/drain.js.map +1 -0
  114. package/drain.ts +115 -0
  115. package/duties.ts +17 -0
  116. package/exports.json +1486 -0
  117. package/external.js +373 -0
  118. package/external.js.map +1 -0
  119. package/external.ts +435 -0
  120. package/facets.js +214 -0
  121. package/facets.js.map +1 -0
  122. package/facets.ts +232 -0
  123. package/feedback.js +54 -0
  124. package/feedback.js.map +1 -0
  125. package/feedback.ts +57 -0
  126. package/files.js +84 -0
  127. package/files.js.map +1 -0
  128. package/files.ts +112 -0
  129. package/get_starts.js +31 -0
  130. package/get_starts.js.map +1 -0
  131. package/get_starts.ts +34 -0
  132. package/git-credential.js +79 -0
  133. package/git-credential.js.map +1 -0
  134. package/git-credential.ts +77 -0
  135. package/grammar.js +4 -0
  136. package/grammar.js.map +1 -0
  137. package/grammar.ts +5 -0
  138. package/held.js +51 -0
  139. package/held.js.map +1 -0
  140. package/held.ts +66 -0
  141. package/host.js +1174 -0
  142. package/host.js.map +1 -0
  143. package/host.ts +1343 -0
  144. package/init.js +138 -0
  145. package/init.js.map +1 -0
  146. package/init.ts +139 -0
  147. package/install.js +216 -0
  148. package/install.js.map +1 -0
  149. package/install.ts +223 -0
  150. package/lifetime.js +56 -0
  151. package/lifetime.js.map +1 -0
  152. package/lifetime.ts +66 -0
  153. package/local-page.ts +114 -0
  154. package/local.js +417 -0
  155. package/local.js.map +1 -0
  156. package/local.ts +537 -0
  157. package/lockfile.js +20 -0
  158. package/lockfile.js.map +1 -0
  159. package/lockfile.ts +32 -0
  160. package/machines.js +33 -0
  161. package/machines.js.map +1 -0
  162. package/machines.ts +51 -0
  163. package/made/4f855610bdabcd736100d34e4e467ea5.json +1 -0
  164. package/main.js +534 -0
  165. package/main.js.map +1 -0
  166. package/main.ts +547 -0
  167. package/mcp.js +108 -0
  168. package/mcp.js.map +1 -0
  169. package/mcp.ts +113 -0
  170. package/member.js +103 -0
  171. package/member.js.map +1 -0
  172. package/member.ts +133 -0
  173. package/memo.js +503 -0
  174. package/memo.js.map +1 -0
  175. package/memo.ts +634 -0
  176. package/mod.js +46 -0
  177. package/mod.js.map +1 -0
  178. package/mod.ts +99 -0
  179. package/operations.js +53 -0
  180. package/operations.js.map +1 -0
  181. package/operations.ts +68 -0
  182. package/package.json +115 -4
  183. package/page.js +211 -0
  184. package/page.js.map +1 -0
  185. package/page.ts +308 -0
  186. package/parser.js +45 -0
  187. package/parser.js.map +1 -0
  188. package/parser.ts +77 -0
  189. package/people-search.js +112 -0
  190. package/people-search.js.map +1 -0
  191. package/people-search.ts +162 -0
  192. package/platform.js +184 -0
  193. package/platform.js.map +1 -0
  194. package/platform.ts +224 -0
  195. package/platform_effects.js +5 -0
  196. package/platform_effects.js.map +1 -0
  197. package/platform_effects.ts +13 -0
  198. package/prepare.js +40 -0
  199. package/prepare.js.map +1 -0
  200. package/prepare.ts +46 -0
  201. package/read_activity.js +54 -0
  202. package/read_activity.js.map +1 -0
  203. package/read_activity.ts +61 -0
  204. package/read_thread.js +387 -0
  205. package/read_thread.js.map +1 -0
  206. package/read_thread.ts +506 -0
  207. package/read_worker.ts +164 -0
  208. package/reader.js +48 -0
  209. package/reader.js.map +1 -0
  210. package/reader.ts +57 -0
  211. package/release.js +82 -0
  212. package/release.js.map +1 -0
  213. package/release.json +127 -0
  214. package/release.ts +98 -0
  215. package/remote-page.ts +70 -0
  216. package/remote.js +96 -0
  217. package/remote.js.map +1 -0
  218. package/remote.ts +153 -0
  219. package/report.js +83 -0
  220. package/report.js.map +1 -0
  221. package/report.ts +101 -0
  222. package/reported.js +32 -0
  223. package/reported.js.map +1 -0
  224. package/reported.ts +38 -0
  225. package/restart.js +349 -0
  226. package/restart.js.map +1 -0
  227. package/restart.ts +478 -0
  228. package/restore.js +32 -0
  229. package/restore.js.map +1 -0
  230. package/restore.ts +38 -0
  231. package/roles.js +32 -0
  232. package/roles.js.map +1 -0
  233. package/roles.ts +49 -0
  234. package/roster.js +65 -0
  235. package/roster.js.map +1 -0
  236. package/roster.ts +84 -0
  237. package/rpc.js +113 -0
  238. package/rpc.js.map +1 -0
  239. package/rpc.ts +159 -0
  240. package/run.js +533 -0
  241. package/run.js.map +1 -0
  242. package/run.ts +741 -0
  243. package/runtime.js +381 -0
  244. package/runtime.js.map +1 -0
  245. package/runtime.ts +433 -0
  246. package/sandboxes.js +26 -0
  247. package/sandboxes.js.map +1 -0
  248. package/sandboxes.ts +30 -0
  249. package/searching.js +33 -0
  250. package/searching.js.map +1 -0
  251. package/searching.ts +50 -0
  252. package/show.js +109 -0
  253. package/show.js.map +1 -0
  254. package/show.ts +144 -0
  255. package/shown.js +13 -0
  256. package/shown.js.map +1 -0
  257. package/shown.ts +44 -0
  258. package/stall.js +90 -0
  259. package/stall.js.map +1 -0
  260. package/stall.ts +156 -0
  261. package/stall_profile.js +113 -0
  262. package/stall_profile.js.map +1 -0
  263. package/stall_profile.ts +142 -0
  264. package/stall_wait.js +183 -0
  265. package/stall_wait.js.map +1 -0
  266. package/stall_wait.ts +249 -0
  267. package/stall_wait_worker.ts +11 -0
  268. package/start.js +349 -0
  269. package/start.js.map +1 -0
  270. package/start.ts +343 -0
  271. package/starvation.js +147 -0
  272. package/starvation.js.map +1 -0
  273. package/starvation.ts +224 -0
  274. package/store.js +118 -0
  275. package/store.js.map +1 -0
  276. package/store.ts +193 -0
  277. package/subcommands.js +62 -0
  278. package/subcommands.js.map +1 -0
  279. package/subcommands.ts +77 -0
  280. package/terminal.js +93 -0
  281. package/terminal.js.map +1 -0
  282. package/terminal.ts +128 -0
  283. package/text.js +20 -0
  284. package/text.js.map +1 -0
  285. package/text.ts +37 -0
  286. package/tool.js +76 -0
  287. package/tool.js.map +1 -0
  288. package/tool.ts +157 -0
  289. package/trace_control.js +231 -0
  290. package/trace_control.js.map +1 -0
  291. package/trace_control.ts +233 -0
  292. package/traces.js +138 -0
  293. package/traces.js.map +1 -0
  294. package/traces.ts +160 -0
  295. package/tracker.js +22 -0
  296. package/tracker.js.map +1 -0
  297. package/tracker.ts +27 -0
  298. package/tty.js +82 -0
  299. package/tty.js.map +1 -0
  300. package/tty.ts +142 -0
  301. package/unit_failure.js +178 -0
  302. package/unit_failure.js.map +1 -0
  303. package/unit_failure.ts +191 -0
  304. package/upkeep_thread.js +32 -0
  305. package/upkeep_thread.js.map +1 -0
  306. package/upkeep_thread.ts +35 -0
  307. package/upkeep_worker.ts +27 -0
  308. package/vault.js +186 -0
  309. package/vault.js.map +1 -0
  310. package/vault.ts +220 -0
  311. package/vocab-ids.js +63 -0
  312. package/vocab-ids.js.map +1 -0
  313. package/vocab-ids.ts +62 -0
  314. package/vocab.json +35 -0
  315. package/warm.js +138 -0
  316. package/warm.js.map +1 -0
  317. package/warm.ts +171 -0
  318. package/watch_revision.js +25 -0
  319. package/watch_revision.js.map +1 -0
  320. package/watch_revision.ts +30 -0
  321. package/words.js +29 -0
  322. package/words.js.map +1 -0
  323. package/words.ts +41 -0
  324. package/workspaces.js +40 -0
  325. package/workspaces.js.map +1 -0
  326. package/workspaces.ts +58 -0
  327. package/yak-unit-failure.conf +6 -0
  328. package/yak-unit-handoff.conf +2 -0
  329. package/yak.js +123 -0
  330. package/yak.js.map +1 -0
  331. package/yak.ts +136 -0
package/host.js ADDED
@@ -0,0 +1,1174 @@
1
+ import { statements } from "@yaks/sqlite/statements";
2
+ import { freshFetch } from "@yaks/process/http";
3
+ import * as process from "@yaks/process/system";
4
+ import * as disk from "@yaks/file/io";
5
+ import { getStarts } from "./get_starts.js";
6
+ import { workspaceCapabilities } from "./workspaces.js";
7
+ import { overdue } from "@yaks/machine/targets";
8
+ import { resolveHome } from "./machines.js";
9
+ import { sandboxCapabilities } from "./sandboxes.js";
10
+ import { trackerOptions } from "./tracker.js";
11
+ import { Refused, Stale } from "@yaks/graph/errors";
12
+ import { hit } from "@yaks/graph/hit";
13
+ import { EXIT, PROCESS } from "@yaks/process/vocab";
14
+ import { ended, selfEid, started } from "@yaks/process/self";
15
+ import { migrations, migrationSchema } from "@yaks/sqlite/migration";
16
+ import { add, follow, printing, printOf } from "@yaks/sqlite/follow";
17
+ import { bindStorage } from "@yaks/sqlite";
18
+ import { requirements, requires } from "@yaks/sqlite/meta";
19
+ import { filler, SCHEMA_DUTY, tend } from "@yaks/sqlite/owe";
20
+ import { survey } from "@yaks/sqlite/survey";
21
+ import { searching } from "./searching.js";
22
+ import { peopleSearch } from "./people-search.js";
23
+ import { adopt, find, heal, indexed, pieces, schema as textSchema, search, split, unfound, worded as wordFields } from "@yaks/fts";
24
+ import { EFFECT, effects, expiration, released } from "@yaks/effects";
25
+ import { peek } from "@yaks/secrets";
26
+ import { opKeeper } from "@yaks/secrets/op";
27
+ import { command, reporter, revision } from "./report.js";
28
+ import { faults } from "@yaks/api/refuse";
29
+ import { backend } from "@yaks/blob/backend";
30
+ import { artifactsAt, fileBlobs } from "@yaks/file/blobs";
31
+ import { blobSchema, sqliteBlobs } from "@yaks/blob/sqlite";
32
+ import { dbOf, given, used } from "./config.js";
33
+ import { ALIAS, aliasEid } from "@yaks/alias";
34
+ import { format } from "@yaks/id";
35
+ import { configured, facetsOf, meet, numbering } from "@yaks/host/config";
36
+ import { facet } from "./words.js";
37
+ import { assembly } from "@yaks/host";
38
+ export { every } from "@yaks/host/roles";
39
+ import { declarations } from "./declarations.js";
40
+ import { ROLES } from "./roles.js";
41
+ export { ROLES } from "./roles.js";
42
+ import { drain } from "./drain.js";
43
+ import { vaultOf } from "./vault.js";
44
+ import { roles as serveRoles } from "@yaks/threads";
45
+ import { during, outcome, peek as tracing } from "@yaks/trace";
46
+ import { compositionAnatomy, secretNames } from "@yaks/host/anatomy";
47
+ import { AsyncLocalStorage } from 'node:async_hooks';
48
+ import { installContext } from "@yaks/trace";
49
+ import { installAsker } from "@yaks/graph/asker";
50
+ import { spool } from "@yaks/tracker/report";
51
+ import { CallError } from "@yaks/tools/errors";
52
+ import { persist } from "@yaks/tools/persist";
53
+ import { feedbackTool } from "./feedback.js";
54
+ import { operations } from "./operations.js";
55
+ import { delivery } from "./remote.js";
56
+ import { system } from "@yaks/fp";
57
+ import { files } from "@yaks/tracker/file";
58
+ import { traceControl } from "./trace_control.js";
59
+ import { upkeepThread } from "./upkeep_thread.js";
60
+ import { watchRevision } from "./watch_revision.js";
61
+ // One carrier per runtime, not per composed graph. Multiple CLI hosts can
62
+ // coexist without replacing one another's async context.
63
+ let traceLocal = new AsyncLocalStorage();
64
+ // What finds the processes that ended without closing, imported by the first
65
+ // host that asks after one: a command that buries nobody never loads the
66
+ // supervisor it lives in.
67
+ let supervisor = ()=>import("@yaks/process");
68
+ installContext({
69
+ get: ()=>traceLocal.getStore(),
70
+ run: (ctx, work)=>traceLocal.run(ctx, work)
71
+ });
72
+ let askerLocal = new AsyncLocalStorage();
73
+ installAsker({
74
+ get: ()=>askerLocal.getStore(),
75
+ run: (asker, work)=>askerLocal.run(asker, work)
76
+ });
77
+ // A read that ran on, named by who asked it: its door and page as tags, its
78
+ // session as what it ran during.
79
+ let asked = (asker)=>({
80
+ tags: {
81
+ step: 'read',
82
+ ...asker && {
83
+ door: asker.door
84
+ },
85
+ ...asker?.page && {
86
+ page: asker.page
87
+ }
88
+ },
89
+ ...asker?.session && {
90
+ during: {
91
+ session: asker.session
92
+ }
93
+ }
94
+ });
95
+ export { facet, words } from "./words.js";
96
+ export { configPath, given, person, read, used } from "./config.js";
97
+ // Scores from FTS and a vector space are incomparable. Rank positions give
98
+ // each source a vote; direct word matches get a small lead, and a hit in both
99
+ // gets both votes.
100
+ let merged = (words, meaning, limit)=>{
101
+ let by = new Map();
102
+ words.forEach((h, i)=>by.set(h.entity, {
103
+ entity: h.entity,
104
+ score: 1.1 / (60 + i + 1),
105
+ snippet: h.snippet,
106
+ source: 'text'
107
+ }));
108
+ meaning.forEach((h, i)=>{
109
+ let had = by.get(h.entity);
110
+ by.set(h.entity, had ? {
111
+ ...had,
112
+ score: had.score + 1 / (60 + i + 1),
113
+ source: 'both'
114
+ } : {
115
+ entity: h.entity,
116
+ score: 1 / (60 + i + 1),
117
+ snippet: h.excerpt,
118
+ source: 'meaning'
119
+ });
120
+ });
121
+ return [
122
+ ...by.values()
123
+ ].sort((a, b)=>b.score - a.score || a.entity.localeCompare(b.entity)).slice(0, limit);
124
+ };
125
+ // The mode a process opens its graph in, as its environment says.
126
+ let moding = ()=>{
127
+ let at = process.env.get('YAK_AT'), branch = process.env.get('YAK_BRANCH');
128
+ return at ? {
129
+ at: Number(at)
130
+ } : branch ? {
131
+ branch: Number(branch)
132
+ } : undefined;
133
+ };
134
+ export { dbOf } from "./config.js";
135
+ // `{"secret": "NAME"}` anywhere in a plugin's options reads that secret at the
136
+ // moment the value is accessed (@yaks/secrets `peek`): the local vault value,
137
+ // or else the environment variable of that name. It is the one thing a config
138
+ // file cannot hold in the open, and the one thing that can arrive after the
139
+ // host is already running, so a plugin that re-reads its options on each pass starts
140
+ // the moment a key is written rather than needing a restart. The value comes
141
+ // from this box's vault; no config read starts a 1Password process. A secret
142
+ // nobody has provided reads as undefined, so the plugin reports in its own
143
+ // words what it is waiting for.
144
+ let revealing = (vault)=>vault ? {
145
+ secret: (name)=>peek(vault, name, {
146
+ env: process.env.get
147
+ })
148
+ } : {};
149
+ /**
150
+ * Who a host writes as when no request named a caller: nobody, through this
151
+ * PROCESS. A process is an instrument, never an actor, so it stands in `via`
152
+ * alone, the way a session does (M-31958).
153
+ *
154
+ * There is no configured actor name. A run of a program is not a singleton and
155
+ * never was — two `yak` commands and a `yak serve` over one file are three
156
+ * writers — so the instrument is the `process` row this run wrote on the way in
157
+ * (@yaks/process `started`). That makes `created.via` the answer to *which run*
158
+ * wrote a thing, and lets a child process's row, written by its parent, record
159
+ * whose child it is without needing a property for it.
160
+ *
161
+ * A graph whose vocabulary has no `process` component has no such row, and
162
+ * writes go unattributed rather than attributed to an id nothing created.
163
+ */ export let writer = (vocab)=>vocab.comp(PROCESS) ? {
164
+ via: selfEid()
165
+ } : null;
166
+ /**
167
+ * Open the graph a config names, for the roles this process serves: import
168
+ * those roles' facets and nothing else, open the database, build the graph, and
169
+ * wire in what each role brings — the code behind the effects, and the worker
170
+ * that runs them, for `effects`; the request handler for `web`; a plugin's
171
+ * service for the role named by its package. Every process serves `graph`,
172
+ * since the graph is what it opened.
173
+ *
174
+ * `load` is how one of a plugin's subpaths becomes a module ({@link facet}).
175
+ * It is injectable, so a test can assemble a host from modules it wrote inline
176
+ * rather than files on disk.
177
+ */ export let compose = (config, roles, load = facet, opts = {})=>{
178
+ // The config exists before its graph does, so a consumer can subscribe to
179
+ // its channel before any startup work. No recorder is created by a host.
180
+ let c = tracing(config);
181
+ if (!c) return composed(config, roles, load, opts);
182
+ let root = c.begin({
183
+ kind: 'process-start',
184
+ name: '@yaks/cli.compose',
185
+ package: '@yaks/cli'
186
+ });
187
+ let part;
188
+ let next = (name)=>{
189
+ part?.end();
190
+ part = c.begin({
191
+ kind: 'phase',
192
+ name: `@yaks/cli.compose.${name}`,
193
+ package: '@yaks/cli',
194
+ parent: root?.id
195
+ });
196
+ };
197
+ return during(root, async ()=>{
198
+ try {
199
+ let host = await composed(config, roles, load, opts, next);
200
+ part?.end();
201
+ return host;
202
+ } catch (error) {
203
+ part?.end({
204
+ outcome: outcome(error)
205
+ });
206
+ throw error;
207
+ }
208
+ });
209
+ };
210
+ let composed = async (config, roles, load, opts, part)=>{
211
+ part?.('reporter');
212
+ if (!roles.includes('graph')) {
213
+ throw new CallError('config', 'a host opens a graph — its roles include graph');
214
+ }
215
+ let uses = new Set(config.plugins?.map(used));
216
+ if (load == facet && !uses.has('@yaks/egress')) {
217
+ config = {
218
+ ...config,
219
+ plugins: [
220
+ ...config.plugins ?? [],
221
+ '@yaks/egress'
222
+ ]
223
+ };
224
+ }
225
+ let platformOperations = roles.includes('effects') ? (await import("./platform_effects.js")).platformEffects : undefined;
226
+ let path = dbOf(config);
227
+ let clock = opts.clock ?? system;
228
+ let report = reporter(opts.readOnly ? {} : config, {
229
+ via: selfEid()
230
+ }, // Asked now and awaited only by a report: the commit is this run's, and
231
+ // a command that reports nothing does not wait on git to learn it.
232
+ config.tracker && !opts.readOnly ? config.tracker.commit ?? revision() : undefined, {
233
+ command: command(process.args),
234
+ roles: roles.join(',')
235
+ });
236
+ opts.reader?.overrun?.((error, asker)=>void report(error, asked(asker)));
237
+ let cleanup = async (step, release)=>{
238
+ try {
239
+ await release();
240
+ } catch (error) {
241
+ await report(error, {
242
+ tags: {
243
+ step
244
+ }
245
+ });
246
+ }
247
+ };
248
+ let mode = opts.mode ?? moding();
249
+ let opened;
250
+ // A store as of a transaction or on a branch is @yaks/sqlite's writing store
251
+ // (`moded`), which the read-only door does not open, so a reader in a mode
252
+ // takes the writer's connection.
253
+ let open = async ()=>opts.readOnly && !mode ? (await import("@yaks/sqlite/read-db")).open(path) : (await import("@yaks/sqlite/db")).open(path);
254
+ let recorded;
255
+ let captureControl;
256
+ // What @yaks/api catches in this process and answers, or meets with nobody
257
+ // to answer (a page body that did not build, a socket, a subscription), are
258
+ // reported here too, named by where they were caught.
259
+ let caught = (error, where)=>void report(error, {
260
+ during: {
261
+ process: selfEid()
262
+ },
263
+ tags: {
264
+ step: where
265
+ }
266
+ });
267
+ // A rejection nobody held is reported where it surfaced, and the host lives
268
+ // on: one stray promise never ends the process and every request it serves.
269
+ // A script's top-level await that failed arrives the same way, and is the
270
+ // script's own end: said and reported as a failure it met (a refusal of
271
+ // what it asked is its runner's to read, and only said), then the process
272
+ // exits 1, as it would with no host.
273
+ let stray = (event)=>{
274
+ event.preventDefault();
275
+ let own = process.mainFailed(event.reason);
276
+ void report(event.reason, own.then((ended)=>ended ? {
277
+ tags: {
278
+ step: 'main module'
279
+ }
280
+ } : {
281
+ during: {
282
+ process: selfEid()
283
+ },
284
+ mechanism: 'onunhandledrejection',
285
+ tags: {
286
+ step: 'unhandled rejection'
287
+ }
288
+ })).then(async ()=>{
289
+ if (await own) process.exit(1);
290
+ });
291
+ };
292
+ globalThis.addEventListener('unhandledrejection', stray);
293
+ let unhooked = faults(caught);
294
+ let unfault = ()=>{
295
+ unhooked();
296
+ globalThis.removeEventListener('unhandledrejection', stray);
297
+ };
298
+ try {
299
+ // An existing graph can refuse before any plugin runtime is imported.
300
+ // Keep its connection; absent graphs wait for a valid assembly before
301
+ // creating a file or its directory.
302
+ let exists = false;
303
+ if (path != ':memory:') {
304
+ try {
305
+ disk.statSync(path);
306
+ exists = true;
307
+ } catch (error) {
308
+ if (!(error instanceof disk.errors.NotFound)) throw error;
309
+ }
310
+ }
311
+ // What the store's data requires (a plugin that shaped how its rows are
312
+ // written) this config must compose, or the store is refused: a host
313
+ // without it would read or write those rows wrongly.
314
+ let required = [];
315
+ if (exists) {
316
+ part?.('sqlite');
317
+ opened = await open();
318
+ part?.('migrations');
319
+ migrations(opened).ready();
320
+ required = requirements(opened);
321
+ meet(config, required);
322
+ }
323
+ // Where this graph's secrets are kept (./vault.ts). Nothing is read from
324
+ // it here: an option naming a secret reads its local value when the
325
+ // option is read.
326
+ part?.('vault');
327
+ let trace = opts.process !== false && (config.tracker || path != ':memory:') ? await import("./traces.js") : undefined;
328
+ let vault = vaultOf(path);
329
+ let secretDeclarations = (config.plugins ?? []).flatMap((p)=>secretNames(given(p)).map((name)=>({
330
+ name,
331
+ package: used(p)
332
+ })));
333
+ let plugins = configured(config, revealing(vault));
334
+ let declared = load === facet ? await declarations(config) : undefined;
335
+ let stored = new Map(declared?.vocabs.filter((v)=>v.value !== null).map((v)=>[
336
+ v.plugin,
337
+ v
338
+ ]));
339
+ part?.('roles');
340
+ let observed = compositionAnatomy((config.plugins ?? []).map((p)=>({
341
+ name: used(p),
342
+ facets: facetsOf(p)
343
+ })), roles, ROLES, secretDeclarations);
344
+ // A declaration hit substitutes data only while its sources agree. The
345
+ // assembly sees the same facets as an ordinary loader, without CLI policy.
346
+ let preparedLoad = Object.assign(async (plugin, name)=>{
347
+ let data = name == 'vocab' ? stored.get(plugin) : undefined;
348
+ return data && !data.factories ? data.value : declared && !declared.facets[plugin].includes(name) ? null : await load(plugin, name);
349
+ }, {
350
+ together: (requests)=>load.together?.(requests.filter(([plugin, name])=>(!declared || declared.facets[plugin].includes(name)) && (name != 'vocab' || !declared || !!stored.get(plugin)?.factories))) ?? Promise.resolve()
351
+ });
352
+ let plan = await assembly(config, roles, preparedLoad, {
353
+ plugins,
354
+ observed,
355
+ part,
356
+ readOnly: opts.readOnly,
357
+ docs: opts.docs
358
+ });
359
+ let { storage } = opts.readOnly ? await import("@yaks/sqlite/read-store") : await import("@yaks/sqlite");
360
+ // A store as of a transaction or on a branch reads through a connection
361
+ // of its own: this one, which opened for nothing else.
362
+ let moded = mode && await import("@yaks/sqlite");
363
+ let opening = (o)=>{
364
+ if (!mode || !moded) return storage(sql, vocab, o);
365
+ let { history } = o;
366
+ if (!history) {
367
+ throw new Error('this graph keeps no history to read as of a transaction or branch: ' + 'list @yaks/journal with versions on');
368
+ }
369
+ if ('at' in mode) return moded.moded(sql, vocab, {
370
+ ...o,
371
+ history
372
+ }, mode);
373
+ let m = moded.branchOf(sql, mode.branch);
374
+ if (!m) throw new Error(`no branch ${mode.branch}`);
375
+ return moded.moded(sql, vocab, {
376
+ ...o,
377
+ history
378
+ }, m);
379
+ };
380
+ let { vocab, derived, backed } = plan.words;
381
+ if (!opened) {
382
+ part?.('sqlite');
383
+ opened = await open();
384
+ part?.('migrations');
385
+ // A new file has no migration control yet; a writer adds it first.
386
+ if (!opts.readOnly) add(opened, migrationSchema());
387
+ } else part?.('migrations');
388
+ let sql = opened;
389
+ let layout = bindStorage(sql, vocab);
390
+ // Facet imports may have awaited while another process announced work.
391
+ // Refuse again on the retained connection before domain schema or factories.
392
+ migrations(sql).ready();
393
+ part?.('host');
394
+ let blobs = sqliteBlobs(statements(sql), {}, opts.reader?.statements);
395
+ let chosen = plugins.find(([name])=>name == '@yaks/blob')?.[1].store;
396
+ let selected = chosen ? backend(chosen, {
397
+ blobs,
398
+ files: fileBlobs
399
+ }) : {
400
+ store: artifactsAt(path)
401
+ };
402
+ let artifacts = selected.store;
403
+ if (!artifacts) throw new Error(`@yaks/blob: ${selected.waiting}`);
404
+ let store;
405
+ // What the file keeps beside the store's own schema over its component
406
+ // tables, the search indexes among them, made with a component's table by
407
+ // its first write (@yaks/sqlite `over`). Composed once the plugins say
408
+ // theirs, after the store is bound.
409
+ let over = [];
410
+ // Search is a property of the declaration: a property marked `search: true`
411
+ // is indexed, whoever declared it, so wiring @yaks/fts here rather than in
412
+ // a plugin is what takes the vocabulary at its word. Two things follow
413
+ // from that one list of properties — a bare word in any query compiles to a
414
+ // text match (one more clause compiler beside the plugins'), and `/mcp`
415
+ // lists a ranked `search` tool. A property marked `contains: true` keeps a
416
+ // substring index beside them, which a `~=` test of it reads.
417
+ let text = indexed(vocab);
418
+ // The search's halves where it searches at all (./searching.ts).
419
+ let hits;
420
+ let said;
421
+ let host;
422
+ let g;
423
+ let record = (bundles)=>persist(()=>g.apply(bundles, {
424
+ trusted: true
425
+ }), (error)=>report(error, {
426
+ during: {
427
+ process: selfEid()
428
+ },
429
+ tags: {
430
+ step: 'process write'
431
+ }
432
+ }), clock);
433
+ let finish = async (holder, end)=>{
434
+ for(;;){
435
+ try {
436
+ return await record([
437
+ ...await released(g, holder),
438
+ end
439
+ ]);
440
+ } catch (error) {
441
+ if (!(error instanceof Stale)) throw error;
442
+ }
443
+ }
444
+ };
445
+ let endings = new Set();
446
+ let closed = false;
447
+ let doing;
448
+ let stopping = new AbortController();
449
+ let self = writer(vocab);
450
+ // The store's print, digested by the platform before the store is bound,
451
+ // so the schema below finds it made.
452
+ if (!opts.readOnly && !mode) await printing(layout, derived, !!sql.file);
453
+ // A web host warms when its server asks (@yaks/api `serve`): first what
454
+ // its routes make ahead of a first request, then, once that is made, the
455
+ // rest (`opts.warm`), so the first page answers before workers start.
456
+ // A make's failure is its route's to report; here it only settles.
457
+ let makes = [];
458
+ let warmed;
459
+ let warm = opts.warm && (()=>warmed ??= Promise.allSettled(makes.map((make)=>make())).then(()=>opts.warm()));
460
+ let early = opts.warm && ((make)=>{
461
+ if (warmed) void Promise.allSettled([
462
+ make()
463
+ ]);
464
+ else makes.push(make);
465
+ });
466
+ // Each branch's host, composed the first time a call names the branch:
467
+ // this config over a connection of its own on the branch, every plugin
468
+ // bound to it, so nothing it writes reaches main. Closed with this host,
469
+ // or when its branch is dropped.
470
+ let forks = new Map();
471
+ let forked = (id)=>{
472
+ let made = forks.get(id);
473
+ if (made) return made;
474
+ made = composed(config, [
475
+ 'graph'
476
+ ], load, {
477
+ mode: {
478
+ branch: id
479
+ },
480
+ process: false,
481
+ docs: opts.docs,
482
+ options: opts.options,
483
+ ...opts.clock ? {
484
+ clock: opts.clock
485
+ } : {}
486
+ });
487
+ forks.set(id, made);
488
+ made.catch(()=>forks.get(id) === made && forks.delete(id));
489
+ return made;
490
+ };
491
+ let unfork = async (id)=>{
492
+ let made = forks.get(id);
493
+ forks.delete(id);
494
+ await (await made?.catch(()=>undefined))?.close();
495
+ };
496
+ let unforked = ()=>Promise.all([
497
+ ...forks.keys()
498
+ ].map(unfork));
499
+ let built = plan.bind({
500
+ operations: platformOperations,
501
+ options: (plugin, options)=>{
502
+ let lent = opts.options?.(plugin, options) ?? options;
503
+ return plugin == '@yaks/tracker' ? trackerOptions(lent) : lent;
504
+ },
505
+ // A database in memory is its connection's alone, so no branch's host
506
+ // could open it.
507
+ branches: (h)=>{
508
+ let kept = h.storage.branches;
509
+ if (!kept || mode || path == ':memory:') return undefined;
510
+ return {
511
+ make: async ()=>await kept.make(),
512
+ list: async (trash)=>await kept.list(trash),
513
+ restore: async (id)=>await kept.restore(id),
514
+ changes: async (id)=>await kept.changes(id),
515
+ drop: async (id)=>{
516
+ await unfork(id);
517
+ await kept.drop(id);
518
+ },
519
+ // A branch nobody made is the caller's mistake, said before any
520
+ // host is composed for it.
521
+ on: async (id)=>{
522
+ if (!forks.has(id) && !(await kept.list()).some((b)=>b.id == id)) {
523
+ throw new Refused(`no branch ${id}`);
524
+ }
525
+ return (await forked(id)).graph;
526
+ }
527
+ };
528
+ },
529
+ unobserved: !!mode && 'branch' in mode,
530
+ tools: {
531
+ package: '@yaks/cli',
532
+ offer: (host)=>[
533
+ ...operations(host, {
534
+ config: opts.path
535
+ }),
536
+ feedbackTool(host),
537
+ ...opts.tools?.(host) ?? []
538
+ ]
539
+ },
540
+ host: {
541
+ fetch: freshFetch(),
542
+ cwd: process.cwd,
543
+ tailText: disk.tailTextSync,
544
+ vault,
545
+ // A key given to the box can be kept in 1Password too
546
+ // (@yaks/connections `keep`), where this machine has `op`.
547
+ keepers: {
548
+ '1password': opKeeper(vault)
549
+ },
550
+ blobs,
551
+ artifacts,
552
+ reader: opts.reader,
553
+ warm,
554
+ early,
555
+ me: selfEid(),
556
+ stopping: stopping.signal,
557
+ report: (error, context = {})=>report(error, {
558
+ ...context,
559
+ during: {
560
+ process: selfEid(),
561
+ ...context.during
562
+ }
563
+ }),
564
+ duties: (signal, only)=>{
565
+ if (!doing) throw new Error('the duties are not built yet');
566
+ return doing(signal, only);
567
+ },
568
+ end: (holder, why)=>{
569
+ if (closed) return Promise.resolve();
570
+ let work = (async ()=>{
571
+ // A thread that failed before it wrote itself in holds nothing.
572
+ if (!self || !g || !(await g.get([
573
+ holder
574
+ ])).length) return;
575
+ if (!opts.readOnly) await host.runner.interrupt(why, holder);
576
+ await finish(holder, {
577
+ entity: {
578
+ eid: holder
579
+ },
580
+ [EXIT]: {}
581
+ });
582
+ })();
583
+ endings.add(work);
584
+ let done = ()=>endings.delete(work);
585
+ work.then(done, done);
586
+ return work;
587
+ },
588
+ bury: async ()=>{
589
+ if (!self || !g) return [];
590
+ let { store, vanished } = await supervisor();
591
+ let dead = await vanished(store(g), {
592
+ me: selfEid()
593
+ });
594
+ for (let b of dead){
595
+ let pid = b[PROCESS]?.pid;
596
+ await host.end(b.entity.eid, `interrupted: process ${pid} ended without closing`);
597
+ }
598
+ // A workspace command records its ending when it is looked at, and
599
+ // whoever waited on it may have stopped looking first.
600
+ if (host.workspaces) {
601
+ await overdue(g, host.workspaces, (error, workspace)=>report(error, {
602
+ during: {
603
+ process: selfEid()
604
+ },
605
+ tags: {
606
+ step: 'workspace process look',
607
+ workspace
608
+ }
609
+ }));
610
+ }
611
+ return dead;
612
+ },
613
+ gone: async (holder)=>{
614
+ if (!self || !g) return false;
615
+ let { gone, store } = await supervisor();
616
+ return await gone(store(g), holder, {
617
+ me: selfEid()
618
+ });
619
+ }
620
+ },
621
+ actor: self,
622
+ process: started({
623
+ roles: [
624
+ ...roles
625
+ ]
626
+ })[PROCESS],
627
+ readOnly: opts.readOnly,
628
+ ...opts.clock ? {
629
+ clock: opts.clock
630
+ } : {},
631
+ storage: (built, extend, _words, history)=>{
632
+ host = built;
633
+ let o = {
634
+ derived,
635
+ backed,
636
+ extend,
637
+ number: numbering(vocab, config.numbers),
638
+ // A number given out before and kept as a name (@yaks/alias) is
639
+ // never given again.
640
+ ...vocab.comp(ALIAS) ? {
641
+ names: (prefix, num)=>aliasEid(format(prefix, num))
642
+ } : {},
643
+ history,
644
+ // A model turn reads its window again each step, a thousand lines
645
+ // of a long transcript: more than a Durable Object's 4 MiB keeps.
646
+ memory: 32 << 20,
647
+ over: ()=>over,
648
+ // What the store outlives and repairs, an entity no archetype
649
+ // names among it, is a bug all the same.
650
+ report: (error)=>report(error, {
651
+ during: {
652
+ process: selfEid()
653
+ }
654
+ })
655
+ };
656
+ store = opening(o);
657
+ return store;
658
+ },
659
+ // The text index follows plugin compilers, preserving their precedence.
660
+ extend: ()=>text.length ? [
661
+ search(text, sql, filler(sql))
662
+ ] : [],
663
+ // One print covers everything this file needs: the store's tables, the
664
+ // ones beside them, the plugins' own and the text indexes. A file that
665
+ // recorded it opens with no DDL; one that did not adds what is missing.
666
+ // What the pass leaves undone (a table whose rows do not fit, a unique
667
+ // index they break) or a pass that fails is reported, and the graph
668
+ // opens with the shape it holds; the print stays unrecorded, so the
669
+ // next opener tries again.
670
+ // A mode's connection reads the file its writers keep in shape.
671
+ schema: opts.readOnly || mode ? undefined : (_built, stmts)=>{
672
+ let beside = [
673
+ ...migrationSchema(),
674
+ ...blobSchema(),
675
+ ...stmts
676
+ ];
677
+ let indexes = textSchema(text, derived, layout);
678
+ over = [
679
+ ...beside,
680
+ ...indexes
681
+ ];
682
+ let print = printOf(store.print(), [
683
+ ...beside,
684
+ ...indexes
685
+ ]);
686
+ let told = (error)=>void report(error, {
687
+ during: {
688
+ process: selfEid()
689
+ },
690
+ tags: {
691
+ step: 'schema'
692
+ }
693
+ });
694
+ let needs = plan.required.filter((p)=>!required.includes(p));
695
+ let pass = ()=>{
696
+ try {
697
+ follow(sql, print, ()=>{
698
+ let left = [
699
+ ...store.install([
700
+ ...beside,
701
+ ...indexes
702
+ ]),
703
+ ...add(sql, beside)
704
+ ];
705
+ if (text.length) {
706
+ adopt(sql, text, derived, {
707
+ heal: false,
708
+ fill: filler(sql)
709
+ });
710
+ }
711
+ left.forEach(told);
712
+ return !left.length;
713
+ });
714
+ } catch (error) {
715
+ told(error);
716
+ }
717
+ // Before this host writes a row, the store records each plugin
718
+ // this composition says the rows it writes will need.
719
+ try {
720
+ requires(sql, needs);
721
+ } catch (error) {
722
+ told(error);
723
+ }
724
+ // What a reader's first look at the file finds, kept for every
725
+ // opener after this one until the schema moves.
726
+ try {
727
+ survey(sql, layout, derived);
728
+ } catch (error) {
729
+ told(error);
730
+ }
731
+ };
732
+ // A graph in memory this process already made with this print is a
733
+ // copy of the first: hundreds of statements become a page copy.
734
+ let key = JSON.stringify([
735
+ print,
736
+ needs
737
+ ]);
738
+ sql.template ? sql.template(key, pass) : pass();
739
+ },
740
+ effects: (built, disabled)=>{
741
+ return effects(vocab, {
742
+ owes: roles.includes('effects') ? 'handled' : 'declared',
743
+ disabled,
744
+ write: (b)=>built.graph.apply(b, {
745
+ trusted: true
746
+ }),
747
+ owner: built.me,
748
+ lease: config.lease,
749
+ gone: built.gone,
750
+ // How busy a worker says its process is (@yaks/effects worker).
751
+ cpu: ()=>{
752
+ let { user, system } = process.cpuUsage();
753
+ return (user + system) / 1000;
754
+ },
755
+ nudge: opts.thread?.nudge,
756
+ // Runs another process commits wake this one's pool at once. Only
757
+ // a new run wakes it: every other commit on the box would set it
758
+ // reading for work it already has, several times a second.
759
+ watch: (heard)=>{
760
+ let newest = opts.reader?.storage?.newest;
761
+ return newest ? watchRevision(()=>newest(EFFECT), heard, (error)=>void report(error, {
762
+ tags: {
763
+ step: 'watch effects'
764
+ }
765
+ }), clock) : store?.watch?.(EFFECT, heard) ?? (()=>{});
766
+ },
767
+ report: (error, job)=>void report(error, {
768
+ during: {
769
+ ...job.event ? {
770
+ entity: job.event.entity.eid
771
+ } : {},
772
+ process: built.me
773
+ },
774
+ tags: {
775
+ handler: job.handler
776
+ }
777
+ })
778
+ });
779
+ },
780
+ ready: (built)=>{
781
+ host = built;
782
+ g = built.graph;
783
+ Object.assign(built, delivery(built));
784
+ // Read workers return their recorded trees to their caller rather than
785
+ // duplicating delivery. A passing CLI and every duty/web process observe
786
+ // their graph, without composing tracker tables into the watched store.
787
+ // An unconfigured private memory graph has no telemetry destination
788
+ // or PID-local capture sidecar. Keeping its channel subscribed would
789
+ // build and discard a complete tree for every startup/catalogue write.
790
+ if (opts.process !== false && (config.tracker || path != ':memory:')) {
791
+ captureControl = config.tracker ? traceControl(path) : undefined;
792
+ recorded = trace.traces(g, {
793
+ getStart: getStarts(path),
794
+ process: selfEid(),
795
+ take: captureControl?.take ?? (()=>Promise.resolve({
796
+ requested: false,
797
+ rate: 0
798
+ })),
799
+ sink: config.tracker ? spool(files(config.tracker.spool).append) : undefined
800
+ });
801
+ }
802
+ built.workspaces = workspaceCapabilities(built, config);
803
+ built.sandboxes = sandboxCapabilities(built, config);
804
+ built.resolveHome = resolveHome(built, config);
805
+ },
806
+ search: (built)=>{
807
+ part?.('search');
808
+ if (!wordFields(text).length) return undefined;
809
+ hits = (words, count)=>find(sql, text, words, {
810
+ limit: count
811
+ });
812
+ said = async (words, found, limit)=>{
813
+ let people = await peopleSearch(built.graph, words, limit);
814
+ let ranked = merged(found.words, found.meaning, limit);
815
+ let hits = new Map(ranked.map((h)=>[
816
+ h.entity,
817
+ h
818
+ ]));
819
+ let named = new Set(people.map((h)=>h.entity));
820
+ for (let h of people){
821
+ let ranked = hits.get(h.entity);
822
+ hits.set(h.entity, {
823
+ ...h,
824
+ score: ranked?.score ?? 0,
825
+ snippet: h.snippet || ranked?.snippet || '',
826
+ source: ranked?.source == 'meaning' ? 'both' : ranked?.source ?? 'text'
827
+ });
828
+ }
829
+ let ordered = [
830
+ ...new Set([
831
+ ...named,
832
+ ...hits.keys()
833
+ ])
834
+ ];
835
+ let rows = await built.graph.get(ordered);
836
+ let hidden = unfound(vocab).not ?? [];
837
+ let at = new Map(rows.map((b)=>[
838
+ b.entity.eid,
839
+ b
840
+ ]));
841
+ // A snippet that says only the title says what the hit line
842
+ // already does; the row's other text says what it is.
843
+ let line = hit(vocab, split(words));
844
+ return ordered.flatMap((eid)=>{
845
+ let b = at.get(eid), h = hits.get(eid);
846
+ if (!b || named.has(eid) && (!b.person || hidden.some((c)=>b[c]))) return [];
847
+ return [
848
+ {
849
+ entity: b.entity,
850
+ hit: {
851
+ ...line(b, h.snippet),
852
+ source: h.source,
853
+ ...b.entry && typeof b.entry == 'object' && 'session' in b.entry && typeof b.entry.session == 'string' ? {
854
+ session: b.entry.session,
855
+ speaker: b.output ? 'output' : 'input'
856
+ } : {}
857
+ }
858
+ }
859
+ ];
860
+ }).slice(0, limit);
861
+ };
862
+ return searching(async (words, count, semantic)=>({
863
+ words: hits(words, count),
864
+ meaning: await built.meaning?.(semantic, {
865
+ limit: count
866
+ }) ?? []
867
+ }), said);
868
+ }
869
+ });
870
+ host = built.host;
871
+ g = host.graph;
872
+ let worded;
873
+ host.text = async (answer, tool, on)=>{
874
+ worded ??= (await import("./text.js")).text(host);
875
+ return worded(answer, tool, on);
876
+ };
877
+ // A numbered graph draws each eid in an answer's prose as the entity's
878
+ // id, from the small series it holds in memory and a read of the rest. A
879
+ // read that failed is reported, and the answer drawn with what it holds.
880
+ if (config.numbers) {
881
+ let draw;
882
+ host.readable = async (answer)=>{
883
+ if (!draw) {
884
+ let [{ held }, { drawing }] = await Promise.all([
885
+ import("@yaks/id/graph"),
886
+ import("@yaks/tools/readable")
887
+ ]);
888
+ let small = held(vocab, host.graph);
889
+ draw = drawing(vocab, (eids)=>small(eids).catch((error)=>{
890
+ report(error);
891
+ return ()=>undefined;
892
+ }), opts.reader?.readable);
893
+ }
894
+ return draw(answer);
895
+ };
896
+ }
897
+ let fx = host.fx;
898
+ // A read-only host commits nothing, so it owes no effects to work, even
899
+ // when its roles name them (a graph with no pool runs them where they
900
+ // are committed).
901
+ let effecting = roles.includes('effects') && !opts.readOnly;
902
+ // Whoever works the effects also works off the schema work a pass owed
903
+ // (@yaks/sqlite/owe), one process at a time under its lease, and does the
904
+ // file's upkeep: its statistics, and once a day a check that each text
905
+ // index holds every row, refilling in windows one that drifted. Between
906
+ // them it makes the pieces of the texts longer than a substring index
907
+ // holds (@yaks/fts `pieces`), a window each.
908
+ let upkeep = (signal, report)=>tend(sql, {
909
+ signal,
910
+ daily: text.length ? [
911
+ {
912
+ name: 'heal',
913
+ run: (d)=>void heal(d, text, {
914
+ derived,
915
+ fill: filler(d)
916
+ })
917
+ }
918
+ ] : [],
919
+ chores: text.length ? [
920
+ {
921
+ name: 'pieces',
922
+ run: (d)=>pieces(d, text, derived)
923
+ }
924
+ ] : [],
925
+ report
926
+ });
927
+ let tending = sql.file ? (signal, tell)=>upkeepThread(config, signal, tell) : upkeep;
928
+ let duties = effecting ? [
929
+ ...built.services,
930
+ {
931
+ name: SCHEMA_DUTY,
932
+ run: (signal)=>tending(signal, (error, work)=>void report(error, {
933
+ during: {
934
+ process: selfEid()
935
+ },
936
+ tags: {
937
+ step: 'schema',
938
+ work
939
+ }
940
+ }))
941
+ },
942
+ {
943
+ name: '@yaks/effects',
944
+ run: (signal)=>expiration(host.graph, {
945
+ owner: selfEid(),
946
+ signal,
947
+ report: (error)=>void report(error, {
948
+ during: {
949
+ process: selfEid()
950
+ },
951
+ tags: {
952
+ step: 'expiration'
953
+ }
954
+ })
955
+ })
956
+ }
957
+ ] : built.services;
958
+ // Started together and stopped together, by one signal: a host shutting
959
+ // down is one fact, and a duty that outlived the database it
960
+ // reads would be a crash nobody asked for. One that throws is reported
961
+ // and that plugin's duty stops — the others keep going, the way a failing
962
+ // effect is telemetry rather than a broken host. The duties this host
963
+ // handed to a thread of its own run beside these, under the same signal.
964
+ // A config that turned them off (`duties: false`) takes no lease, works
965
+ // no effects and runs none of them, in either form. The CLI's
966
+ // `--no-duties` disables inline duties; web still restores external workers:
967
+ // what it commits is left written down for a process that does.
968
+ //
969
+ // A thread gone without closing — ended where it stood, or failed — ran in
970
+ // this process's pid, which goes on, so nobody can tell it is over until
971
+ // this host writes its ending: once, however many of its promises say so.
972
+ let ending;
973
+ let lose = (error)=>{
974
+ void report(error, {
975
+ during: {
976
+ process: host.me
977
+ },
978
+ tags: {
979
+ step: 'duty thread'
980
+ }
981
+ });
982
+ return ending ??= host.end(opts.thread.me, 'interrupted: its thread ended before it closed').catch((e)=>report(e, {
983
+ tags: {
984
+ step: 'end duty thread'
985
+ }
986
+ }));
987
+ };
988
+ let dutiesHost = serveRoles(g, {
989
+ me: selfEid(),
990
+ roles: [
991
+ ...effecting ? [
992
+ 'effects'
993
+ ] : [],
994
+ ...duties.map((d)=>d.name)
995
+ ],
996
+ fx: effecting ? fx : undefined,
997
+ services: Object.fromEntries(duties.map((d)=>[
998
+ d.name,
999
+ d.run
1000
+ ])),
1001
+ hold: config.lease,
1002
+ gone: host.gone,
1003
+ report: (error, role)=>report(error, {
1004
+ during: {
1005
+ process: host.me
1006
+ },
1007
+ tags: role == 'effects' ? {
1008
+ step: 'effects'
1009
+ } : {
1010
+ role
1011
+ }
1012
+ })
1013
+ });
1014
+ doing = config.duties == false ? async ()=>{} : (signal, only)=>{
1015
+ let until = signal ?? stopping.signal;
1016
+ return Promise.all([
1017
+ ...opts.thread ? [
1018
+ opts.thread.duties(until).catch(lose)
1019
+ ] : [],
1020
+ dutiesHost.duties(until, only)
1021
+ ]).then(()=>{});
1022
+ };
1023
+ // A draining process is alive but no longer covers its duty roles. Publish
1024
+ // that before waiting for in-flight steps, so the web can replace it.
1025
+ let retiring;
1026
+ let retire = ()=>retiring ??= self && opts.process !== false && !opts.readOnly ? Promise.resolve(record([
1027
+ {
1028
+ entity: {
1029
+ eid: selfEid()
1030
+ },
1031
+ process: {
1032
+ roles: roles.filter((role)=>role == 'graph' || role == 'web')
1033
+ }
1034
+ }
1035
+ ])).catch((error)=>report(error, {
1036
+ tags: {
1037
+ step: 'retire duties'
1038
+ }
1039
+ })) : Promise.resolve();
1040
+ // Its effects, drained once: begun by the first of `stop` and `close`,
1041
+ // and awaited by `close`.
1042
+ let draining;
1043
+ let drained = ()=>draining ??= drain(fx, (line)=>console.error(line));
1044
+ let closing;
1045
+ // This process, written in, with the roles it serves. First among the
1046
+ // writes, because everything after is attributed to it and `created.by`
1047
+ // is a reference: a process attributing writes to an entity nothing
1048
+ // created would store a dangling id on its very first write. What a
1049
+ // process starting owes is owed when it starts working the effects
1050
+ // (@yaks/effects `start`), not here.
1051
+ part?.('process');
1052
+ if (self && opts.process !== false && !opts.readOnly) {
1053
+ await record([
1054
+ started({
1055
+ roles: [
1056
+ ...roles
1057
+ ]
1058
+ })
1059
+ ]);
1060
+ }
1061
+ let lifecycle = {
1062
+ storage: g.storage,
1063
+ upkeep,
1064
+ graph: g,
1065
+ fx,
1066
+ hits,
1067
+ said,
1068
+ // The last transaction, then the file: every lease this process holds
1069
+ // released, and its ending stamped. One transaction, because they are
1070
+ // one fact — a process that is over is not doing any work, and the next
1071
+ // process to ask should not have to wait out a lease nobody is using.
1072
+ // Last, because an absent `exit` is what running means, so a process
1073
+ // that closed without stamping one reads as still running forever.
1074
+ //
1075
+ // First of all, the abort: the duties stop and every timer a
1076
+ // plugin hung off {@link Host.stopping} is cancelled, so nothing is
1077
+ // still pending over a database that is about to be closed. It leaves
1078
+ // the pool, so what it commits from then on, its last transaction
1079
+ // included, is left written down for another, and the effects it
1080
+ // started are let finish, for as long as each takes (./drain.ts). Then
1081
+ // the thread beside it closes, draining the same way. A thread that does
1082
+ // not close, this host writes the ending of. The calls this process was
1083
+ // still running are ended first, as interrupted, so none is left to
1084
+ // lapse.
1085
+ stop: ()=>{
1086
+ void retire();
1087
+ stopping.abort();
1088
+ dutiesHost.stop();
1089
+ if (effecting) void drained();
1090
+ },
1091
+ close: (code)=>closing ??= (async ()=>{
1092
+ let wait = async (name, work)=>{
1093
+ let cancel = clock.after(5000, ()=>console.error(`host drain — ${name}`));
1094
+ try {
1095
+ return await work();
1096
+ } finally{
1097
+ cancel();
1098
+ }
1099
+ };
1100
+ await wait('retire', retire);
1101
+ await wait('branches', unforked);
1102
+ stopping.abort();
1103
+ dutiesHost.stop();
1104
+ await wait('duty thread', ()=>opts.thread?.close().catch(lose));
1105
+ await wait('thread ending', ()=>ending);
1106
+ if (effecting) await wait('effects', drained);
1107
+ await wait('duties', ()=>dutiesHost.close());
1108
+ await wait('plugins', ()=>cleanup('dispose plugins', built.close));
1109
+ let shut = async ()=>{
1110
+ await wait('capture', ()=>cleanup('close capture', ()=>captureControl?.close()));
1111
+ await wait('traces', ()=>cleanup('close traces', ()=>recorded?.close()));
1112
+ // A forced ending can arrive while graceful shutdown drains. Stop
1113
+ // admitting endings and finish those already admitted before SQL
1114
+ // closes; a late repeat has nothing left to release. An ending
1115
+ // reads through the reader, so it closes after them.
1116
+ closed = true;
1117
+ await wait('endings', ()=>Promise.allSettled([
1118
+ ...endings
1119
+ ]));
1120
+ await wait('reader', ()=>cleanup('close reader', ()=>opts.reader?.close?.()));
1121
+ await wait('storage', ()=>cleanup('close storage', ()=>sql.close()));
1122
+ unfault();
1123
+ await wait('reports', ()=>report.close());
1124
+ };
1125
+ // A call whose tool has not returned by now never will in this
1126
+ // process. Ended as interrupted, rather than left claimed for a sweep
1127
+ // to run again in a process nobody asked — a server, a tail, a land in
1128
+ // somebody else's checkout.
1129
+ if (!opts.readOnly) {
1130
+ await wait('interrupt calls', ()=>built.interrupt(`interrupted: this process ended${code == null ? '' : ` with code ${code}`} before the tool returned`).catch((e)=>report(e, {
1131
+ tags: {
1132
+ step: 'interrupt calls'
1133
+ }
1134
+ })));
1135
+ }
1136
+ if (!self || opts.process === false || opts.readOnly) {
1137
+ return shut();
1138
+ }
1139
+ try {
1140
+ await wait('process ending', ()=>finish(selfEid(), ended(code)));
1141
+ } catch (e) {
1142
+ await report(e, {
1143
+ tags: {
1144
+ step: 'close host'
1145
+ }
1146
+ });
1147
+ }
1148
+ await shut();
1149
+ })()
1150
+ };
1151
+ // Spreading Host would invoke its lazy tools/runner getters here.
1152
+ return Object.defineProperties({}, {
1153
+ ...Object.getOwnPropertyDescriptors(host),
1154
+ ...Object.getOwnPropertyDescriptors(lifecycle)
1155
+ });
1156
+ } catch (error) {
1157
+ try {
1158
+ await report(error, {
1159
+ tags: {
1160
+ step: 'compose host'
1161
+ }
1162
+ });
1163
+ await cleanup('close capture', ()=>captureControl?.close());
1164
+ await cleanup('close traces', ()=>recorded?.close());
1165
+ await cleanup('close storage', ()=>opened?.close());
1166
+ } finally{
1167
+ unfault();
1168
+ await report.close();
1169
+ }
1170
+ throw error;
1171
+ }
1172
+ };
1173
+ export let reader = async (...args)=>(await import("./reader.js")).reader(...args);
1174
+ //# sourceMappingURL=host.js.map