@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/args.ts ADDED
@@ -0,0 +1,494 @@
1
+ // The command line, parsed into a tool's arguments. The tool's own input
2
+ // schema is the only grammar there is: `name=value` and `--name value` name a
3
+ // property, and the type that property declares decides whether the argument
4
+ // stays a string, is parsed as JSON, or becomes a number.
5
+ //
6
+ // Three forms expand a value before its type is ever consulted, because a body
7
+ // is rarely something a person types out: `@path` is that file's text, `-` and
8
+ // `@-` are stdin, and anything else is the argument itself. That is what makes
9
+ //
10
+ // yak app_files --app recipes --path index.html --content @index.html
11
+ //
12
+ // the same command whether the page is two lines or two hundred.
13
+ //
14
+ // Rejecting a name the schema does not declare is deliberate: the cached
15
+ // schema is kept fresh (store.ts), so an undeclared `--nmae` is a typo worth
16
+ // an error message here rather than a rejection one round trip away.
17
+
18
+ import { toolCheck, validateToolInput } from '@yaks/vocab/tools'
19
+ import { CallError } from '@yaks/tools/errors'
20
+ import { fileArgs, fileSchema } from './files.js'
21
+ import { commandOf, type Prop, type Schema, typeOf } from './tool.js'
22
+
23
+ /** As much of a tool as a command line reads: what it is called, the schema
24
+ * its arguments must satisfy, and how they are written on a command line. A
25
+ * tool an MCP server listed (tool.ts `Listed`) and one this process runs
26
+ * (@yaks/graph `Tool`) both carry this much. */
27
+ export type Grammar = {
28
+ name?: string
29
+ noun?: string
30
+ verb?: string
31
+ inputSchema?: Schema | Record<string, unknown>
32
+ positional?: readonly string[]
33
+ /** Words retained verbatim for another schema to parse. */
34
+ forward?: string
35
+ }
36
+
37
+ /** An app's vocabulary declaration, in the same grammar as package tools.
38
+ * Positionals and short flags come only from its declaration. */
39
+ export let appGrammar = (
40
+ name: string,
41
+ tool: {
42
+ input?: Record<string, Prop>
43
+ required?: string[]
44
+ positional?: Grammar['positional']
45
+ },
46
+ ): Grammar => ({
47
+ name,
48
+ inputSchema: {
49
+ type: 'object',
50
+ properties: tool.input ?? {},
51
+ required: tool.required ?? [],
52
+ additionalProperties: false,
53
+ },
54
+ positional: tool.positional,
55
+ })
56
+
57
+ /** The command line was wrong — nothing ran, and the exit code is 2. The
58
+ * caller's own mistake, so a refusal (@yaks/tools `CallError`), never a
59
+ * defect to report. */
60
+ export class Usage extends CallError {
61
+ constructor(message: string) {
62
+ super('usage', message)
63
+ }
64
+ }
65
+
66
+ /** Where an expanded value is read from. A test passes two functions and
67
+ * touches no disk. */
68
+ export type Reads = {
69
+ file: (path: string) => string | Promise<string>
70
+ stdin: () => string | Promise<string>
71
+ /** The command’s working directory, for tools that accept `cwd`. */
72
+ cwd?: () => string
73
+ }
74
+
75
+ /** A parsed command line: options in the order they were given (a bare flag
76
+ * is `true`), and the bare words that named no option. */
77
+ export type Said = {
78
+ opts: [string, string | true][]
79
+ words: string[]
80
+ }
81
+
82
+ /**
83
+ * Split a command line into options and bare words. A `--name` whose next word
84
+ * is not itself an option takes that word as its value; otherwise it is a
85
+ * flag. `--name=value` always takes the value, which is the only way to pass a
86
+ * value that itself starts with `--`.
87
+ *
88
+ * ```ts
89
+ * saidIn(['--q', '.recipe', '--json'])
90
+ * // { opts: [['q', '.recipe'], ['json', true]], words: [] }
91
+ * ```
92
+ */
93
+ export let saidIn = (argv: string[]): Said => {
94
+ let opts: [string, string | true][] = []
95
+ let words: string[] = []
96
+ for (let i = 0; i < argv.length; i++) {
97
+ let a = argv[i]
98
+ if (!a.startsWith('--')) {
99
+ words.push(a)
100
+ continue
101
+ }
102
+ let eq = a.indexOf('=')
103
+ if (eq > 2) {
104
+ opts.push([a.slice(2, eq), a.slice(eq + 1)])
105
+ continue
106
+ }
107
+ let next = argv[i + 1]
108
+ if (next != undefined && !next.startsWith('--')) {
109
+ opts.push([a.slice(2), next]), i++
110
+ } else opts.push([a.slice(2), true])
111
+ }
112
+ return { opts, words }
113
+ }
114
+
115
+ /** `@path` reads that file, `-` and `@-` read stdin, anything else is used as
116
+ * given. */
117
+ export let inflate = async (word: string, reads?: Reads): Promise<string> => {
118
+ if (!reads) return word
119
+ if (word == '-' || word == '@-') return await reads.stdin()
120
+ return word.startsWith('@') ? await reads.file(word.slice(1)) : word
121
+ }
122
+
123
+ let parsed = (name: string, raw: string, want: string): unknown => {
124
+ try {
125
+ return JSON.parse(raw)
126
+ } catch {
127
+ throw new Usage(`--${name} wants ${want}, and this is not JSON: ${raw}`)
128
+ }
129
+ }
130
+
131
+ /** One expanded argument, converted to the type its property declares. A
132
+ * string stays a string — JSON-looking or not — so a title that reads like a
133
+ * number is still a title. */
134
+ export let valueOf = (name: string, raw: string, p?: Prop): unknown => {
135
+ let want = typeOf(p)
136
+ if (want == 'boolean') {
137
+ if (raw == 'true' || raw == '1') return true
138
+ if (raw == 'false' || raw == '0') return false
139
+ throw new Usage(`--${name} wants true or false, got ${raw}`)
140
+ }
141
+ if (want == 'number' || want == 'integer') {
142
+ let n = Number(raw)
143
+ if (raw.trim() == '' || Number.isNaN(n)) {
144
+ throw new Usage(`--${name} wants a number, got ${raw}`)
145
+ }
146
+ return n
147
+ }
148
+ if (want == 'object') {
149
+ let v = parsed(name, raw, 'an object')
150
+ if (!v || typeof v != 'object' || Array.isArray(v)) {
151
+ throw new Usage(`--${name} wants an object, got ${raw}`)
152
+ }
153
+ return v
154
+ }
155
+ if (want == 'array') {
156
+ // A whole array as JSON, or one item — repeat the option for more
157
+ // (`--filters .a --filters .b`), which is how a list is typed without
158
+ // getting brackets past a shell.
159
+ let v = raw.trimStart().startsWith('[')
160
+ ? parsed(name, raw, 'an array')
161
+ : null
162
+ if (Array.isArray(v)) return v
163
+ return [valueOf(name, raw, p?.items)]
164
+ }
165
+ return raw
166
+ }
167
+
168
+ let listed = (names: string[]): string =>
169
+ names.length ? names.map((n) => `--${n}`).join(', ') : '(no arguments)'
170
+
171
+ let restOf = (tool: Grammar): string | undefined => {
172
+ let last = tool.positional?.at(-1)
173
+ return last?.endsWith('...') ? last.slice(0, -3) : undefined
174
+ }
175
+
176
+ /** Nullable fields the CLI can clear. A declared clear argument keeps its own
177
+ * meaning; the CLI adds no option that would hide it. */
178
+ export let clearable = (tool: Grammar): string[] => {
179
+ let props = ((tool.inputSchema ?? {}) as Schema).properties ?? {}
180
+ return Object.hasOwn(props, 'clear')
181
+ ? []
182
+ : Object.keys(props).filter((name) =>
183
+ !toolCheck(lone(props, name))({ [name]: null }).length
184
+ )
185
+ }
186
+
187
+ /**
188
+ * The arguments a tool was given, parsed through its own input schema — the
189
+ * one grammar there is. The bare words fill `positional` in order; a final
190
+ * name suffixed `...` takes the remaining words; `name=value`, `--name value`,
191
+ * `--name=value` and a declared short `-n` name a property, a boolean one is a
192
+ * flag, a repeated one builds its list, and `--` ends the options. Every value
193
+ * expands (`@path`, `-`) before its type is consulted, and the whole object is
194
+ * then validated against the schema, which is also what fills in its defaults.
195
+ *
196
+ * Throws {@link Usage} — exit code 2 — for anything the command line got
197
+ * wrong.
198
+ */
199
+ export let argsFor = async (
200
+ tool: Grammar,
201
+ argv: readonly string[],
202
+ reads?: Reads,
203
+ ): Promise<Record<string, unknown>> => {
204
+ let props = ((tool.inputSchema ?? {}) as Schema).properties ?? {}
205
+ let rest = restOf(tool)
206
+ let forward = tool.forward
207
+ let grammar = reads && tool.inputSchema
208
+ ? { ...tool, inputSchema: fileSchema(tool.inputSchema) }
209
+ : tool
210
+ let { pairs, spare } = scanned(grammar, argv)
211
+ let out: Record<string, unknown> = {}
212
+ for (let [name, raw] of pairs) {
213
+ let value = raw === true || raw === null ? raw : valueOf(
214
+ name,
215
+ await inflate(raw, reads),
216
+ name == '_files' ? { type: 'boolean' } : props[name],
217
+ )
218
+ let had = out[name]
219
+ out[name] = Array.isArray(had) && Array.isArray(value)
220
+ ? [...had, ...value]
221
+ : value
222
+ }
223
+
224
+ if (props.cwd && out.cwd === undefined && reads?.cwd) {
225
+ out.cwd = reads.cwd()
226
+ }
227
+
228
+ // Forwarded words keep their spelling until the receiving schema parses
229
+ // them. In particular, a file value must expand exactly once, at that door.
230
+ if (forward) out[forward] = spare
231
+ else if (rest && spare.length) {
232
+ let had = out[rest]
233
+ let values = await Promise.all(spare.map((w) => inflate(w, reads)))
234
+ out[rest] = typeOf(props[rest]) == 'array'
235
+ ? [
236
+ ...Array.isArray(had) ? had : [],
237
+ ...values.flatMap((v) => valueOf(rest, v, props[rest])),
238
+ ]
239
+ : [had, ...values].filter((w) => w != undefined).join(' ')
240
+ }
241
+
242
+ if (reads && '_files' in out) {
243
+ // Top-level values already expanded before parsing. Only strings inside
244
+ // parsed objects and arrays still name files.
245
+ let { _files, ...input } = out
246
+ let nested = Object.fromEntries(
247
+ Object.entries(input).filter(([, value]) => typeof value != 'string'),
248
+ )
249
+ out = {
250
+ ...input,
251
+ ...await fileArgs(
252
+ { ...nested, _files },
253
+ tool.inputSchema ?? {},
254
+ reads.file,
255
+ ),
256
+ }
257
+ }
258
+
259
+ if (!tool.inputSchema) {
260
+ if (Object.keys(out).length) {
261
+ throw new Usage(`${commandOf(tool)} takes no arguments`)
262
+ }
263
+ return out
264
+ }
265
+ return validateToolInput(
266
+ { inputSchema: tool.inputSchema as Record<string, unknown> },
267
+ out,
268
+ (message) => new Usage(message),
269
+ )
270
+ }
271
+
272
+ export let commandFor = <T extends Grammar>(
273
+ tools: readonly T[],
274
+ argv: readonly string[],
275
+ ): { verb: T; args: string[] } | undefined => {
276
+ let [word, next] = argv
277
+ if (!word) return undefined
278
+ for (let t of tools) {
279
+ if (t.noun && t.verb) {
280
+ if (
281
+ (t.noun == word && t.verb == next) || (t.verb == word && t.noun == next)
282
+ ) return { verb: t, args: argv.slice(2) }
283
+ // The name MCP gives the pair (`task_update`) is the same tool.
284
+ if (word == `${t.noun}_${t.verb}`) return { verb: t, args: argv.slice(1) }
285
+ } else if (commandOf(t) == word) return { verb: t, args: argv.slice(1) }
286
+ }
287
+ }
288
+
289
+ /** A typed line's words and their replacement ranges. Incomplete quotes are
290
+ * allowed only while completing; parsing asks for a closed line. */
291
+ export let tokensIn = (
292
+ line: string,
293
+ partial = false,
294
+ ): { value: string; from: number; to: number }[] => {
295
+ let words: { value: string; from: number; to: number }[] = []
296
+ let value = '', quote = '', from = -1
297
+ for (let i = 0; i < line.length; i++) {
298
+ let c = line[i]
299
+ if (from < 0 && !/\s/.test(c)) from = i
300
+ if (c == '\\' && i + 1 < line.length) value += line[++i]
301
+ else if (quote) {
302
+ if (c == quote) quote = ''
303
+ else value += c
304
+ } else if (c == '"' || c == "'") quote = c
305
+ else if (/\s/.test(c)) {
306
+ if (from >= 0) words.push({ value, from, to: i })
307
+ value = '', from = -1
308
+ } else value += c
309
+ }
310
+ if (quote && !partial) throw new Usage('Close the quoted argument.')
311
+ if (from >= 0) words.push({ value, from, to: line.length })
312
+ else if (partial) {
313
+ words.push({ value: '', from: line.length, to: line.length })
314
+ }
315
+ return words
316
+ }
317
+
318
+ // One property's schema on its own, made once for each property: a check is
319
+ // compiled once for each schema object (@yaks/vocab `toolCheck`), and a
320
+ // partial walk checks a value at every keystroke.
321
+ let lones = new WeakMap<object, Map<string, Record<string, unknown>>>()
322
+ let lone = (props: Record<string, Prop>, name: string) => {
323
+ let made = lones.get(props) ?? new Map<string, Record<string, unknown>>()
324
+ lones.set(props, made)
325
+ let schema = made.get(name)
326
+ if (!schema) {
327
+ schema = { type: 'object', properties: { [name]: props[name] } }
328
+ made.set(name, schema)
329
+ }
330
+ return schema
331
+ }
332
+
333
+ /** The single argument walk used by parsing and completion. A partial walk
334
+ * reports the property still awaiting a value, without requiring the schema's
335
+ * remaining mandatory properties. */
336
+ export let scanned = (
337
+ tool: Grammar,
338
+ argv: readonly string[],
339
+ partial = false,
340
+ ): {
341
+ pairs: [string, string | true | null][]
342
+ spare: string[]
343
+ given: Set<string>
344
+ literal: boolean
345
+ pending: string | undefined
346
+ awaiting: string | undefined
347
+ } => {
348
+ let props = ((tool.inputSchema ?? {}) as Schema).properties ?? {}
349
+ let clearing = clearable(tool)
350
+ let rest = restOf(tool)
351
+ let forward = tool.forward
352
+ let positional = (tool.positional ?? []).filter((n) => !n.endsWith('...'))
353
+ let shorts = Object.fromEntries(
354
+ Object.entries(props).flatMap(([name, p]) =>
355
+ p.short ? [[p.short, name]] : []
356
+ ),
357
+ )
358
+ let pairs: [string, string | true | null][] = [], spare: string[] = []
359
+ let given = new Set<string>(),
360
+ at = 0,
361
+ literal = false,
362
+ awaiting: string | undefined,
363
+ pending: string | undefined
364
+ let put = (name: string, raw: string | true | null) => {
365
+ if (
366
+ partial && name != rest && raw !== true && raw !== null &&
367
+ !raw.startsWith('@') &&
368
+ raw != '-'
369
+ ) {
370
+ let value = valueOf(name, raw, props[name])
371
+ validateToolInput(
372
+ { inputSchema: lone(props, name) },
373
+ { [name]: value },
374
+ (message) => new Usage(message),
375
+ )
376
+ }
377
+ pairs.push([name, raw])
378
+ given.add(name)
379
+ }
380
+ for (let i = 0; i < argv.length; i++) {
381
+ let word = argv[i]
382
+ if (!literal && word == '--') {
383
+ literal = true
384
+ if (forward) spare.push(word)
385
+ continue
386
+ }
387
+ let eq = word.indexOf('=')
388
+ let flag = eq > 0 ? word.slice(0, eq) : word
389
+ let name = flag.startsWith('--') ? flag.slice(2) : shorts[flag.slice(1)]
390
+ if (!literal && flag == '--clear' && clearing.length) {
391
+ let field = eq > 0 ? word.slice(eq + 1) : argv[i + 1]
392
+ if (field == undefined || field.startsWith('--')) {
393
+ if (!partial || field != undefined) {
394
+ throw new Usage('--clear needs a field')
395
+ }
396
+ awaiting = pending = 'clear'
397
+ } else {
398
+ if (!clearing.includes(field)) {
399
+ throw new Usage(
400
+ `--clear expects ${clearing.join(', ')}, not ${field}`,
401
+ )
402
+ }
403
+ put(field, null)
404
+ if (eq < 0) i++
405
+ }
406
+ continue
407
+ }
408
+ if (!literal && (flag.startsWith('--') || flag.startsWith('-') && name)) {
409
+ let p = forward &&
410
+ (name == forward || positional.includes(name) && given.has(name))
411
+ ? undefined
412
+ : props[name]
413
+ if (!p && forward) {
414
+ spare.push(word)
415
+ continue
416
+ }
417
+ if (!p) {
418
+ throw new Usage(
419
+ `Unknown option: ${flag} — ${commandOf(tool)} takes ${
420
+ listed(Object.keys(props))
421
+ }`,
422
+ )
423
+ }
424
+ if (eq > 0) {
425
+ put(name, word.slice(eq + 1))
426
+ continue
427
+ }
428
+ let next = argv[i + 1]
429
+ if (
430
+ typeOf(p) == 'boolean' &&
431
+ (next == undefined ||
432
+ !['true', 'false', '1', '0', '-'].includes(next) &&
433
+ !next.startsWith('@'))
434
+ ) {
435
+ put(name, true)
436
+ if (partial && next == undefined) awaiting = name
437
+ } else if (next == undefined || next.startsWith('--')) {
438
+ if (!partial || next != undefined) {
439
+ throw new Usage(`${flag} needs a value`)
440
+ }
441
+ awaiting = name
442
+ pending = name
443
+ } else put(name, argv[++i])
444
+ continue
445
+ }
446
+ if (!literal && eq > 0 && Object.hasOwn(props, word.slice(0, eq))) {
447
+ put(word.slice(0, eq), word.slice(eq + 1))
448
+ continue
449
+ }
450
+ while (at < positional.length && given.has(positional[at])) at++
451
+ // `id=T-5` names an option this tool does not have; taken as the task
452
+ // it would run on the wrong thing, or on nothing. `--` passes it as is.
453
+ if (!literal && at < positional.length && /^[a-z_]\w*=/i.test(word)) {
454
+ throw new Usage(
455
+ `Unknown option: ${word.slice(0, eq)} — ${commandOf(tool)} takes ${
456
+ listed(Object.keys(props))
457
+ }`,
458
+ )
459
+ }
460
+ if (at < positional.length) put(positional[at++], word)
461
+ else if (rest && !given.has(rest)) put(rest, word)
462
+ else if (rest || forward) spare.push(word)
463
+ else {throw new Usage(
464
+ `${commandOf(tool)} takes ${listed(Object.keys(props))}, not ${word}`,
465
+ )}
466
+ }
467
+ if (partial && rest && given.has(rest)) {
468
+ let raw = pairs.filter(([name]) => name == rest).at(-1)?.[1]
469
+ let words = [raw, ...spare].filter((w): w is string => typeof w == 'string')
470
+ if (!words.some((w) => w.startsWith('@') || w == '-')) {
471
+ let prop = props[rest]
472
+ let value = typeOf(prop) == 'array'
473
+ ? words.flatMap((w) => valueOf(rest, w, prop))
474
+ : words.join(' ')
475
+ validateToolInput(
476
+ { inputSchema: lone(props, rest) },
477
+ { [rest]: value },
478
+ (message) => new Usage(message),
479
+ )
480
+ }
481
+ }
482
+ while (at < positional.length && given.has(positional[at])) at++
483
+ return {
484
+ pairs,
485
+ spare,
486
+ given,
487
+ literal,
488
+ pending,
489
+ awaiting: awaiting ?? positional[at] ??
490
+ (rest && props[rest]?.type != undefined && typeOf(props[rest]) == 'string'
491
+ ? rest
492
+ : undefined),
493
+ }
494
+ }
package/code.js ADDED
@@ -0,0 +1,209 @@
1
+ import { fault } from "@yaks/api/refuse";
2
+ import * as disk from "@yaks/file/io";
3
+ import { watchReads } from "@yaks/file/io";
4
+ import { watchImports } from "@yaks/fp/imports";
5
+ import { modules } from "@yaks/process/modules";
6
+ import * as system from "@yaks/process/system";
7
+ import { createHash } from 'node:crypto';
8
+ import { fileURLToPath } from 'node:url';
9
+ import { runtimeTree } from "./runtime.js";
10
+ /** The entry every `yak` process starts from, in its tree. */ export let ENTRY = 'packages/cli/yak.ts';
11
+ // What every module shares, beside the configs over it.
12
+ let SHARED = [
13
+ 'deno.json',
14
+ 'deno.lock',
15
+ 'package.json',
16
+ 'pnpm-lock.yaml'
17
+ ];
18
+ /// codeFile('/run/user/1000/yak-web-1.ready') -> '/run/user/1000/yak-web-1.code'
19
+ /** Where the process whose ready file is `ready` keeps its code record. */ export let codeFile = (ready)=>ready.replace(/\.ready$/, '') + '.code';
20
+ let sum = (bytes)=>createHash('sha256').update(bytes).digest('hex');
21
+ let digest = (path)=>disk.readFile(path).then(sum, ()=>undefined);
22
+ /// inside('/c/0', 'file:///c/0/packages/a.ts') -> 'packages/a.ts'
23
+ /// inside('/c/0', '/c/0/packages/') -> 'packages'
24
+ /// inside('/c/0', '/c/0/node_modules/x/a.js') -> undefined
25
+ /// inside('/c/0', '/c/01/a.ts') -> undefined
26
+ /** A path in the tree at `root`, outside its `node_modules`, which its lock
27
+ * speaks for. */ export let inside = (root, at)=>{
28
+ let path = at instanceof URL || at.startsWith('file:') ? fileURLToPath(at) : disk.resolve(at);
29
+ if (!path.startsWith(`${root}/`)) return;
30
+ let rel = path.slice(root.length + 1).replace(/\/$/, '');
31
+ return /(^|\/)node_modules(\/|$)/.test(rel) || !rel ? undefined : rel;
32
+ };
33
+ // The files in the tree at `root` that the module graph of `roots` (paths
34
+ // in it) reaches, or undefined when deno can't say.
35
+ let reach = async (root, roots)=>{
36
+ let graph = await modules(roots.map((p)=>`file://${root}/${p}`), root);
37
+ if (!graph) return;
38
+ let files = new Set();
39
+ for (let m of graph.modules){
40
+ let rel = m.local ? inside(root, m.local) : undefined;
41
+ if (rel) files.add(rel);
42
+ }
43
+ return files;
44
+ };
45
+ /** Keep what this process runs in `file`, if it runs from a pinned tree,
46
+ * from now until `stop` removes it; `now` is what it holds. The record is
47
+ * rewritten, whole, within a second of learning more, and its graph
48
+ * resolved once no import has been learned for `quiet` milliseconds. */ export let record = (file, config, tree = runtimeTree(), quiet = 10_000)=>{
49
+ if (!tree) return {
50
+ now: ()=>undefined,
51
+ stop: async ()=>{}
52
+ };
53
+ let imports = new Set(), reads = new Set();
54
+ let graphed = new Set(), reached = new Set();
55
+ let said = config ? {
56
+ path: disk.resolve(config),
57
+ sum: sum(disk.readFileSync(config))
58
+ } : undefined;
59
+ let now = ()=>({
60
+ root: tree.root,
61
+ tree: tree.id,
62
+ imports: [
63
+ ...imports
64
+ ].sort(),
65
+ reads: [
66
+ ...reads
67
+ ].sort(),
68
+ ...said ? {
69
+ config: said
70
+ } : {},
71
+ ...graphed.size ? {
72
+ graph: {
73
+ roots: [
74
+ ...graphed
75
+ ].sort(),
76
+ files: [
77
+ ...reached
78
+ ].sort()
79
+ }
80
+ } : {}
81
+ });
82
+ let pending;
83
+ let settling;
84
+ let resolving = false;
85
+ let written = Promise.resolve();
86
+ let stopped = false;
87
+ let write = ()=>{
88
+ pending = undefined;
89
+ written = written.then(async ()=>{
90
+ if (stopped) return;
91
+ let next = `${file}.${crypto.randomUUID()}`;
92
+ await disk.writeTextFile(next, JSON.stringify(now()));
93
+ await disk.rename(next, file);
94
+ }).catch((error)=>fault(error, `writing ${file}`));
95
+ };
96
+ let later = ()=>{
97
+ if (pending || stopped) return;
98
+ pending = setTimeout(write, 1000);
99
+ system.unrefTimer(pending);
100
+ };
101
+ // One resolution at a time, of the roots not yet graphed; roots learned
102
+ // meanwhile settle again after it.
103
+ let graph = async ()=>{
104
+ settling = undefined;
105
+ let roots = [
106
+ ENTRY,
107
+ ...imports
108
+ ].filter((p)=>!graphed.has(p));
109
+ if (stopped || resolving || !roots.length) return;
110
+ resolving = true;
111
+ try {
112
+ let files = await reach(tree.root, roots);
113
+ if (!files || stopped) return;
114
+ for (let p of roots)graphed.add(p);
115
+ for (let f of files)reached.add(f);
116
+ later();
117
+ } catch (error) {
118
+ fault(error, `resolving what ${file} runs`);
119
+ } finally{
120
+ resolving = false;
121
+ }
122
+ if (!settling && [
123
+ ENTRY,
124
+ ...imports
125
+ ].some((p)=>!graphed.has(p))) settle();
126
+ };
127
+ let settle = ()=>{
128
+ if (stopped) return;
129
+ clearTimeout(settling);
130
+ settling = setTimeout(graph, quiet);
131
+ system.unrefTimer(settling);
132
+ };
133
+ let learn = (into, at)=>{
134
+ let rel = inside(tree.root, at);
135
+ if (!rel || into.has(rel)) return;
136
+ into.add(rel);
137
+ if (into == imports) settle();
138
+ later();
139
+ };
140
+ let offImports = watchImports((specifier)=>{
141
+ if (specifier.startsWith('file:')) learn(imports, specifier);
142
+ });
143
+ let offReads = watchReads((path)=>learn(reads, path));
144
+ write();
145
+ settle();
146
+ return {
147
+ now,
148
+ stop: async ()=>{
149
+ stopped = true;
150
+ offImports();
151
+ offReads();
152
+ clearTimeout(pending);
153
+ clearTimeout(settling);
154
+ await written;
155
+ await disk.remove(file).catch(()=>{});
156
+ }
157
+ };
158
+ };
159
+ // A file's bytes, a directory's listing, or nothing.
160
+ let held = async (path)=>{
161
+ let info = await disk.stat(path).catch(()=>undefined);
162
+ if (!info) return;
163
+ if (!info.isDirectory) return digest(path);
164
+ let names = [];
165
+ for await (let entry of disk.readDir(path))names.push(entry.name);
166
+ return names.sort().join('\n');
167
+ };
168
+ /** Why the process `code` describes would run differently from one started
169
+ * from the tree `tree`, or undefined when it runs the same: the config, or
170
+ * the first file, that differs. Only the roots its record's graph doesn't
171
+ * cover are resolved here. */ export let stale = async (code, tree)=>{
172
+ if (code.config && await digest(code.config.path) != code.config.sum) {
173
+ return `${code.config.path} differs`;
174
+ }
175
+ if (code.tree == tree.id) return;
176
+ let covered = new Set(code.graph?.roots);
177
+ let rest = [
178
+ ENTRY,
179
+ ...code.imports
180
+ ].filter((p)=>!covered.has(p));
181
+ if (!await disk.stat(code.root).then(()=>true, ()=>false)) {
182
+ return `${code.root} is gone`;
183
+ }
184
+ let reached = rest.length ? await reach(code.root, rest) : new Set();
185
+ if (!reached) return `deno can't say what ${code.root} loads`;
186
+ let files = new Set([
187
+ ...SHARED,
188
+ ...code.reads
189
+ ]);
190
+ for (let rel of [
191
+ ...code.graph?.files ?? [],
192
+ ...reached
193
+ ]){
194
+ files.add(rel);
195
+ for(let dir = rel; dir.includes('/');){
196
+ dir = dir.slice(0, dir.lastIndexOf('/'));
197
+ files.add(`${dir}/deno.json`);
198
+ files.add(`${dir}/package.json`);
199
+ }
200
+ }
201
+ // Every file at once, the first that differs in order reported.
202
+ let sorted = [
203
+ ...files
204
+ ].sort();
205
+ let same = await Promise.all(sorted.map(async (rel)=>await held(`${code.root}/${rel}`) == await held(`${tree.root}/${rel}`)));
206
+ let first = same.indexOf(false);
207
+ if (first >= 0) return `${sorted[first]} differs`;
208
+ };
209
+ //# sourceMappingURL=code.js.map