@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/local.ts ADDED
@@ -0,0 +1,537 @@
1
+ import * as system from '@yaks/process/system'
2
+ import * as disk from '@yaks/file/io'
3
+ // The graph this process opens. `yak --config yak.json task list` reads that
4
+ // config file, imports the plugins it names over the SQLite file it names,
5
+ // runs the tool right here and exits — no server, no socket, nothing
6
+ // listening.
7
+ //
8
+ // That is how a `yak` command runs where no `yak serve` answers for its graph
9
+ // (./warm.ts asks the one that does). SQLite in WAL mode accepts as
10
+ // many writers as there are commands running, each one serialized by the file
11
+ // itself, so nothing bottlenecks on a process somebody has to remember to
12
+ // start. `yak serve` is one more of those commands: a tool that stays up
13
+ // answering HTTP over the same file (@yaks/api).
14
+ //
15
+ // Listing the commands opens nothing and loads nothing of this module: the
16
+ // tools a graph offers are declared in its plugins' `./vocab` (./words.ts), so
17
+ // the usage page, a help page and a mistyped word cost no database
18
+ // (./subcommands.ts). Running one opens the graph for the roles that
19
+ // command's process serves (host.ts `compose`): the graph, and whatever else
20
+ // its tool declares it needs — `serve` answers HTTP, so its process serves
21
+ // `web`.
22
+ //
23
+ // A command line runs a tool through the tool runner. A read-only command
24
+ // opens SQLite read-only and records nothing; a writing command records its
25
+ // call and result. What came back is shown through
26
+ // the plugins' views (./answer.ts). Recorded work uses the same rules,
27
+ // post-commit effects and attribution whichever door asked for it.
28
+ //
29
+ // The effect pool and the plugins' services are never this thread's. A host
30
+ // that stays up explicitly starts them through `host.duties()` (@yaks/threads),
31
+ // so a command passing through never claims work it cannot finish.
32
+ //
33
+ // This module is imported only by a command that runs against a graph,
34
+ // because importing it pulls in everything that opens one — a cost `yak help`
35
+ // should not pay, nor `yak login` on a machine with no graph.
36
+
37
+ import type { Actor, Bundle, Graph } from 'jsr:@yaks/graph@0.2.36'
38
+ import { mint } from '@yaks/graph/identity'
39
+ import { signed } from '@yaks/graph/provenance'
40
+ import type { AnatomyObservation } from 'jsr:@yaks/code@0.2.36/anatomy'
41
+ import type { Vocab } from 'jsr:@yaks/vocab@0.2.36'
42
+ import { EFFECT } from '@yaks/effects'
43
+ import { answerOf, faulted, structured, toolEid } from '@yaks/tools/result'
44
+ import { ailing } from '@yaks/tools/check'
45
+ import { registry } from './answer.js'
46
+ import { shown } from './shown.js'
47
+ import { type Config, exported, pluginViews, read, used } from './config.js'
48
+ import { asides, hosts } from './held.js'
49
+ import type { Listing } from './subcommands.ts'
50
+ import { VIA } from './rpc.js'
51
+ import type { Ctx } from './run.ts'
52
+ import {
53
+ type CliCommand,
54
+ compose,
55
+ dbOf,
56
+ type Declared,
57
+ facet,
58
+ person,
59
+ type Role,
60
+ type Served,
61
+ } from './host.js'
62
+ import { readThread } from './read_thread.js'
63
+ import { stalls, thread as threadPath } from './stall.js'
64
+ import { sampler } from './stall_profile.js'
65
+ import { waitSampler } from './stall_wait.js'
66
+ import { thread } from '@yaks/threads'
67
+ import { during, peek } from '@yaks/trace'
68
+ import { dutyRoles, rolesOf, workerRoles } from './roles.js'
69
+ import { declarations } from './declarations.js'
70
+ import { lifetime } from './lifetime.js'
71
+ import { bound } from './drain.js'
72
+ export { rolesOf } from './roles.js'
73
+
74
+ /** The duty roles of a config's graph that a process serving `mine` does not
75
+ * cover already: the effect pool, where the graph keeps one, and each plugin's
76
+ * service. A plugin that exports no `./service` has none (`has`, the resolver
77
+ * asked rather than the module imported). */
78
+ export let dutiesOf = (
79
+ vocab: Vocab,
80
+ config: Config,
81
+ mine: readonly Role[],
82
+ has: (plugin: string, facet: string) => boolean = exported,
83
+ ): Role[] => dutyRoles(config, !!vocab.comp(EFFECT), mine, has)
84
+
85
+ // A process that stays up answers its committed reads in a read thread beside
86
+ // it (./read_thread.ts), lent to its graph (@yaks/graph `Lent`): a slow read,
87
+ // whoever asked it, holds a worker's lane and never the thread its requests,
88
+ // duties, leases and sockets run on. Committed preflight, address and journal
89
+ // reads use it too. A write and its transaction reads stay on their owner.
90
+ // A read sent after a write commits sees it.
91
+ // A passing command opens none; it would wait on the workers starting.
92
+ let HOUR = 60 * 60 * 1000
93
+
94
+ let lend = (path: string, config: Config) =>
95
+ dbOf(config) != ':memory:' ? readThread(path) : undefined
96
+
97
+ // The graph a command opens: composed for its own roles, with its duty roles
98
+ // external for web, otherwise planned in a thread beside it. Only a host
99
+ // explicitly serving duties starts that thread. Every commit still records the effects it owes for a worker to
100
+ // claim, whether this command or another process wrote it.
101
+ let open = async (
102
+ path: string,
103
+ roles: Role[],
104
+ duties: boolean,
105
+ readOnly = false,
106
+ ): Promise<Served> => {
107
+ let config = read(path)
108
+ let web = roles.includes('web')
109
+ let reader = web ? lend(path, config) : undefined
110
+ // A web listens first and warms after, when its server asks (@yaks/api
111
+ // `serve`): its reader's workers start, so a read is as fast as the next,
112
+ // its main thread is watched ({@link watched}), and then workers start for
113
+ // the duty roles nothing covers. An earlier read starts its worker itself
114
+ // and waits asynchronously for it. Warming settles once the
115
+ // workers it started for uncovered duty roles are ready, so a server's
116
+ // `--ready` says every module it runs is loaded. A warming that fails
117
+ // rejects, and the server ends.
118
+ let host: Served | undefined
119
+ let cover = (): Promise<void> => Promise.resolve()
120
+ let warming: Promise<void> | undefined
121
+ let warm = web
122
+ ? () =>
123
+ warming ??= (reader ? watched(host!, reader.ready()) : Promise.resolve())
124
+ .then(() => cover())
125
+ : undefined
126
+ if (
127
+ readOnly || config.duties === false || (!duties && !web)
128
+ ) {
129
+ return host = await compose({ ...config, duties: false }, roles, facet, {
130
+ path,
131
+ reader,
132
+ warm,
133
+ readOnly,
134
+ })
135
+ }
136
+ if (web) {
137
+ let served = host = await compose(config, roles, facet, {
138
+ path,
139
+ reader,
140
+ warm,
141
+ })
142
+ cover = () => covered(served, path, config, roles)
143
+ return served
144
+ }
145
+ let aside = thread<string>(new URL('./duties.ts', import.meta.url))
146
+ asides.add(aside)
147
+ host = await compose(config, roles, facet, {
148
+ path,
149
+ thread: aside,
150
+ reader,
151
+ })
152
+ try {
153
+ aside.plan({ data: path, roles: dutiesOf(host.vocab, config, roles) })
154
+ } catch (error) {
155
+ await host.close()
156
+ await reader?.close()
157
+ throw error
158
+ }
159
+ return host
160
+ }
161
+
162
+ // Workers for the duty roles of a web's graph that no live process serves,
163
+ // started and watched for as long as the web is up. Only a web host starts
164
+ // them, so only it loads how. What fails is reported, and the web stays up.
165
+ let covered = async (
166
+ host: Served,
167
+ path: string,
168
+ config: Config,
169
+ roles: Role[],
170
+ ): Promise<void> => {
171
+ try {
172
+ let { external } = await import('./external.js')
173
+ if (host.stopping.aborted) return
174
+ let coverage = external(
175
+ host.graph,
176
+ path,
177
+ dutiesOf(host.vocab, config, roles),
178
+ {
179
+ signal: host.stopping,
180
+ report: (error, role) =>
181
+ host.report?.(error, {
182
+ tags: { step: 'duty coverage', ...role ? { role } : {} },
183
+ }),
184
+ feed: host.feed,
185
+ },
186
+ )
187
+ let close = host.close
188
+ host.close = async (code) => {
189
+ await coverage.close()
190
+ await close(code)
191
+ }
192
+ await coverage.checked
193
+ } catch (error) {
194
+ await host.report?.(error, { tags: { step: 'duty coverage' } })
195
+ }
196
+ }
197
+
198
+ // A process that stays up tells of a main thread held so long that its
199
+ // timers, sockets and requests all waited on it (./stall.ts), with the stacks
200
+ // sampled while it was held (./stall_profile.ts). Watching starts once `ready`
201
+ // settles, and the host's close stops it.
202
+ let watched = (
203
+ host: Served,
204
+ ready: Promise<unknown> = Promise.resolve(),
205
+ ): Promise<void> => {
206
+ let profile: Awaited<ReturnType<typeof sampler>> | undefined
207
+ let waiting: ReturnType<typeof waitSampler> | undefined
208
+ let unwatch = () => {}
209
+ let done = (async () => {
210
+ await ready
211
+ let started = profile = await sampler()
212
+ let observer = waiting = waitSampler(threadPath())
213
+ // Silent once started: its samples are told only in a stall's report.
214
+ unwatch = stalls({
215
+ sample: (ms, held) => {
216
+ let end = performance.timeOrigin + performance.now()
217
+ let evidence = held
218
+ ? [
219
+ `held interval: ${new Date(end - ms).toISOString()} to ${
220
+ new Date(end).toISOString()
221
+ }`,
222
+ observer.take(ms),
223
+ ].filter(Boolean).join('\n')
224
+ : ''
225
+ return started.take(ms, held)?.catch((error) => {
226
+ void host.report?.(error, {
227
+ tags: { step: 'main thread sampling' },
228
+ })
229
+ return `stack sampling failed: ${String(error)}`
230
+ }).then((stack) => held ? `${evidence}\n${stack}` : undefined)
231
+ },
232
+ report: (error) =>
233
+ void host.report?.(error, { tags: { step: 'main thread' } }),
234
+ })
235
+ })()
236
+ let close = host.close
237
+ host.close = async (code) => {
238
+ await done.catch(() => {})
239
+ unwatch()
240
+ waiting?.close()
241
+ try {
242
+ await profile?.close()
243
+ } finally {
244
+ await close(code)
245
+ }
246
+ }
247
+ return done
248
+ }
249
+
250
+ /** The graph a config names, open for the roles a command's own thread serves,
251
+ * with duties available to a host that explicitly starts them. `--no-duties`
252
+ * disables inline duties, not external web recovery; config `duties: false`
253
+ * disables both. Assembled once per config path and roles; {@link close}
254
+ * closes it when the command is done. */
255
+ export let opened = (
256
+ path: string,
257
+ roles: Role[],
258
+ duties = true,
259
+ readOnly = false,
260
+ ): Promise<Served> => {
261
+ let key = JSON.stringify([path, roles, readOnly])
262
+ let host = hosts.get(key)
263
+ if (!host) hosts.set(key, host = open(path, roles, duties, readOnly))
264
+ return host
265
+ }
266
+
267
+ /** The independent duty process. Its graph is registered with the same wind
268
+ * down path as any command: stop claims, finish in-flight work, then close.
269
+ * Readiness means the pool's handlers and graph are assembled, not that old
270
+ * singleton services have surrendered their leases. */
271
+ export let work = async (
272
+ path: string,
273
+ ready?: string,
274
+ only?: string[],
275
+ tethered = false,
276
+ process?: string,
277
+ ): Promise<void> => {
278
+ let config = read(path)
279
+ let lives = await lifetime(
280
+ dbOf(config),
281
+ tethered ? system.stdin.readable : undefined,
282
+ ready,
283
+ )
284
+ let said = await declarations(config)
285
+ let duties = dutyRoles(
286
+ config,
287
+ said.pooled,
288
+ [],
289
+ (p, name) => said.facets[p].includes(name),
290
+ )
291
+ let roles = workerRoles(config, duties, only, process)
292
+ let key = JSON.stringify([path, roles])
293
+ let reader = lend(path, config)
294
+ let opening = compose(config, roles, facet, { reader }).catch(
295
+ async (error) => {
296
+ await reader?.close()
297
+ throw error
298
+ },
299
+ )
300
+ hosts.set(key, opening)
301
+ let host = await opening
302
+ let unbound = bound(
303
+ host.fx,
304
+ host.stopping,
305
+ () => system.exit(1),
306
+ console.error,
307
+ )
308
+ // A worker's thread is watched as a web's is, once its reader has started:
309
+ // a stall says what held it. A reader that cannot start is reported, and
310
+ // its callers hear the failure without falling back to blocking SQL here.
311
+ let started = reader?.ready().catch((error) =>
312
+ host.report?.(error, { tags: { step: 'read' } })
313
+ )
314
+ watched(host, started).catch((error) =>
315
+ host.report?.(error, { tags: { step: 'main thread sampling' } })
316
+ )
317
+ let close = host.close
318
+ host.close = async (code) => {
319
+ try {
320
+ await close(code)
321
+ } finally {
322
+ unbound()
323
+ }
324
+ }
325
+ await host.bury()
326
+ let { reconcile } = await import('@yaks/tools')
327
+ let timer = setInterval(() => {
328
+ void lives().then((live) => {
329
+ if (!live) host.stop()
330
+ }, (error) => {
331
+ console.error(error)
332
+ host.stop()
333
+ })
334
+ }, 1000)
335
+ // What ends while this worker runs is buried within the hour, not at the
336
+ // next start.
337
+ let burying = setInterval(() => {
338
+ void host.bury().catch((error) =>
339
+ host.report?.(error, { tags: { step: 'bury' } })
340
+ )
341
+ }, HOUR)
342
+ let running = Promise.all([host.duties(), reconcile(host.runner)])
343
+ try {
344
+ if (ready) {
345
+ // Readiness names the process a caller owns and signals.
346
+ await disk.writeTextFile(ready, `${system.pid}\n`)
347
+ }
348
+ await running
349
+ } finally {
350
+ clearInterval(timer)
351
+ clearInterval(burying)
352
+ if (ready) {
353
+ await disk.remove(ready).catch((error) => {
354
+ if (!(error instanceof disk.errors.NotFound)) throw error
355
+ })
356
+ }
357
+ }
358
+ }
359
+
360
+ export { close, cut, stop } from './held.js'
361
+
362
+ /** Who a command line writes as: the answer the host's door gives a request
363
+ * naming this line's session in `x-via`, exactly as it answers one arriving
364
+ * over HTTP (@yaks/session/graph), so a session's writes are its own however
365
+ * they reached the graph. A door that knows no such session answers this
366
+ * process ({@link writer} in ./host.ts), and a line with no session, typed at a
367
+ * terminal, writes as the config's `person` through it: an agent's shell always
368
+ * names its session (run.ts `via`), so a keyboard with none is the person's. */
369
+ export let signer = async (
370
+ host: Pick<Served, 'who' | 'config' | 'graph'>,
371
+ via?: string,
372
+ typed: boolean = system.stdin.isTerminal(),
373
+ ): Promise<{ $actor?: Actor }> => {
374
+ let actor = await host.who(
375
+ new Request('http://localhost/', { headers: via ? { [VIA]: via } : {} }),
376
+ )
377
+ let by = !via && typed ? await person(host) : undefined
378
+ if (by) return { $actor: { ...actor, by } }
379
+ return actor ? { $actor: { ...actor } } : {}
380
+ }
381
+
382
+ /** Restore supplied server-owned values through normal graph admission,
383
+ * guards, rules, stamps and journaling. The journal writer is the current
384
+ * caller; historical component values do not grant their author authority. */
385
+ export let restoreInto = (
386
+ graph: Graph,
387
+ bundles: Bundle[],
388
+ actor: Actor | null,
389
+ opts: { check?: boolean; stamp?: boolean } = {},
390
+ ): Bundle[] | Promise<Bundle[]> =>
391
+ graph.apply(signed(bundles, actor), { ...opts, trusted: true })
392
+
393
+ /** The filesystem command's restoration door, unavailable to remote calls. */
394
+ export let restore = async (
395
+ args: Record<string, unknown>,
396
+ c: Ctx,
397
+ ): Promise<number> => {
398
+ let host = await opened(c.config!, ['graph'], c.duties)
399
+ let { $actor } = await signer(host, c.via)
400
+ let bundles = await restoreInto(
401
+ host.graph,
402
+ args.bundles as Bundle[],
403
+ $actor ?? null,
404
+ { check: args.check === true, stamp: args.stamp !== false },
405
+ )
406
+ c.out(JSON.stringify(bundles, null, 2))
407
+ return 0
408
+ }
409
+
410
+ // The views an answer is drawn with, imported when one is first drawn, never
411
+ // to list; one registry per listing.
412
+ let drawing = new WeakMap<
413
+ Listing,
414
+ { views: ReturnType<typeof registry>; seen: AnatomyObservation[] }
415
+ >()
416
+ let drawn = (listing: Listing, host: Served) => {
417
+ let made = drawing.get(listing)
418
+ if (!made) {
419
+ let seen: AnatomyObservation[] = []
420
+ let views = registry(plugins(listing), pluginViews, (o) => seen.push(o))
421
+ drawing.set(listing, made = { views, seen })
422
+ }
423
+ for (let o of made.seen) host.observe?.(o)
424
+ return made.views
425
+ }
426
+
427
+ let plugins = (listing: Listing) => (listing.config.plugins ?? []).map(used)
428
+
429
+ // The graph a listed command runs against, opened for the roles it declares,
430
+ // with the terminal controls the listing loaded written into its anatomy.
431
+ let opening = async (
432
+ c: Ctx,
433
+ declared: Pick<Declared, 'roles' | 'readOnly'>,
434
+ listing: Listing,
435
+ ): Promise<Served> => {
436
+ let host = await opened(
437
+ c.config!,
438
+ rolesOf(declared, listing.said.pooled),
439
+ c.duties,
440
+ !!declared.readOnly,
441
+ )
442
+ for (let { plugin, value } of listing.said.controls) {
443
+ host.observe?.({
444
+ package: plugin,
445
+ facet: 'cli',
446
+ loaded: value !== null,
447
+ bound: true,
448
+ value,
449
+ })
450
+ }
451
+ return host
452
+ }
453
+
454
+ // A server's tool lasts for the process lifetime; its HTTP/socket requests
455
+ // must be independent roots, not children of that command.
456
+ let spanOf = (
457
+ host: Served,
458
+ declared: { roles?: readonly string[]; name?: string },
459
+ ) =>
460
+ declared.roles?.includes('web') ? undefined : peek(host.graph)?.begin({
461
+ kind: 'request',
462
+ name: `cli ${declared.name}`,
463
+ package: '@yaks/cli',
464
+ })
465
+
466
+ /** One of the graph's tools, run as a command line asked: the graph opened
467
+ * for it, the call made through the tool runner, and the answer printed. */
468
+ export let tool = async (
469
+ c: Ctx,
470
+ declared: Declared,
471
+ args: Record<string, unknown>,
472
+ listing: Listing,
473
+ ): Promise<number> => {
474
+ // A tool that declares terminal behavior receives the global display
475
+ // choice through the same input it declares for every other argument.
476
+ let props = declared.inputSchema?.properties
477
+ if (props && typeof props == 'object' && 'tui' in props) {
478
+ args.tui = c.tui
479
+ }
480
+ let branch = typeof args.branch == 'number' ? args.branch : undefined
481
+ // What the answer names is drawn as the branch it was read on holds it.
482
+ let on = branch === undefined ? undefined : { branch }
483
+ let host = await opening(c, declared, listing)
484
+ // Write the `tool` rows a call's `to` points at first: a call naming an
485
+ // entity nothing created would be a dangling reference. Done once per
486
+ // process, by whichever caller gets there first (@yaks/tools `ensure`).
487
+ if (!declared.readOnly) await host.runner.ensure([declared.name])
488
+ let id = mint()
489
+ let invoke = declared.readOnly ? host.runner.read : host.runner.call
490
+ let call = {
491
+ entity: { eid: id },
492
+ call: { to: toolEid(declared.name), args: args ?? {} },
493
+ ...await signer(host, c.via),
494
+ }
495
+ let landed = await during(spanOf(host, declared), () => invoke(call))
496
+ // `--json` prints the answer as data, the same object an MCP client
497
+ // reads as `structuredContent` (@yaks/tools `structured`).
498
+ let answer = answerOf(landed, id)
499
+ if (host.readable) answer = await host.readable(answer)
500
+ if (c.json) {
501
+ c.out(JSON.stringify(structured(declared, answer), null, 2))
502
+ } else if (!c.tui && !c.tty && host.text) {
503
+ let text = await host.text(answer, declared, on)
504
+ if (text) c.out(text)
505
+ } else {
506
+ await shown(
507
+ c,
508
+ plugins(listing),
509
+ await drawn(listing, host),
510
+ host.vocab,
511
+ answer,
512
+ {
513
+ lookup: (eids) => host.graph.get(eids, undefined, on),
514
+ query: (q) => host.graph.read(q, on),
515
+ },
516
+ declared,
517
+ host.observe,
518
+ )
519
+ }
520
+ // A refusal is data, not an exception: the text is printed either way
521
+ // and the exit code is what reports which it was — taken from the runner,
522
+ // since a tool that returns fault rows has not itself failed — or from a
523
+ // check's own verdict.
524
+ return faulted(landed, id) || ailing(declared, answer) ? 1 : 0
525
+ }
526
+
527
+ /** A plugin's terminal control, run against the graph opened for it. */
528
+ export let control = async (
529
+ c: Ctx,
530
+ declared: Omit<CliCommand, 'run'>,
531
+ run: CliCommand['run'],
532
+ args: Record<string, unknown>,
533
+ listing: Listing,
534
+ ): Promise<number> => {
535
+ let host = await opening(c, declared, listing)
536
+ return await during(spanOf(host, declared), () => run(args, host, c))
537
+ }
package/lockfile.js ADDED
@@ -0,0 +1,20 @@
1
+ // Whether a checkout's node_modules was installed from its lockfile. It
2
+ // imports nothing, so the installer's bootstrap (bin/workspace-dependencies.ts)
3
+ // can ask before node_modules exists, when no workspace package resolves.
4
+ /** The lockfile a checkout at root wants installed. */ export let wanted = (root)=>`${root}/pnpm-lock.yaml`;
5
+ /** pnpm's copy of the lockfile it last installed at root, without the
6
+ * document that pins pnpm itself. */ export let current = (root)=>`${root}/node_modules/.pnpm/lock.yaml`;
7
+ /** The input a completed frozen install used. pnpm's virtual store lock can
8
+ * differ from it when pnpm normalizes or selects entries for this host. */ export let installedFrom = (root)=>`${root}/node_modules/.pnpm/.yak-lock.yaml`;
9
+ // A formatter may have rewrapped the lockfile's flow mappings (`{ a: 1, }` over
10
+ // three lines where pnpm writes `{a: 1}`): its whitespace and trailing commas
11
+ // are not what pnpm installed.
12
+ let packages = (lock)=>lock?.split(/^---\n/m).at(-1)?.replace(/\s+/g, '').replaceAll(',}', '}');
13
+ /// differs('a', 'a') -> false
14
+ /// differs('---\npnpm: 12\n\n---\na', 'a') -> false
15
+ /// differs('a: {\n b: 1,\n}\n', 'a: {b: 1}') -> false
16
+ /// differs('a', 'b') -> true
17
+ /// differs('a', undefined) -> true
18
+ /// differs(undefined, undefined) -> false
19
+ /** Whether what pnpm installed (`current`'s text) is not the lockfile wanted. */ export let differs = (wanted, installed)=>packages(wanted) !== packages(installed);
20
+ //# sourceMappingURL=lockfile.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"lockfile.js","sources":["./lockfile.ts"],"names":[],"mappings":"AAAA,wEAAwE;AACxE,gFAAgF;AAChF,0EAA0E;AAE1E,qDAAqD,GACrD,OAAO,IAAI,SAAS,CAAC,OAAyB,GAAG,KAAK,eAAe,CAAC,CAAA;AAEtE;mCACmC,GACnC,OAAO,IAAI,UAAU,CAAC,OACpB,GAAG,KAAK,6BAA6B,CAAC,CAAA;AAExC;yEACyE,GACzE,OAAO,IAAI,gBAAgB,CAAC,OAC1B,GAAG,KAAK,kCAAkC,CAAC,CAAA;AAE7C,gFAAgF;AAChF,8EAA8E;AAC9E,+BAA+B;AAC/B,IAAI,WAAW,CAAC,OACd,MAAM,MAAM,WAAW,GAAG,CAAC,IAAI,QAAQ,QAAQ,IAAI,WAAW,MAAM;AAEtE,8BAA8B;AAC9B,oDAAoD;AACpD,uDAAuD;AACvD,6BAA6B;AAC7B,mCAAmC;AACnC,0CAA0C;AAC1C,+EAA+E,GAC/E,OAAO,IAAI,UAAU,CAAC,QAAiB,YACrC,SAAS,YAAY,SAAS,WAAU"}
package/lockfile.ts ADDED
@@ -0,0 +1,32 @@
1
+ // Whether a checkout's node_modules was installed from its lockfile. It
2
+ // imports nothing, so the installer's bootstrap (bin/workspace-dependencies.ts)
3
+ // can ask before node_modules exists, when no workspace package resolves.
4
+
5
+ /** The lockfile a checkout at root wants installed. */
6
+ export let wanted = (root: string): string => `${root}/pnpm-lock.yaml`
7
+
8
+ /** pnpm's copy of the lockfile it last installed at root, without the
9
+ * document that pins pnpm itself. */
10
+ export let current = (root: string): string =>
11
+ `${root}/node_modules/.pnpm/lock.yaml`
12
+
13
+ /** The input a completed frozen install used. pnpm's virtual store lock can
14
+ * differ from it when pnpm normalizes or selects entries for this host. */
15
+ export let installedFrom = (root: string): string =>
16
+ `${root}/node_modules/.pnpm/.yak-lock.yaml`
17
+
18
+ // A formatter may have rewrapped the lockfile's flow mappings (`{ a: 1, }` over
19
+ // three lines where pnpm writes `{a: 1}`): its whitespace and trailing commas
20
+ // are not what pnpm installed.
21
+ let packages = (lock?: string) =>
22
+ lock?.split(/^---\n/m).at(-1)?.replace(/\s+/g, '').replaceAll(',}', '}')
23
+
24
+ /// differs('a', 'a') -> false
25
+ /// differs('---\npnpm: 12\n\n---\na', 'a') -> false
26
+ /// differs('a: {\n b: 1,\n}\n', 'a: {b: 1}') -> false
27
+ /// differs('a', 'b') -> true
28
+ /// differs('a', undefined) -> true
29
+ /// differs(undefined, undefined) -> false
30
+ /** Whether what pnpm installed (`current`'s text) is not the lockfile wanted. */
31
+ export let differs = (wanted?: string, installed?: string): boolean =>
32
+ packages(wanted) !== packages(installed)
package/machines.js ADDED
@@ -0,0 +1,33 @@
1
+ import * as system from "@yaks/process/system";
2
+ import { line } from "@yaks/query";
3
+ import { given, used } from "@yaks/host/config";
4
+ /** Whether a native session works on a task it holds the claim on, and so
5
+ * wants a checkout of its own. Never a fixer (`fixer{bug}`), nor a session an
6
+ * outside CLI runs. */ export let working = async (g, session)=>{
7
+ let [owner] = await g.get([
8
+ session
9
+ ]);
10
+ if (!owner?.session || !owner.native || owner.fixer) return false;
11
+ let held = await g.read(line`.claim.session=${session}&.task&.limit=1&.fields=entity.eid`);
12
+ return held.length > 0;
13
+ };
14
+ export let resolveHome = (host, config)=>async (session)=>{
15
+ if (!await working(host.graph, session)) return;
16
+ let spawn = config.plugins?.find((plug)=>used(plug) == '@yaks/spawn');
17
+ let options = spawn ? given(spawn) : {};
18
+ let worktrees = typeof options.worktrees == 'string' ? options.worktrees : '';
19
+ // A host with no place to cut a worktree leaves the session to its
20
+ // sandboxes, as one holding nothing is.
21
+ if (!(worktrees && host.workspaces)) return;
22
+ let { createWorktree } = await import("@yaks/git/host");
23
+ let tree = await createWorktree(host.graph, typeof options.cwd == 'string' ? options.cwd : system.cwd(), {
24
+ path: `${worktrees}/${session}`,
25
+ branch: `session-${session}`
26
+ });
27
+ let cwd = String(tree.workspace.root);
28
+ return {
29
+ workspace: tree.entity.eid,
30
+ cwd
31
+ };
32
+ };
33
+ //# sourceMappingURL=machines.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"machines.js","sources":["./machines.ts"],"names":[],"mappings":"AAAA,YAAY,wCAA6C;AAQzD,SAAS,IAAI,2BAAgC;AAE7C,SAAS,KAAK,EAAE,IAAI,iCAAsC;AAE1D;;qBAEqB,GACrB,OAAO,IAAI,UAAU,OACnB,GACA;EAEA,IAAI,CAAC,MAAM,GAAG,MAAM,EAAE,GAAG,CAAC;IAAC;GAAQ;EACnC,IAAI,CAAC,OAAO,WAAW,CAAC,MAAM,MAAM,IAAI,MAAM,KAAK,EAAE,OAAO;EAC5D,IAAI,OAAO,MAAM,EAAE,IAAI,CACrB,IAAI,CAAC,eAAe,EAAE,QAAQ,kCAAkC,CAAC;EAEnE,OAAO,KAAK,MAAM,GAAG;AACvB,EAAC;AAED,OAAO,IAAI,cACT,CAAC,MAAY,SACb,OAAO;IACL,IAAI,CAAC,MAAM,QAAQ,KAAK,KAAK,EAAE,UAAU;IACzC,IAAI,QAAQ,OAAO,OAAO,EAAE,KAAK,CAAC,OAAS,KAAK,SAAS;IACzD,IAAI,UAAU,QAAQ,MAAM,SAAS,CAAC;IACtC,IAAI,YAAY,OAAO,QAAQ,SAAS,IAAI,WACxC,QAAQ,SAAS,GACjB;IACJ,mEAAmE;IACnE,wCAAwC;IACxC,IAAI,CAAC,CAAC,aAAa,KAAK,UAAU,GAAG;IACrC,IAAI,EAAE,cAAc,EAAE,GAAG,MAAM,MAAM,CAAC;IACtC,IAAI,OAAO,MAAM,eACf,KAAK,KAAK,EACV,OAAO,QAAQ,GAAG,IAAI,WAAW,QAAQ,GAAG,GAAG,OAAO,GAAG,IACzD;MACE,MAAM,GAAG,UAAU,CAAC,EAAE,SAAS;MAC/B,QAAQ,CAAC,QAAQ,EAAE,SAAS;IAC9B;IAEF,IAAI,MAAM,OAAO,AAAC,KAAK,SAAS,CAAsB,IAAI;IAC1D,OAAO;MAAE,WAAW,KAAK,MAAM,CAAC,GAAG;MAAE;IAAI;EAC3C,EAAC"}
package/machines.ts ADDED
@@ -0,0 +1,51 @@
1
+ import * as system from '@yaks/process/system'
2
+ // Host preparation of the checkout a native session does a project's work in:
3
+ // that of a session holding a task (one started on a person's comment,
4
+ // @yaks/session `starting`, or a lander, @yaks/harness/isolated), which gets
5
+ // what a spawned run has, its own worktree cut from the checkout @yaks/spawn's
6
+ // config names. A fixer works in a sandbox of its own, never a checkout of the
7
+ // host's; a session holding nothing is not the host's to place either.
8
+ import type { Graph } from 'jsr:@yaks/graph@0.2.36'
9
+ import { line } from '@yaks/query'
10
+ import type { Config, Host } from 'jsr:@yaks/host@0.2.36'
11
+ import { given, used } from '@yaks/host/config'
12
+
13
+ /** Whether a native session works on a task it holds the claim on, and so
14
+ * wants a checkout of its own. Never a fixer (`fixer{bug}`), nor a session an
15
+ * outside CLI runs. */
16
+ export let working = async (
17
+ g: Pick<Graph, 'get' | 'read'>,
18
+ session: string,
19
+ ): Promise<boolean> => {
20
+ let [owner] = await g.get([session])
21
+ if (!owner?.session || !owner.native || owner.fixer) return false
22
+ let held = await g.read(
23
+ line`.claim.session=${session}&.task&.limit=1&.fields=entity.eid`,
24
+ )
25
+ return held.length > 0
26
+ }
27
+
28
+ export let resolveHome =
29
+ (host: Host, config: Config): NonNullable<Host['resolveHome']> =>
30
+ async (session) => {
31
+ if (!await working(host.graph, session)) return
32
+ let spawn = config.plugins?.find((plug) => used(plug) == '@yaks/spawn')
33
+ let options = spawn ? given(spawn) : {}
34
+ let worktrees = typeof options.worktrees == 'string'
35
+ ? options.worktrees
36
+ : ''
37
+ // A host with no place to cut a worktree leaves the session to its
38
+ // sandboxes, as one holding nothing is.
39
+ if (!(worktrees && host.workspaces)) return
40
+ let { createWorktree } = await import('@yaks/git/host')
41
+ let tree = await createWorktree(
42
+ host.graph,
43
+ typeof options.cwd == 'string' ? options.cwd : system.cwd(),
44
+ {
45
+ path: `${worktrees}/${session}`,
46
+ branch: `session-${session}`,
47
+ },
48
+ )
49
+ let cwd = String((tree.workspace as { root: string }).root)
50
+ return { workspace: tree.entity.eid, cwd }
51
+ }