@skillcdn/console 0.5.0 → 0.5.2

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 (490) hide show
  1. package/README.md +87 -12
  2. package/SKILLCDN.md +3 -3
  3. package/dist/agent-page.d.ts.map +1 -1
  4. package/dist/agent-page.js +7 -6
  5. package/dist/agent-page.js.map +1 -1
  6. package/dist/api.d.ts +9 -7
  7. package/dist/api.d.ts.map +1 -1
  8. package/dist/api.js +8 -6
  9. package/dist/api.js.map +1 -1
  10. package/dist/charts.d.ts +103 -0
  11. package/dist/charts.d.ts.map +1 -0
  12. package/dist/charts.js +182 -0
  13. package/dist/charts.js.map +1 -0
  14. package/dist/cli/cli.d.ts +58 -2
  15. package/dist/cli/cli.d.ts.map +1 -1
  16. package/dist/cli/cli.js +1742 -472
  17. package/dist/cli/cli.js.map +1 -1
  18. package/dist/cli/command-words.d.ts +20 -0
  19. package/dist/cli/command-words.d.ts.map +1 -0
  20. package/dist/cli/command-words.js +51 -0
  21. package/dist/cli/command-words.js.map +1 -0
  22. package/dist/cli/credentials.d.ts +54 -5
  23. package/dist/cli/credentials.d.ts.map +1 -1
  24. package/dist/cli/credentials.js +126 -20
  25. package/dist/cli/credentials.js.map +1 -1
  26. package/dist/cli/directory.d.ts +19 -4
  27. package/dist/cli/directory.d.ts.map +1 -1
  28. package/dist/cli/directory.js +16 -8
  29. package/dist/cli/directory.js.map +1 -1
  30. package/dist/cli/format.d.ts +70 -9
  31. package/dist/cli/format.d.ts.map +1 -1
  32. package/dist/cli/format.js +267 -40
  33. package/dist/cli/format.js.map +1 -1
  34. package/dist/cli/help.d.ts +13 -4
  35. package/dist/cli/help.d.ts.map +1 -1
  36. package/dist/cli/help.js +101 -58
  37. package/dist/cli/help.js.map +1 -1
  38. package/dist/cli/machine-check.d.ts +36 -0
  39. package/dist/cli/machine-check.d.ts.map +1 -0
  40. package/dist/cli/machine-check.js +151 -0
  41. package/dist/cli/machine-check.js.map +1 -0
  42. package/dist/cli/main.js +76 -2
  43. package/dist/cli/main.js.map +1 -1
  44. package/dist/cli/pack.d.ts +69 -60
  45. package/dist/cli/pack.d.ts.map +1 -1
  46. package/dist/cli/pack.js +241 -270
  47. package/dist/cli/pack.js.map +1 -1
  48. package/dist/cli/plugin-check.d.ts +42 -0
  49. package/dist/cli/plugin-check.d.ts.map +1 -1
  50. package/dist/cli/plugin-check.js +221 -36
  51. package/dist/cli/plugin-check.js.map +1 -1
  52. package/dist/cli/plugin-cli.d.ts +6 -1
  53. package/dist/cli/plugin-cli.d.ts.map +1 -1
  54. package/dist/cli/plugin-cli.js +21 -4
  55. package/dist/cli/plugin-cli.js.map +1 -1
  56. package/dist/cli/plugin-main.js +1 -0
  57. package/dist/cli/plugin-main.js.map +1 -1
  58. package/dist/cli/runner-host.d.ts +7 -0
  59. package/dist/cli/runner-host.d.ts.map +1 -1
  60. package/dist/cli/runner-host.js +2 -0
  61. package/dist/cli/runner-host.js.map +1 -1
  62. package/dist/cli/secret-notes.d.ts +8 -0
  63. package/dist/cli/secret-notes.d.ts.map +1 -0
  64. package/dist/cli/secret-notes.js +48 -0
  65. package/dist/cli/secret-notes.js.map +1 -0
  66. package/dist/cli/serve.d.ts +33 -1
  67. package/dist/cli/serve.d.ts.map +1 -1
  68. package/dist/cli/serve.js +252 -3
  69. package/dist/cli/serve.js.map +1 -1
  70. package/dist/client.d.ts +54 -9
  71. package/dist/client.d.ts.map +1 -1
  72. package/dist/client.js +77 -80
  73. package/dist/client.js.map +1 -1
  74. package/dist/components/agent-page.d.ts +164 -8
  75. package/dist/components/agent-page.d.ts.map +1 -1
  76. package/dist/components/agent-page.js +588 -151
  77. package/dist/components/agent-page.js.map +1 -1
  78. package/dist/components/agents.d.ts.map +1 -1
  79. package/dist/components/agents.js +1 -1
  80. package/dist/components/agents.js.map +1 -1
  81. package/dist/components/board.d.ts.map +1 -1
  82. package/dist/components/board.js +3 -2
  83. package/dist/components/board.js.map +1 -1
  84. package/dist/components/categories.js +1 -1
  85. package/dist/components/categories.js.map +1 -1
  86. package/dist/components/charts.d.ts +157 -0
  87. package/dist/components/charts.d.ts.map +1 -0
  88. package/dist/components/charts.js +182 -0
  89. package/dist/components/charts.js.map +1 -0
  90. package/dist/components/decision-list.d.ts.map +1 -1
  91. package/dist/components/decision-list.js +1 -1
  92. package/dist/components/decision-list.js.map +1 -1
  93. package/dist/components/desk-records.d.ts +102 -0
  94. package/dist/components/desk-records.d.ts.map +1 -0
  95. package/dist/components/desk-records.js +221 -0
  96. package/dist/components/desk-records.js.map +1 -0
  97. package/dist/components/desk.d.ts +85 -0
  98. package/dist/components/desk.d.ts.map +1 -0
  99. package/dist/components/desk.js +135 -0
  100. package/dist/components/desk.js.map +1 -0
  101. package/dist/components/event-feed.d.ts.map +1 -1
  102. package/dist/components/event-feed.js +7 -3
  103. package/dist/components/event-feed.js.map +1 -1
  104. package/dist/components/goals.d.ts +2 -0
  105. package/dist/components/goals.d.ts.map +1 -1
  106. package/dist/components/goals.js +1 -1
  107. package/dist/components/goals.js.map +1 -1
  108. package/dist/components/home.d.ts.map +1 -1
  109. package/dist/components/home.js +14 -6
  110. package/dist/components/home.js.map +1 -1
  111. package/dist/components/icon.d.ts +31 -0
  112. package/dist/components/icon.d.ts.map +1 -0
  113. package/dist/components/icon.js +169 -0
  114. package/dist/components/icon.js.map +1 -0
  115. package/dist/components/markdown.d.ts +6 -0
  116. package/dist/components/markdown.d.ts.map +1 -1
  117. package/dist/components/markdown.js +10 -2
  118. package/dist/components/markdown.js.map +1 -1
  119. package/dist/components/people.js +1 -1
  120. package/dist/components/people.js.map +1 -1
  121. package/dist/components/plugin-frame.d.ts.map +1 -1
  122. package/dist/components/plugin-frame.js +7 -0
  123. package/dist/components/plugin-frame.js.map +1 -1
  124. package/dist/components/plugin-settings.d.ts.map +1 -1
  125. package/dist/components/plugin-settings.js +54 -3
  126. package/dist/components/plugin-settings.js.map +1 -1
  127. package/dist/components/projects.d.ts +17 -4
  128. package/dist/components/projects.d.ts.map +1 -1
  129. package/dist/components/projects.js +51 -12
  130. package/dist/components/projects.js.map +1 -1
  131. package/dist/components/rules.d.ts +8 -10
  132. package/dist/components/rules.d.ts.map +1 -1
  133. package/dist/components/rules.js +35 -13
  134. package/dist/components/rules.js.map +1 -1
  135. package/dist/components/sessions.d.ts.map +1 -1
  136. package/dist/components/sessions.js +3 -2
  137. package/dist/components/sessions.js.map +1 -1
  138. package/dist/components/setup.d.ts +9 -3
  139. package/dist/components/setup.d.ts.map +1 -1
  140. package/dist/components/setup.js +12 -6
  141. package/dist/components/setup.js.map +1 -1
  142. package/dist/components/shell.d.ts.map +1 -1
  143. package/dist/components/shell.js +3 -2
  144. package/dist/components/shell.js.map +1 -1
  145. package/dist/components/tokens.js +1 -1
  146. package/dist/components/tokens.js.map +1 -1
  147. package/dist/components/ui.d.ts +5 -2
  148. package/dist/components/ui.d.ts.map +1 -1
  149. package/dist/components/ui.js +10 -7
  150. package/dist/components/ui.js.map +1 -1
  151. package/dist/connect-page.js +1 -1
  152. package/dist/connect-page.js.map +1 -1
  153. package/dist/console.css +1172 -106
  154. package/dist/console.d.ts +5 -0
  155. package/dist/console.d.ts.map +1 -1
  156. package/dist/console.js +52 -39
  157. package/dist/console.js.map +1 -1
  158. package/dist/data.d.ts.map +1 -1
  159. package/dist/data.js +32 -33
  160. package/dist/data.js.map +1 -1
  161. package/dist/desk-page.d.ts +38 -0
  162. package/dist/desk-page.d.ts.map +1 -0
  163. package/dist/desk-page.js +184 -0
  164. package/dist/desk-page.js.map +1 -0
  165. package/dist/desk-records-page.d.ts +18 -0
  166. package/dist/desk-records-page.d.ts.map +1 -0
  167. package/dist/desk-records-page.js +130 -0
  168. package/dist/desk-records-page.js.map +1 -0
  169. package/dist/desk-records.d.ts +247 -0
  170. package/dist/desk-records.d.ts.map +1 -0
  171. package/dist/desk-records.js +543 -0
  172. package/dist/desk-records.js.map +1 -0
  173. package/dist/desk.d.ts +122 -0
  174. package/dist/desk.d.ts.map +1 -0
  175. package/dist/desk.js +211 -0
  176. package/dist/desk.js.map +1 -0
  177. package/dist/feed-stream.d.ts +39 -0
  178. package/dist/feed-stream.d.ts.map +1 -0
  179. package/dist/feed-stream.js +117 -0
  180. package/dist/feed-stream.js.map +1 -0
  181. package/dist/home-tiles.d.ts +19 -3
  182. package/dist/home-tiles.d.ts.map +1 -1
  183. package/dist/home-tiles.js +147 -42
  184. package/dist/home-tiles.js.map +1 -1
  185. package/dist/i18n/en.d.ts +228 -6
  186. package/dist/i18n/en.d.ts.map +1 -1
  187. package/dist/i18n/en.js +309 -9
  188. package/dist/i18n/en.js.map +1 -1
  189. package/dist/i18n/ko.d.ts.map +1 -1
  190. package/dist/i18n/ko.js +366 -85
  191. package/dist/i18n/ko.js.map +1 -1
  192. package/dist/i18n/particles.d.ts +7 -0
  193. package/dist/i18n/particles.d.ts.map +1 -0
  194. package/dist/i18n/particles.js +72 -0
  195. package/dist/i18n/particles.js.map +1 -0
  196. package/dist/icons/glyphs.d.ts +605 -0
  197. package/dist/icons/glyphs.d.ts.map +1 -0
  198. package/dist/icons/glyphs.js +104 -0
  199. package/dist/icons/glyphs.js.map +1 -0
  200. package/dist/icons/index.d.ts +59 -0
  201. package/dist/icons/index.d.ts.map +1 -0
  202. package/dist/icons/index.js +157 -0
  203. package/dist/icons/index.js.map +1 -0
  204. package/dist/index.d.ts +9 -0
  205. package/dist/index.d.ts.map +1 -1
  206. package/dist/index.js +9 -0
  207. package/dist/index.js.map +1 -1
  208. package/dist/limits.d.ts +20 -0
  209. package/dist/limits.d.ts.map +1 -1
  210. package/dist/limits.js +20 -0
  211. package/dist/limits.js.map +1 -1
  212. package/dist/marks.d.ts +9 -0
  213. package/dist/marks.d.ts.map +1 -1
  214. package/dist/marks.js +9 -0
  215. package/dist/marks.js.map +1 -1
  216. package/dist/onboarding.d.ts +6 -0
  217. package/dist/onboarding.d.ts.map +1 -1
  218. package/dist/onboarding.js +5 -5
  219. package/dist/onboarding.js.map +1 -1
  220. package/dist/plugin/context.d.ts +42 -11
  221. package/dist/plugin/context.d.ts.map +1 -1
  222. package/dist/plugin/limits.d.ts +2 -0
  223. package/dist/plugin/limits.d.ts.map +1 -1
  224. package/dist/plugin/limits.js +2 -0
  225. package/dist/plugin/limits.js.map +1 -1
  226. package/dist/plugin/manifest.d.ts +13 -0
  227. package/dist/plugin/manifest.d.ts.map +1 -1
  228. package/dist/plugin/manifest.js +30 -3
  229. package/dist/plugin/manifest.js.map +1 -1
  230. package/dist/plugin/rest-schemas.d.ts +55 -0
  231. package/dist/plugin/rest-schemas.d.ts.map +1 -1
  232. package/dist/plugin/rest-schemas.js +37 -0
  233. package/dist/plugin/rest-schemas.js.map +1 -1
  234. package/dist/plugin/sandbox.d.ts.map +1 -1
  235. package/dist/plugin/sandbox.js +4 -1
  236. package/dist/plugin/sandbox.js.map +1 -1
  237. package/dist/plugin/testing.d.ts +6 -2
  238. package/dist/plugin/testing.d.ts.map +1 -1
  239. package/dist/plugin/testing.js +52 -10
  240. package/dist/plugin/testing.js.map +1 -1
  241. package/dist/plugin/web.d.ts +3 -0
  242. package/dist/plugin/web.d.ts.map +1 -1
  243. package/dist/plugin/web.js +5 -1
  244. package/dist/plugin/web.js.map +1 -1
  245. package/dist/plugin.d.ts +1 -1
  246. package/dist/plugin.d.ts.map +1 -1
  247. package/dist/plugin.js +1 -1
  248. package/dist/plugin.js.map +1 -1
  249. package/dist/records.d.ts +283 -0
  250. package/dist/records.d.ts.map +1 -0
  251. package/dist/records.js +543 -0
  252. package/dist/records.js.map +1 -0
  253. package/dist/routes.d.ts +3 -1
  254. package/dist/routes.d.ts.map +1 -1
  255. package/dist/routes.js +3 -1
  256. package/dist/routes.js.map +1 -1
  257. package/dist/rules.d.ts +30 -11
  258. package/dist/rules.d.ts.map +1 -1
  259. package/dist/rules.js +98 -45
  260. package/dist/rules.js.map +1 -1
  261. package/dist/runner/acp.d.ts +1 -1
  262. package/dist/runner/acp.d.ts.map +1 -1
  263. package/dist/runner/acp.js +32 -21
  264. package/dist/runner/acp.js.map +1 -1
  265. package/dist/runner/awake.d.ts +35 -0
  266. package/dist/runner/awake.d.ts.map +1 -0
  267. package/dist/runner/awake.js +95 -0
  268. package/dist/runner/awake.js.map +1 -0
  269. package/dist/runner/claude.d.ts +1 -1
  270. package/dist/runner/claude.d.ts.map +1 -1
  271. package/dist/runner/claude.js +100 -18
  272. package/dist/runner/claude.js.map +1 -1
  273. package/dist/runner/codex.d.ts +1 -1
  274. package/dist/runner/codex.d.ts.map +1 -1
  275. package/dist/runner/codex.js +20 -17
  276. package/dist/runner/codex.js.map +1 -1
  277. package/dist/runner/config.d.ts +5 -0
  278. package/dist/runner/config.d.ts.map +1 -1
  279. package/dist/runner/config.js +9 -0
  280. package/dist/runner/config.js.map +1 -1
  281. package/dist/runner/desk.d.ts +43 -2
  282. package/dist/runner/desk.d.ts.map +1 -1
  283. package/dist/runner/desk.js +168 -13
  284. package/dist/runner/desk.js.map +1 -1
  285. package/dist/runner/process.d.ts.map +1 -1
  286. package/dist/runner/process.js +11 -4
  287. package/dist/runner/process.js.map +1 -1
  288. package/dist/runner/redact.d.ts +39 -4
  289. package/dist/runner/redact.d.ts.map +1 -1
  290. package/dist/runner/redact.js +81 -5
  291. package/dist/runner/redact.js.map +1 -1
  292. package/dist/runner/runner.d.ts +28 -3
  293. package/dist/runner/runner.d.ts.map +1 -1
  294. package/dist/runner/runner.js +371 -54
  295. package/dist/runner/runner.js.map +1 -1
  296. package/dist/runner/slack.d.ts.map +1 -1
  297. package/dist/runner/slack.js +10 -4
  298. package/dist/runner/slack.js.map +1 -1
  299. package/dist/runner/task-scheduler.d.ts +20 -0
  300. package/dist/runner/task-scheduler.d.ts.map +1 -1
  301. package/dist/runner/task-scheduler.js +34 -4
  302. package/dist/runner/task-scheduler.js.map +1 -1
  303. package/dist/runner/types.d.ts +51 -1
  304. package/dist/runner/types.d.ts.map +1 -1
  305. package/dist/runner/types.js +26 -0
  306. package/dist/runner/types.js.map +1 -1
  307. package/dist/runner.d.ts +6 -6
  308. package/dist/runner.d.ts.map +1 -1
  309. package/dist/runner.js +5 -5
  310. package/dist/runner.js.map +1 -1
  311. package/dist/schemas.d.ts +603 -6
  312. package/dist/schemas.d.ts.map +1 -1
  313. package/dist/schemas.js +156 -20
  314. package/dist/schemas.js.map +1 -1
  315. package/dist/services.d.ts +22 -5
  316. package/dist/services.d.ts.map +1 -1
  317. package/dist/services.js +41 -17
  318. package/dist/services.js.map +1 -1
  319. package/dist/setup-guide.d.ts +17 -4
  320. package/dist/setup-guide.d.ts.map +1 -1
  321. package/dist/setup-guide.js +48 -41
  322. package/dist/setup-guide.js.map +1 -1
  323. package/dist/tokens.d.ts.map +1 -1
  324. package/dist/tokens.js +5 -1
  325. package/dist/tokens.js.map +1 -1
  326. package/dist/vocabulary.d.ts +21 -3
  327. package/dist/vocabulary.d.ts.map +1 -1
  328. package/dist/vocabulary.js +19 -3
  329. package/dist/vocabulary.js.map +1 -1
  330. package/docs/specs/cli.md +73 -44
  331. package/docs/specs/plugins.md +40 -22
  332. package/docs/specs/records.md +113 -0
  333. package/docs/specs/rest.md +30 -21
  334. package/docs/specs/runner.md +46 -22
  335. package/package.json +11 -2
  336. package/skills/building-a-console/SKILL.md +4 -4
  337. package/skills/building-a-plugin/SKILL.md +6 -6
  338. package/skills/deploying-a-console/SKILL.md +4 -4
  339. package/skills/deploying-a-console/references/resources.md +41 -4
  340. package/skills/deploying-a-console/references/running-it-again.md +3 -2
  341. package/skills/keeping-a-desk/SKILL.md +133 -0
  342. package/skills/keeping-a-desk/collections.md +96 -0
  343. package/skills/planning-the-board/SKILL.md +14 -18
  344. package/skills/planning-the-board/references/a-task.md +2 -2
  345. package/skills/planning-the-board/references/project-rules.md +13 -14
  346. package/skills/planning-the-board/references/setting-up.md +15 -13
  347. package/skills/running-an-agent/SKILL.md +47 -56
  348. package/skills/working-the-board/SKILL.md +63 -44
  349. package/skills/working-the-board/references/terms.md +9 -5
  350. package/skills/working-the-board/references/the-pack.md +12 -10
  351. package/skills/working-the-board/references/the-sentence.md +2 -2
  352. package/src/agent-page.tsx +16 -2
  353. package/src/api.ts +109 -3
  354. package/src/charts.ts +250 -0
  355. package/src/cli/cli.ts +2226 -580
  356. package/src/cli/command-words.ts +56 -0
  357. package/src/cli/credentials.ts +181 -20
  358. package/src/cli/directory.ts +28 -10
  359. package/src/cli/format.ts +332 -49
  360. package/src/cli/help.ts +113 -57
  361. package/src/cli/machine-check.ts +223 -0
  362. package/src/cli/main.ts +72 -2
  363. package/src/cli/pack.ts +333 -372
  364. package/src/cli/plugin-check.ts +275 -34
  365. package/src/cli/plugin-cli.ts +28 -4
  366. package/src/cli/plugin-main.ts +1 -0
  367. package/src/cli/runner-host.ts +8 -0
  368. package/src/cli/secret-notes.ts +63 -0
  369. package/src/cli/serve.ts +295 -2
  370. package/src/client.ts +215 -177
  371. package/src/components/agent-page.tsx +1044 -281
  372. package/src/components/agents.tsx +9 -5
  373. package/src/components/board.tsx +3 -15
  374. package/src/components/categories.tsx +2 -2
  375. package/src/components/charts.tsx +680 -0
  376. package/src/components/decision-list.tsx +11 -7
  377. package/src/components/desk-records.tsx +724 -0
  378. package/src/components/desk.tsx +471 -0
  379. package/src/components/event-feed.tsx +12 -3
  380. package/src/components/goals.tsx +33 -25
  381. package/src/components/home.tsx +42 -6
  382. package/src/components/icon.tsx +337 -0
  383. package/src/components/markdown.tsx +22 -2
  384. package/src/components/people.tsx +1 -1
  385. package/src/components/plugin-frame.tsx +7 -0
  386. package/src/components/plugin-settings.tsx +171 -12
  387. package/src/components/projects.tsx +68 -17
  388. package/src/components/rules.tsx +94 -34
  389. package/src/components/sessions.tsx +2 -13
  390. package/src/components/setup.tsx +20 -5
  391. package/src/components/shell.tsx +3 -20
  392. package/src/components/tokens.tsx +1 -1
  393. package/src/components/ui.tsx +16 -8
  394. package/src/connect-page.tsx +1 -1
  395. package/src/console.tsx +104 -62
  396. package/src/data.ts +37 -34
  397. package/src/desk-page.tsx +332 -0
  398. package/src/desk-records-page.tsx +256 -0
  399. package/src/desk-records.ts +808 -0
  400. package/src/desk.ts +329 -0
  401. package/src/feed-stream.ts +144 -0
  402. package/src/home-tiles.ts +170 -46
  403. package/src/i18n/en.ts +323 -11
  404. package/src/i18n/ko.ts +378 -87
  405. package/src/i18n/particles.ts +79 -0
  406. package/src/icons/glyphs.ts +112 -0
  407. package/src/icons/index.ts +195 -0
  408. package/src/index.ts +125 -0
  409. package/src/limits.ts +20 -0
  410. package/src/marks.ts +12 -0
  411. package/src/onboarding.ts +14 -6
  412. package/src/plugin/context.ts +55 -12
  413. package/src/plugin/limits.ts +2 -0
  414. package/src/plugin/manifest.ts +38 -2
  415. package/src/plugin/rest-schemas.ts +41 -0
  416. package/src/plugin/sandbox.ts +4 -1
  417. package/src/plugin/testing.ts +63 -12
  418. package/src/plugin/web.ts +9 -2
  419. package/src/plugin.ts +2 -0
  420. package/src/records.ts +702 -0
  421. package/src/routes.ts +3 -1
  422. package/src/rules.ts +108 -47
  423. package/src/runner/acp.ts +49 -30
  424. package/src/runner/awake.ts +135 -0
  425. package/src/runner/claude.ts +131 -26
  426. package/src/runner/codex.ts +37 -26
  427. package/src/runner/config.ts +9 -0
  428. package/src/runner/desk.ts +200 -15
  429. package/src/runner/process.ts +11 -4
  430. package/src/runner/redact.ts +92 -6
  431. package/src/runner/runner.ts +457 -56
  432. package/src/runner/slack.ts +10 -4
  433. package/src/runner/task-scheduler.ts +36 -4
  434. package/src/runner/types.ts +67 -1
  435. package/src/runner.ts +27 -2
  436. package/src/schemas.ts +177 -18
  437. package/src/services.ts +55 -16
  438. package/src/setup-guide.ts +49 -40
  439. package/src/styles/README.md +16 -5
  440. package/src/styles/base.css +17 -0
  441. package/src/styles/console.css +10 -0
  442. package/src/styles/drawn-by-pages.json +1 -1
  443. package/src/styles/pages/agents.css +103 -1
  444. package/src/styles/pages/board.css +0 -10
  445. package/src/styles/pages/calendar.css +1 -1
  446. package/src/styles/pages/connect.css +0 -10
  447. package/src/styles/pages/decisions.css +3 -1
  448. package/src/styles/pages/desk.css +126 -0
  449. package/src/styles/pages/documents.css +5 -0
  450. package/src/styles/pages/feed.css +5 -2
  451. package/src/styles/pages/home.css +5 -0
  452. package/src/styles/pages/roadmap.css +2 -2
  453. package/src/styles/pages/settings.css +11 -0
  454. package/src/styles/pages/task.css +0 -20
  455. package/src/styles/pages/thread.css +1 -1
  456. package/src/styles/parts/bars.css +80 -0
  457. package/src/styles/parts/calendar.css +1 -1
  458. package/src/styles/parts/callout.css +1 -0
  459. package/src/styles/parts/chart.css +173 -0
  460. package/src/styles/parts/detail.css +22 -0
  461. package/src/styles/parts/empty.css +2 -0
  462. package/src/styles/parts/eyebrow.css +1 -1
  463. package/src/styles/parts/facts.css +1 -1
  464. package/src/styles/parts/figures.css +65 -0
  465. package/src/styles/parts/form.css +2 -1
  466. package/src/styles/parts/icon.css +191 -0
  467. package/src/styles/parts/input.css +14 -4
  468. package/src/styles/parts/legend.css +48 -0
  469. package/src/styles/parts/mark.css +36 -0
  470. package/src/styles/parts/menu.css +1 -7
  471. package/src/styles/parts/page.css +1 -1
  472. package/src/styles/parts/panel.css +10 -0
  473. package/src/styles/parts/person.css +5 -2
  474. package/src/styles/parts/progress.css +5 -2
  475. package/src/styles/parts/rows.css +1 -0
  476. package/src/styles/parts/series.css +32 -0
  477. package/src/styles/parts/settings.css +5 -0
  478. package/src/styles/parts/share.css +25 -0
  479. package/src/styles/parts/spark.css +23 -0
  480. package/src/styles/parts/stat.css +69 -0
  481. package/src/styles/tokens.css +31 -10
  482. package/src/tokens.ts +5 -1
  483. package/src/vocabulary.ts +25 -3
  484. package/template/desk-web/README.md +8 -0
  485. package/template/desk-web/index.html +13 -0
  486. package/template/desk-web/package.json +25 -0
  487. package/template/desk-web/src/main.tsx +24 -0
  488. package/template/desk-web/src/page.tsx +51 -0
  489. package/template/desk-web/tsconfig.json +16 -0
  490. package/template/desk-web/vite.config.ts +15 -0
package/dist/cli/cli.js CHANGED
@@ -1,32 +1,41 @@
1
- import { basename, extname } from "node:path";
1
+ import { basename, extname, isAbsolute } from "node:path";
2
2
  import { parseArgs } from "node:util";
3
3
  import { deflateSync } from "node:zlib";
4
+ import { PackError, ReadMisuse, readNumber, readPack, wroteLine, } from "@skillcdn/cli";
5
+ import { BROWSE_MAX_LIMIT, FIND_MAX_LIMIT, READ_FILE_MAX_LIMIT, } from "@skillcdn/core";
4
6
  import { avatarScanlines, MAX_AVATAR_PIXELS, pngFile } from "../avatar.js";
5
7
  import { ApiError, createClient, } from "../client.js";
6
8
  import { CLIENT_RANGE_HEADER, CONSOLE_AT_LEAST, consoleRange, formatRange, judgeClient, judgeConsole, parseVersion, VERSION_HEADER, formatVersion as versionText, } from "../compat.js";
7
9
  import { normalizeConnectCode } from "../connect.js";
8
10
  import { addDays, dayOf as dayOfDate, firstDayOfWeek, isDay, weekOf } from "../dates.js";
9
- import { DEFAULT_PAGE_LIMIT, LIST_LIMIT, MAX_DECIDERS, MAX_OPTIONS, MAX_RUNNER_LINE_LENGTH, MAX_SIGNALS_PAGE_LIMIT, MIN_OPTIONS, } from "../limits.js";
11
+ import { ICON_NAMES, isIconName } from "../icons/index.js";
12
+ import { DEFAULT_PAGE_LIMIT, EVENTS_PAGE_LIMIT, LIST_LIMIT, MAX_DECIDERS, MAX_OPTIONS, MAX_OWN_WAKE_DAYS, MAX_RUNNER_LINE_LENGTH, MAX_SIGNALS_PAGE_LIMIT, MIN_OPTIONS, OWN_WAKE_KEY, } from "../limits.js";
13
+ import { onboardingTitle } from "../onboarding.js";
10
14
  import { capabilityWords } from "../plugin/capabilities.js";
11
15
  import { PLUGIN_LIST_LIMIT } from "../plugin/limits.js";
16
+ import { checkRecords, RECORDS_DIR, RECORDS_INDEX_FILE } from "../records.js";
17
+ import { agentHref, decisionHref, docHref, myDecisionHref, taskHref } from "../router.js";
12
18
  import { fillRules, RULES_PATH, RULES_TITLE } from "../rules.js";
13
19
  import { DEFAULT_RUNNER_CONFIG, parseRunnerConfig } from "../runner/config.js";
14
- import { deskFiles, deskServicesOf } from "../runner/desk.js";
20
+ import { DESK_FOLDER, deskFiles, deskServicesOf, deskWebTitleOf, personDeskFiles, } from "../runner/desk.js";
15
21
  import { ownRunnerModules } from "../runner/modules.js";
16
- import { createRunner, GIT_TOKEN_SECRET } from "../runner/runner.js";
22
+ import { createRunner, GIT_TOKEN_SECRET, } from "../runner/runner.js";
17
23
  import { hostOfLogin, } from "../schemas.js";
18
24
  import { agentLoginOf, deskRemoteOf } from "../services.js";
19
25
  import { setupGuideOf, setupGuideText, setupSentenceOf } from "../setup-guide.js";
20
26
  import { COLOR_NAMES, CONSOLE_LANGUAGES, GOAL_STATES, PEOPLE_VISIBILITIES, PERSON_ROLES, PROJECT_ROLES, PROJECT_VISIBILITIES, PROVIDER_KEYS, SERVICE_ROLES, TASK_PRIORITIES, TASK_STATES, WEEK_STARTS, } from "../vocabulary.js";
21
27
  import { loadWebRoot, WebRootError } from "../web.js";
22
- import { CredentialsError, EMPTY_CREDENTIALS, loginsAt, resolveLogin, withLogin, withoutLogin, } from "./credentials.js";
23
- import { THE_SENTENCE } from "./directory.js";
24
- import { calledOf, deciderLogins, formatAgent, formatAgentLine, formatAnswer, formatCategoryLine, formatComment, formatDecision, formatDecisionLine, formatDocument, formatDocuments, formatGoal, formatGoalLine, formatInvocation, formatListingLine, formatMemberLine, formatMore, formatOptions, formatPersonLine, formatPersonWork, formatPlugin, formatPluginAsks, formatPluginGrantLine, formatPluginHelp, formatPluginRecord, formatPluginRecords, formatPluginRecordVersions, formatPluginSettingLine, formatPlugins, formatProject, formatProjectLine, formatRules, formatRun, formatRunLine, formatSecretLine, formatSignalLine, formatTask, formatTaskLine, formatTeamLine, formatVersion, formatVersionLine, formatWork, formatWorkspace, localized, moment, setMomentZone, } from "./format.js";
28
+ import { commandLine, commandWord, NO_LINE_TO_RUN } from "./command-words.js";
29
+ import { CredentialsError, EMPTY_CREDENTIALS, fitsFile, keepsNothing, lasts, loginsAt, pendingAt, resolveLogin, withLogin, withoutLogin, withoutPending, withPending, } from "./credentials.js";
30
+ import { DIRECTORY_FILE, THE_SENTENCE, } from "./directory.js";
31
+ import { calledOf, deciderLogins, formatAgent, formatAgentLine, formatAnswer, formatCategoryLine, formatComment, formatDecision, formatDecisionLine, formatDocument, formatDocuments, formatGoal, formatGoalLine, formatInvocation, formatListingLine, formatMemberLine, formatMore, formatOptions, formatOwnWakeLine, formatPersonLine, formatPersonWork, formatPlugin, formatPluginAsks, formatPluginEvents, formatPluginGrantLine, formatPluginHelp, formatPluginRecord, formatPluginRecords, formatPluginRecordVersions, formatPluginSettingLine, formatPlugins, formatProject, formatProjectLine, formatRules, formatRulesChanged, formatRulesLeftOut, formatRun, formatRunLine, formatSecretLine, formatSignalLine, formatTask, formatTaskLine, formatTeamLine, formatVersion, formatVersionLine, formatWork, formatWorkspace, localized, moment, pageLine, rulesMark, setMomentZone, } from "./format.js";
25
32
  import { COMMAND_HELP, helpFor, ownSkillPath, usage } from "./help.js";
26
33
  import { describeInstall, updateCommandFor } from "./install.js";
27
- import { bodyOfFile, bodyOfFolder, bodyOfSkill, csvOfRows, dataRefusal, describeCode, describeRows, formatSkillBrowse, formatSkillFile, formatSkillFind, formatSkillLoad, formatSkills, joinCode, joinFile, joinFolder, joinRows, joinSkill, skillPathIn, summaryOf, textOfCode, } from "./pack.js";
34
+ import { awakeWords, heldAwake, lookAtMachine } from "./machine-check.js";
35
+ import { consolePack, formatSkills, holdsNothing, ORGANIZATION_PACK_LINE, PackRefusal, packWords, refusalWords, skillPathIn, } from "./pack.js";
28
36
  import { workPath } from "./runner-host.js";
29
- import { createServeHandler, DEFAULT_SERVE_PORT } from "./serve.js";
37
+ import { secretNotes } from "./secret-notes.js";
38
+ import { createServeHandler, DEFAULT_SERVE_PORT, loadRecordsRoot, RecordsRootError, } from "./serve.js";
30
39
  // The `console` command (docs/specs/cli.md): the agent's side of the console. A thin client of
31
40
  // the REST API with no logic of its own: every command is one or two requests and the words to
32
41
  // say what came back. It takes what it needs from `CliIo`, so that tests run it whole, against
@@ -39,7 +48,7 @@ export const EXIT = {
39
48
  failed: 1,
40
49
  /** The command was not understood. */
41
50
  usage: 2,
42
- /** The decision still waits for a person. */
51
+ /** What was waited for still waits for a person: a decision's answer, or a connection's approval. */
43
52
  waiting: 3,
44
53
  /** The command and the console do not go together (ADR-0025): stderr says which to update, and how. */
45
54
  incompatible: 4,
@@ -54,6 +63,12 @@ const WAIT_PAUSE_MS = 500;
54
63
  const DEFAULT_ASK_WAIT_SECONDS = 60;
55
64
  /** The longest wait a person may ask for: a day. */
56
65
  const MAX_WAIT_SECONDS = 86_400;
66
+ /**
67
+ * How long `login` waits for the approval of a connection a call before it began, where no
68
+ * terminal shows its words as they are printed (ADR-0129): within the two minutes an agent's
69
+ * host gives a command before it cuts it off.
70
+ */
71
+ const DEFAULT_LOGIN_WAIT_SECONDS = 90;
57
72
  /** The command stops with an exit code and a word on stderr. */
58
73
  class CliExit extends Error {
59
74
  exit;
@@ -104,6 +119,79 @@ const texts = (values, name) => {
104
119
  }
105
120
  return typeof value === "string" ? [value] : [];
106
121
  };
122
+ /**
123
+ * What is said of a project the console does not have, or does not show the member: the key,
124
+ * the console and what named the key, then the two things a person can do about it, each
125
+ * something to ask for or to do. An agent that reads only "not found" guesses at causes; one of
126
+ * these two is always the one. `login` is the member's, where the command knows it. Both are
127
+ * said as what is done and by whom, never as a command to whoever reads: an agent told to do
128
+ * as it saw fit took "bind this directory anew" for its own step, bound the checkout to another
129
+ * project and went on with no task. Which key is right is the repository's agreement's to say,
130
+ * or the person's.
131
+ */
132
+ function unseenProjectWords(url, named, login) {
133
+ const right = "the right one, the key the repository's agreement names or the one the person says";
134
+ const mend = named.source.kind === "directory"
135
+ ? `the directory is bound to ${right}, with console use <key>`
136
+ : named.source.kind === "environment"
137
+ ? `CONSOLE_PROJECT is set to ${right}, or unset`
138
+ : `--project is given ${right}`;
139
+ return [
140
+ `project.not_found: ${url} has no project ${named.key}, or it is not yours to see. The key is named by ${sourceWords(named.source)}.`,
141
+ `Where the project is there and you are not in it, one of its owners lists you: console member add ${login ?? "<your login>"} --project ${named.key}. Where the key is wrong, ${mend}; console projects lists the projects you may work in at this console.`,
142
+ ].join("\n");
143
+ }
144
+ /**
145
+ * The console's refusal of the project a directory or the environment names, with the words
146
+ * above: still the refusal it was, for the code that reads one (a decision is looked for
147
+ * elsewhere when its project is not found), and said in full where the command ends on it.
148
+ */
149
+ class UnseenProject extends ApiError {
150
+ words;
151
+ constructor(refusal, words) {
152
+ super(refusal.status, refusal.code, refusal.message);
153
+ this.name = "UnseenProject";
154
+ this.words = words;
155
+ }
156
+ }
157
+ /**
158
+ * A project's client whose refusals as `project.not_found` carry `words`: every command that
159
+ * works in the directory's project goes through one, so that the refusal names the key, the
160
+ * console and what named it wherever it is met, and no command says it for itself.
161
+ */
162
+ function namingUnseen(project, words) {
163
+ return new Proxy(project, {
164
+ get(target, property, receiver) {
165
+ const member = Reflect.get(target, property, receiver);
166
+ if (typeof member !== "function") {
167
+ return member;
168
+ }
169
+ return (...args) => {
170
+ const result = Reflect.apply(member, target, args);
171
+ return result instanceof Promise
172
+ ? result.catch((error) => {
173
+ throw error instanceof ApiError && error.code === "project.not_found"
174
+ ? new UnseenProject(error, words())
175
+ : error;
176
+ })
177
+ : result;
178
+ };
179
+ },
180
+ });
181
+ }
182
+ /** Where a project's key came from, as `whoami` and its refusal say it. */
183
+ function sourceWords(source) {
184
+ switch (source.kind) {
185
+ case "flag":
186
+ return "--project";
187
+ case "environment":
188
+ return "CONSOLE_PROJECT";
189
+ case "directory":
190
+ return source.directory === undefined
191
+ ? DIRECTORY_FILE
192
+ : `${DIRECTORY_FILE} in ${source.directory}`;
193
+ }
194
+ }
107
195
  const NO_PROJECT = "Say which project: --project <key>, CONSOLE_PROJECT in the environment, or console use <key> once in this directory. console projects lists the projects you may work in.";
108
196
  /** What the command keeps, or nothing; a file that cannot be read stops the command, and is never written over. */
109
197
  async function loadCredentials(io) {
@@ -117,6 +205,18 @@ async function loadCredentials(io) {
117
205
  throw error;
118
206
  }
119
207
  }
208
+ /**
209
+ * What is about to be kept, where the credentials file would read it back; else the command
210
+ * stops, and nothing is written. What a console answered comes to rest in that file, and
211
+ * anything at an address may answer to nobody: kept beyond the file's own bounds, it would have
212
+ * every later command stop on a file it cannot read, at every console.
213
+ */
214
+ function fitting(next, url) {
215
+ if (!fitsFile(next)) {
216
+ throw failed(`${url} answered what the command cannot keep: a code, a token or a name beyond the bounds a console's have. Nothing was kept. Check that the address is the console's, and sign in again.`);
217
+ }
218
+ return next;
219
+ }
120
220
  /** The console a directory is bound to, as an origin, when it names one. */
121
221
  function directoryOrigin(settings) {
122
222
  if (settings?.url === undefined) {
@@ -177,7 +277,19 @@ async function open(io, values) {
177
277
  ?.timeZone
178
278
  : undefined);
179
279
  const client = clientOf(io, url, token);
180
- const projectKey = async () => text(values, "project") ?? io.env.CONSOLE_PROJECT ?? directory?.project;
280
+ const projectNamed = () => {
281
+ const flagged = text(values, "project");
282
+ if (flagged !== undefined) {
283
+ return { key: flagged, source: { kind: "flag" } };
284
+ }
285
+ if (io.env.CONSOLE_PROJECT !== undefined) {
286
+ return { key: io.env.CONSOLE_PROJECT, source: { kind: "environment" } };
287
+ }
288
+ return directory === undefined
289
+ ? undefined
290
+ : { key: directory.project, source: { kind: "directory", directory: directory.directory } };
291
+ };
292
+ const projectKey = async () => projectNamed()?.key;
181
293
  return {
182
294
  client,
183
295
  url,
@@ -187,12 +299,17 @@ async function open(io, values) {
187
299
  credentials,
188
300
  json: on(values, "json"),
189
301
  projectKey,
302
+ projectNamed,
190
303
  async project() {
191
- const key = await projectKey();
192
- if (key === undefined) {
304
+ const named = projectNamed();
305
+ if (named === undefined) {
193
306
  throw failed(NO_PROJECT);
194
307
  }
195
- return client.project(key);
308
+ // A key typed on the command is in front of whoever typed it; one the directory or the
309
+ // environment named is not, and is said with the refusal.
310
+ return named.source.kind === "flag"
311
+ ? client.project(named.key)
312
+ : namingUnseen(client.project(named.key), () => unseenProjectWords(url, named, resolved.account));
196
313
  },
197
314
  };
198
315
  }
@@ -201,21 +318,57 @@ function answer(io, session, value, words) {
201
318
  io.stdout(session.json ? `${JSON.stringify(value, null, 2)}\n` : `${words()}\n`);
202
319
  }
203
320
  /** The run a command on a run means: the one named, else the one open run of this token in the project. */
204
- async function currentRun(project, values) {
321
+ async function currentRun(session, project, values) {
205
322
  const given = text(values, "run");
206
323
  if (given !== undefined) {
207
324
  return given;
208
325
  }
209
- const { items } = await project.runs({ open: true, mine: true });
326
+ // The brief form: a command on a run asks which run is open every time, and needs no report
327
+ // of it, where a long run has many.
328
+ const { items } = await project.runBriefs({ open: true, mine: true });
210
329
  const [only] = items;
211
330
  if (only !== undefined && items.length === 1) {
212
331
  return only.id;
213
332
  }
214
333
  if (items.length === 0) {
334
+ // A run is its person's, and `mine` is this token's: a run begun through another of the
335
+ // person's agents, or before the command was signed in again, is open all the same, and
336
+ // goes on by its id. It is named before any word of taking, since taking its task again
337
+ // would end it, a run that waits for a decision included.
338
+ const theirs = await openRunsOfThePerson(session, project);
339
+ if (theirs.length > 0) {
340
+ const one = theirs.length === 1;
341
+ throw failed([
342
+ `run.none: no run begun through this agent is open in this project; ${theirs.length} of yours begun through another agent, or before a new sign-in, ${one ? "is" : "are"} open:`,
343
+ ...theirs.map((run) => ` ${formatRunLine(run)}`),
344
+ `Go on with ${one ? "it" : "one of them"}: add --run <id> to the command. A run is its person's, whichever of their agents began it; taking its task again would end it and begin another.`,
345
+ ].join("\n"));
346
+ }
215
347
  throw failed("run.none: no run of yours is open in this project. Take a task first: console take <number>; or name a run: --run <id>");
216
348
  }
217
349
  throw failed(`run.ambiguous: several runs of yours are open in this project; say which with --run <id>:\n${items.map((run) => ` ${formatRunLine(run)}`).join("\n")}`);
218
350
  }
351
+ /**
352
+ * The open runs of the project that are for the person the command acts as, whichever of their
353
+ * agents began them: what a command on a run looks through when none was begun with its own
354
+ * token. A courtesy before a refusal: where the console does not answer it, there are none.
355
+ */
356
+ async function openRunsOfThePerson(session, project) {
357
+ try {
358
+ const [me, open] = await Promise.all([
359
+ session.client.me(),
360
+ project.runBriefs({ open: true, limit: LIST_LIMIT }),
361
+ ]);
362
+ const person = me.person;
363
+ return person === null ? [] : open.items.filter((run) => run.person.id === person.id);
364
+ }
365
+ catch (error) {
366
+ if (error instanceof ApiError) {
367
+ return [];
368
+ }
369
+ throw error;
370
+ }
371
+ }
219
372
  /** A Markdown body: from `--file`, from standard input for `-`, or as given. */
220
373
  async function bodyOf(io, values, given) {
221
374
  const file = text(values, "file");
@@ -410,7 +563,9 @@ const stillWaiting = (id) => `Decision ${id} still waits for a person; the run w
410
563
  * Waits for the answer and says what it is, or that it is still to come. On `--json`, a decision
411
564
  * printed already as it was raised (`shown`) is printed again only with its answer.
412
565
  */
413
- async function settle(io, session, project, decision, seconds, shown = false) {
566
+ async function settle(io, session, project, decision, seconds, shown = false,
567
+ /** What is said where the decision still waits, in place of how an attended agent waits on. */
568
+ waiting) {
414
569
  const outcome = decision.answer === null && seconds > 0
415
570
  ? await waitForAnswer(io, project, decision, seconds)
416
571
  : decision;
@@ -420,10 +575,36 @@ async function settle(io, session, project, decision, seconds, shown = false) {
420
575
  }
421
576
  }
422
577
  else {
423
- io.stdout(`${outcome.answer === null ? stillWaiting(outcome.id) : formatAnswer(outcome)}\n`);
578
+ io.stdout(`${outcome.answer === null ? (waiting ?? stillWaiting(outcome.id)) : formatAnswer(outcome)}\n`);
424
579
  }
425
580
  return outcome.answer === null ? EXIT.waiting : EXIT.ok;
426
581
  }
582
+ /**
583
+ * Whether the command is signed in as the account itself (ADR-0084), which is how an agent
584
+ * account's own command is: what the login kept says, and nothing the environment's pair does.
585
+ */
586
+ function signedInAsItself(session) {
587
+ return (session.via === "login" &&
588
+ session.credentials?.logins.find((kept) => kept.url === session.url && kept.account === session.account)?.self === true);
589
+ }
590
+ /**
591
+ * The address of a task's page at the console the command talks to: the console's origin and
592
+ * the path the pages route a task by (ADR-0010), made here and asked of no console. An agent
593
+ * that tells a person of a task links this, and not the console's front page; nothing where
594
+ * the command works in no project.
595
+ */
596
+ async function taskPage(session, number) {
597
+ const key = await session.projectKey();
598
+ return key === undefined ? undefined : `${session.url}${taskHref(key, number)}`;
599
+ }
600
+ /**
601
+ * The address of a decision's page: in the project the command reached it in, else the
602
+ * decision's own (ADR-0068), which whoever it reaches may open, in that project or not.
603
+ */
604
+ async function decisionPage(session, id, atItsAddress = false) {
605
+ const key = atItsAddress ? undefined : await session.projectKey();
606
+ return `${session.url}${key === undefined ? myDecisionHref(id) : decisionHref(key, id)}`;
607
+ }
427
608
  /**
428
609
  * Who the command is, in a few words: the login and the role, and an agent account by its
429
610
  * handle first, which is what it is called by everywhere and what its setup's guide says the
@@ -449,12 +630,6 @@ say = io.stdout) {
449
630
  throw failed("The console does not know this token. Make one on your Agents page and try again.");
450
631
  }
451
632
  const credentials = (await loadCredentials(io)) ?? EMPTY_CREDENTIALS;
452
- const replaced = loginsAt(credentials, url).find((login) => login.account === person.login);
453
- if (replaced !== undefined && replaced.token !== token) {
454
- await clientOf(io, url, replaced.token)
455
- .giveUpToken()
456
- .catch(() => undefined);
457
- }
458
633
  const next = withLogin(credentials, {
459
634
  url,
460
635
  account: person.login,
@@ -463,12 +638,29 @@ say = io.stdout) {
463
638
  since: new Date(io.now()).toISOString(),
464
639
  ...(self ? { self: true } : {}),
465
640
  timeZone: me.workspace.timeZone ?? undefined,
466
- }, { default: asDefault });
467
- const kept = await io.store.save(next);
641
+ }, io.now(), { default: asDefault });
642
+ // A login kept at a console ends the connection that waited there (ADR-0129): its secret
643
+ // is spent, and is kept no longer. Asked whether it can be kept before the token it replaces
644
+ // is given up, so that none is given up for one that never was.
645
+ const keeping = fitting(withoutPending(next, url, io.now()), url);
646
+ const replaced = loginsAt(credentials, url).find((login) => login.account === person.login);
647
+ if (replaced !== undefined && replaced.token !== token) {
648
+ await clientOf(io, url, replaced.token)
649
+ .giveUpToken()
650
+ .catch(() => undefined);
651
+ }
652
+ const kept = await io.store.save(keeping);
468
653
  const standing = next.default === url ? ", the default console here" : "";
654
+ // Last, what holds where, never a next step: the line once said to bind this directory
655
+ // next, and a folder that is no checkout of a project's repository, a desk or a home
656
+ // directory, was bound to a project because it said so.
657
+ const binding = "Only a project's checkout is bound to it: console use <key> (console projects lists them).";
658
+ // Where it is kept: the file, for a person at a terminal. Where no terminal shows the words,
659
+ // an agent reads them, and the path of the one file it must never open is not handed to it.
660
+ const where = io.terminal === false ? "on this machine by the command, and never shown" : `in ${kept}`;
469
661
  say(self
470
- ? `Signed in to ${me.workspace.name} at ${url} as ${whoOf(person)}, the account itself${standing}: what this command does, ${person.login} does, and no agent is named beside it. The session is kept while it is used; its secret is kept in ${kept}.\nNext, say which project this directory works in: console use <key> (console projects lists them).\n`
471
- : `${agent === undefined ? "Signed in" : `Connected as "${agent}"`} to ${me.workspace.name} at ${url} as ${whoOf(person)}${standing}. The token is kept in ${kept}.\nNext, say which project this directory works in: console use <key> (console projects lists them).\n`);
662
+ ? `Signed in to ${me.workspace.name} at ${url} as ${whoOf(person)}, the account itself${standing}: what this command does, ${person.login} does, and no agent is named beside it. The session is kept while it is used; its secret is kept ${where}.\n${binding}\n`
663
+ : `${agent === undefined ? "Signed in" : `Connected as "${agent}"`} to ${me.workspace.name} at ${url} as ${whoOf(person)}${standing}. The token is kept ${where}.\n${binding}\n`);
472
664
  return EXIT.ok;
473
665
  }
474
666
  const login = async (args, io) => {
@@ -477,6 +669,7 @@ const login = async (args, io) => {
477
669
  agent: { type: "string" },
478
670
  self: { type: "boolean" },
479
671
  default: { type: "boolean" },
672
+ wait: { type: "string" },
480
673
  }, false);
481
674
  const credentials = await loadCredentials(io);
482
675
  const wanted = text(values, "url") ?? io.env.CONSOLE_URL ?? credentials?.default;
@@ -495,36 +688,150 @@ const login = async (args, io) => {
495
688
  // A connection (ADR-0011): a code a person approves on the console's own pages, and the token
496
689
  // handed over here once, never shown.
497
690
  const client = clientOf(io, url);
498
- // "<agent> on <machine>": the pages say the agent and keep the machine for a hover.
499
- const agent = text(values, "agent") ?? agentOf(io.env) ?? "An agent";
500
691
  // With --self the command asks to be the account itself (ADR-0084): whoever approves says
501
692
  // "this is me", and what is handed over is a session of the command's, in place of a token.
502
693
  const self = on(values, "self");
503
- const begun = await client.connect({
504
- agent: io.hostname === undefined ? agent : `${agent} on ${io.hostname}`,
505
- ...(self ? { as: "self" } : {}),
506
- });
507
- io.stdout(self
508
- ? `To sign this command in as an account itself, open ${begun.url} signed in as that account, check that the page shows the code ${begun.code}, and say that it is you.\nWaiting for that, until ${begun.expiresAt}.\n`
509
- : `To connect this agent, a person opens ${begun.url} signed in, checks that the page shows the code ${begun.code}, names the agent and approves.\nWaiting for that, until ${begun.expiresAt}.\n`);
510
- for (;;) {
511
- await io.sleep(begun.interval * 1000);
512
- let claim;
513
- try {
514
- claim = await client.claimConnection(begun.secret);
694
+ // Where no terminal shows the command's words as they are printed, whoever runs it sees them
695
+ // when it ends: an agent's host held the address and the code back until its own limit, two
696
+ // minutes on, while a person waited for them. There the call that begins a connection says
697
+ // them and ends, and the next call waits for the approval (ADR-0129).
698
+ const attended = io.terminal !== false;
699
+ const wait = text(values, "wait");
700
+ const waitGiven = wait === undefined ? undefined : secondsOf(wait, 0);
701
+ // The end of the wait is a moment as any other the command prints (ADR-0035): in the
702
+ // workspace's time zone where a login at this console kept it, which is one zone whoever
703
+ // signed in; on a first sign-in, when none is known yet, in the machine's own, since an agent
704
+ // relays the moment to a person; as the API gave it where the machine says none.
705
+ setMomentZone(credentials?.logins.find((login) => login.url === url)?.timeZone ?? io.timeZone);
706
+ const again = `console login --url ${url}${self ? " --self" : ""}`;
707
+ /** Whom the code is shown to, and what they do with it. */
708
+ const asked = (page, code) => self
709
+ ? `To sign this command in as an account itself, open ${page} signed in as that account, check that the page shows the code ${code}, and say that it is you.`
710
+ : `To connect this agent, a person opens ${page} signed in, checks that the page shows the code ${code}, names the agent and approves.`;
711
+ /** Forgets the connection kept for this console, and any whose code ran out; writes nothing where none was kept. */
712
+ const forget = async () => {
713
+ const kept = await loadCredentials(io);
714
+ if (kept === undefined || (kept.pending ?? []).length === 0) {
715
+ return;
515
716
  }
516
- catch (error) {
517
- if (error instanceof ApiError && error.code === "connect.not_found") {
518
- throw failed("The connection was not approved in time, or the person said it was not theirs. Run console login again for a new code.");
717
+ const next = withoutPending(kept, url, io.now());
718
+ if (keepsNothing(next)) {
719
+ await io.store.clear();
720
+ }
721
+ else {
722
+ await io.store.save(next);
723
+ }
724
+ };
725
+ // A connection a call before this one began at this console, of the kind this call asks for:
726
+ // it is gone on with, and no new code is made while its code lasts.
727
+ let waiting = pendingAt(credentials, url);
728
+ if (waiting !== undefined && ((waiting.self === true) !== self || !lasts(waiting, io.now()))) {
729
+ const ranOut = !lasts(waiting, io.now());
730
+ await forget();
731
+ if (ranOut) {
732
+ io.stdout(`The code ${waiting.code} ran out before a person approved it. A new one:\n`);
733
+ }
734
+ waiting = undefined;
735
+ }
736
+ for (;;) {
737
+ const resumed = waiting !== undefined;
738
+ if (waiting === undefined) {
739
+ // "<agent> on <machine>": the pages say the agent and keep the machine for a hover.
740
+ const agent = text(values, "agent") ?? agentOf(io.env) ?? "An agent";
741
+ const begun = await client.connect({
742
+ agent: io.hostname === undefined ? agent : `${agent} on ${io.hostname}`,
743
+ ...(self ? { as: "self" } : {}),
744
+ });
745
+ waiting = {
746
+ url,
747
+ secret: begun.secret,
748
+ code: begun.code,
749
+ page: begun.url,
750
+ expiresAt: begun.expiresAt,
751
+ interval: begun.interval,
752
+ ...(self ? { self: true } : {}),
753
+ ...(asDefault ? { default: true } : {}),
754
+ };
755
+ // Kept only where this call may end before the approval: at a terminal, with no wait
756
+ // said, the secret stays in the process as it always did.
757
+ if (!attended || waitGiven !== undefined) {
758
+ await io.store.save(fitting(withPending((await loadCredentials(io)) ?? EMPTY_CREDENTIALS, waiting, io.now()), url));
519
759
  }
520
- throw error;
521
760
  }
522
- if (claim.status === "connected") {
523
- return keep(io, url, claim.secret, claim.token.name, asDefault);
761
+ const pending = waiting;
762
+ const until = moment(pending.expiresAt);
763
+ const end = Date.parse(pending.expiresAt);
764
+ const seconds = waitGiven ?? (attended ? MAX_WAIT_SECONDS : resumed ? DEFAULT_LOGIN_WAIT_SECONDS : 0);
765
+ // A call that begins a connection and waits for nothing says what a person does and ends:
766
+ // the words reach whoever ran it now, and the next call waits. A call that goes on with a
767
+ // connection says nothing before its wait where no terminal would show it.
768
+ const told = !resumed && seconds === 0;
769
+ if (!resumed || attended) {
770
+ // The telling is a sentence of its own, before the one that names the command: read in
771
+ // one sentence, an agent ran the command first and told its person after. And the wait
772
+ // of the next call is said apart from the code's end, which an agent took for how long
773
+ // that call waits, and gave it half an hour. At a terminal, told not to wait, the next
774
+ // call there waits while the code lasts, and says so.
775
+ const next = attended
776
+ ? `it waits for the approval while the code lasts, until ${until}`
777
+ : `it waits for the approval up to ${DEFAULT_LOGIN_WAIT_SECONDS} seconds a call, and the code lasts until ${until}`;
778
+ io.stdout(told
779
+ ? `${asked(pending.page, pending.code)}\n${self ? "Have that done now" : "Tell the person that address and that code now, in a message of its own"}, before you run the command again.\nThen run ${again} again: ${next}.\n`
780
+ : `${asked(pending.page, pending.code)}\nWaiting for that, until ${until}.\n`);
524
781
  }
525
- if (claim.status === "signed_in") {
526
- return keep(io, url, claim.secret, undefined, asDefault, true);
782
+ if (told) {
783
+ return EXIT.ok;
784
+ }
785
+ // Where the call may end before the approval, it waits no longer than it was given, and no
786
+ // longer than the code lasts; at a terminal with no wait said, until the console says how
787
+ // the connection ended, as before.
788
+ const bounded = waitGiven !== undefined || !attended;
789
+ const deadline = Math.min(io.now() + seconds * 1000, Number.isFinite(end) ? end : Number.POSITIVE_INFINITY);
790
+ // A connection gone on with is claimed at once, since its person may have approved between
791
+ // the two calls; one begun now, after the breath the console asked for, as before.
792
+ let first = resumed;
793
+ let gone = false;
794
+ for (;;) {
795
+ if (!first) {
796
+ if (bounded && io.now() + pending.interval * 1000 > deadline) {
797
+ break;
798
+ }
799
+ await io.sleep(pending.interval * 1000);
800
+ }
801
+ first = false;
802
+ let claim;
803
+ try {
804
+ claim = await client.claimConnection(pending.secret);
805
+ }
806
+ catch (error) {
807
+ if (error instanceof ApiError && error.code === "connect.not_found") {
808
+ gone = true;
809
+ break;
810
+ }
811
+ throw error;
812
+ }
813
+ if (claim.status === "connected") {
814
+ return keep(io, url, claim.secret, claim.token.name, asDefault || pending.default === true);
815
+ }
816
+ if (claim.status === "signed_in") {
817
+ return keep(io, url, claim.secret, undefined, asDefault || pending.default === true, true);
818
+ }
819
+ }
820
+ if (gone) {
821
+ await forget();
822
+ if (!resumed) {
823
+ throw failed("The connection was not approved in time, or the person said it was not theirs. Run console login again for a new code.");
824
+ }
825
+ // A connection kept from a call before, which the console no longer knows: its code ran
826
+ // out there, or a person said it was not theirs. It is forgotten, and a new one begun.
827
+ io.stdout(`The code ${pending.code} is good no longer: it ran out, or a person said the connection was not theirs. A new one:\n`);
828
+ waiting = undefined;
829
+ continue;
527
830
  }
831
+ // The wait this call was given is over and the code still lasts: the connection stays kept,
832
+ // and the same command goes on waiting for it.
833
+ io.stdout(`${self ? "Not signed in yet" : "Not approved yet"}. ${asked(pending.page, pending.code)}\nKeep waiting with: ${again}, as often as needed until ${until}.\n`);
834
+ return EXIT.waiting;
528
835
  }
529
836
  };
530
837
  const logout = async (args, io) => {
@@ -537,7 +844,15 @@ const logout = async (args, io) => {
537
844
  }
538
845
  };
539
846
  if (credentials === undefined || credentials.logins.length === 0) {
540
- io.stdout("Not signed in here: nothing to forget.\n");
847
+ // Nobody is signed in; a connection that waited for a person is forgotten all the same
848
+ // (ADR-0129), with its secret.
849
+ if (credentials !== undefined && (credentials.pending ?? []).length > 0) {
850
+ await io.store.clear();
851
+ io.stdout("Not signed in here; the connection that waited for a person is forgotten.\n");
852
+ }
853
+ else {
854
+ io.stdout("Not signed in here: nothing to forget.\n");
855
+ }
541
856
  envNote();
542
857
  return EXIT.ok;
543
858
  }
@@ -558,7 +873,16 @@ const logout = async (args, io) => {
558
873
  const chosen = account === undefined ? at : at.filter((login) => login.account === account);
559
874
  const [login] = chosen;
560
875
  if (login === undefined) {
561
- throw failed(`Nobody is signed in here at ${url}${account === undefined ? "" : ` as ${account}`}: nothing to forget. console logins lists the consoles signed in.`);
876
+ const whom = account === undefined ? "" : ` as ${account}`;
877
+ // Nobody to sign out there; a connection that waits for a person at that console is
878
+ // forgotten all the same (ADR-0129): signing out of a console leaves no secret of it here.
879
+ if (pendingAt(credentials, url) !== undefined) {
880
+ await io.store.save(withoutPending(credentials, url, io.now()));
881
+ io.stdout(`Nobody is signed in here at ${url}${whom}; the connection that waited for a person there is forgotten.\n`);
882
+ envNote();
883
+ return EXIT.ok;
884
+ }
885
+ throw failed(`Nobody is signed in here at ${url}${whom}: nothing to forget. console logins lists the consoles signed in.`);
562
886
  }
563
887
  if (chosen.length > 1) {
564
888
  throw failed(`Several accounts are signed in at ${url} (${chosen.map((kept) => kept.account ?? "?").join(", ")}); say which: console logout --url ${url} --account <login>`);
@@ -580,8 +904,10 @@ const logout = async (args, io) => {
580
904
  outcome = "left";
581
905
  }
582
906
  }
583
- const next = withoutLogin(credentials, url, login.account);
584
- if (next.logins.length === 0) {
907
+ // A connection that waited at this console goes with its login (ADR-0129), as does any
908
+ // whose code ran out: signing out leaves no secret of the console here.
909
+ const next = withoutPending(withoutLogin(credentials, url, io.now(), login.account), url, io.now());
910
+ if (keepsNothing(next)) {
585
911
  await io.store.clear();
586
912
  }
587
913
  else {
@@ -609,17 +935,36 @@ const logins = async (args, io) => {
609
935
  since: login.since ?? null,
610
936
  default: credentials?.default === login.url,
611
937
  }));
938
+ // The connections that wait for a person while their codes last (ADR-0129): the console, the
939
+ // code and its end, never the secret; one whose code ran out is not shown.
940
+ const waiting = (credentials?.pending ?? [])
941
+ .filter((pending) => lasts(pending, io.now()))
942
+ .map((pending) => ({
943
+ url: pending.url,
944
+ code: pending.code,
945
+ expiresAt: pending.expiresAt,
946
+ self: pending.self === true,
947
+ }));
612
948
  if (on(values, "json")) {
613
- io.stdout(`${JSON.stringify({ default: credentials?.default ?? null, logins: kept }, null, 2)}\n`);
949
+ io.stdout(`${JSON.stringify({
950
+ default: credentials?.default ?? null,
951
+ logins: kept,
952
+ ...(waiting.length === 0 ? {} : { waiting }),
953
+ }, null, 2)}\n`);
614
954
  return EXIT.ok;
615
955
  }
956
+ const lines = [
957
+ ...kept.map((login) => `${login.url} ${login.account ?? "(account unknown)"}${login.agent === null ? "" : ` ${login.agent}`}${login.self ? " as the account itself" : ""}${login.since === null ? "" : ` since ${login.since.slice(0, 10)}`}${login.default ? " (default)" : ""}`),
958
+ ];
959
+ for (const pending of waiting) {
960
+ // The code's end as login printed it: in the zone a login at that console kept, else the machine's.
961
+ setMomentZone(credentials?.logins.find((login) => login.url === pending.url)?.timeZone ?? io.timeZone);
962
+ lines.push(`${pending.url} waits for a person to approve the code ${pending.code}, until ${moment(pending.expiresAt)}: console login --url ${pending.url}${pending.self ? " --self" : ""}`);
963
+ }
616
964
  if (kept.length === 0) {
617
- io.stdout("Not signed in anywhere here: console login --url <the console's origin>\n");
618
- return EXIT.ok;
965
+ lines.unshift("Not signed in anywhere here: console login --url <the console's origin>");
619
966
  }
620
- io.stdout(`${kept
621
- .map((login) => `${login.url} ${login.account ?? "(account unknown)"}${login.agent === null ? "" : ` ${login.agent}`}${login.self ? " as the account itself" : ""}${login.since === null ? "" : ` since ${login.since.slice(0, 10)}`}${login.default ? " (default)" : ""}`)
622
- .join("\n")}\n`);
967
+ io.stdout(`${lines.join("\n")}\n`);
623
968
  return EXIT.ok;
624
969
  };
625
970
  /** The agent the command runs under, where its environment says so: what a connection is named by default. */
@@ -645,7 +990,8 @@ async function rememberZone(io, session, zone) {
645
990
  if (kept === undefined || kept.timeZone === zone) {
646
991
  return;
647
992
  }
648
- await io.store.save(withLogin(session.credentials, { ...kept, timeZone: zone }));
993
+ // Kept anew, and so without a connection whose code ran out (ADR-0129).
994
+ await io.store.save(fitting(withLogin(session.credentials, { ...kept, timeZone: zone }, io.now()), session.url));
649
995
  }
650
996
  const whoami = async (args, io) => {
651
997
  const { values } = parse(args, {}, false);
@@ -656,7 +1002,29 @@ const whoami = async (args, io) => {
656
1002
  throw failed("The console does not know this token. Sign in again: console login");
657
1003
  }
658
1004
  await rememberZone(io, session, me.workspace.timeZone ?? undefined);
659
- const key = await session.projectKey();
1005
+ // The project the directory names is asked of the console (ADR-0112): a key repeated from a
1006
+ // file says nothing of whether this console has the project, or shows it to this member, and
1007
+ // an agreement has its agents check the binding with this command before the first one on
1008
+ // the board. Where the key came from is said either way, since that is where it is mended.
1009
+ const named = session.projectNamed();
1010
+ const key = named?.key;
1011
+ let projectName;
1012
+ if (named !== undefined) {
1013
+ try {
1014
+ projectName = (await session.client.project(named.key).get()).name;
1015
+ }
1016
+ catch (error) {
1017
+ if (!(error instanceof ApiError && error.code === "project.not_found")) {
1018
+ throw error;
1019
+ }
1020
+ }
1021
+ }
1022
+ const missing = named !== undefined && projectName === undefined;
1023
+ const projectWords = named === undefined
1024
+ ? "; no project named here"
1025
+ : projectName === undefined
1026
+ ? `; project ${named.key}, named by ${sourceWords(named.source)}, which this console does not have or does not show you`
1027
+ : `; project ${named.key} (${projectName}), named by ${sourceWords(named.source)}`;
660
1028
  const command = parseVersion(io.version);
661
1029
  const server = parseVersion(me.console?.version);
662
1030
  const verdict = command === undefined || server === undefined
@@ -673,14 +1041,21 @@ const whoami = async (args, io) => {
673
1041
  ...me,
674
1042
  console: me.console ?? null,
675
1043
  project: key ?? null,
1044
+ projectName: projectName ?? null,
1045
+ projectSource: named?.source ?? null,
676
1046
  command: { version: io.version ?? null, install: io.install ?? null },
677
1047
  }, () => [
678
- `${whoOf(person)} at ${me.workspace.name}, ${session.url}${key === undefined ? "; no project named here" : `; project ${key}`}${me.session?.kind === "command" ? "; signed in as the account itself" : ""}`,
679
- // The pack's rules send an agent here first; from here the rules and the skill are the next
680
- // steps. In a directory that names no project too: an agent account's desk names none,
681
- // the command's help sends an agent here for where the skill is, and the workspace has
682
- // rules whatever the project.
683
- `What this organization asks of agents: console rules. How the board is worked: the skill working-the-board, shipped with this command${io.skillsDir === undefined ? " (console skills says where it is)." : `: ${ownSkillPath(io.skillsDir)}`}`,
1048
+ `${whoOf(person)} at ${me.workspace.name}, ${session.url}${projectWords}${me.session?.kind === "command" ? "; signed in as the account itself" : ""}`,
1049
+ // The sentence of a checkout's agreement sends an agent here first and says that this
1050
+ // answer says how: so it says what is read before the first task, the rules and the
1051
+ // skill, and that one command's flags are read from that command's help, since an agent
1052
+ // that has the skill was reading the whole help beside it. In a directory that names
1053
+ // no project too: an agent account's desk names none, the command's help sends an
1054
+ // agent here for where the skill is, and the workspace has rules whatever the project.
1055
+ // The skill's path stands last, with nothing after it, to be copied as it is.
1056
+ io.skillsDir === undefined
1057
+ ? "Before the first task, read console rules and the skill working-the-board (console skills says where it is); for one command's flags, console help <command>."
1058
+ : `Before the first task, read console rules and the skill working-the-board; for one command's flags, console help <command>. The skill: ${ownSkillPath(io.skillsDir)}`,
684
1059
  `This command is ${io.version ?? "of a version it does not know"}${io.install === undefined ? "" : `, ${describeInstall(io.install)}`}; ${consoleWords}.`,
685
1060
  ...(verdict === "behind"
686
1061
  ? [`A newer command exists. Update it: ${updateWords(io, me.console?.version)}`]
@@ -690,6 +1065,11 @@ const whoami = async (args, io) => {
690
1065
  ]
691
1066
  : []),
692
1067
  ].join("\n"));
1068
+ if (missing && named !== undefined) {
1069
+ // Who and where are said above, which is what mends it; the command still ends as refused,
1070
+ // so that a check of the binding never passes on a key alone.
1071
+ throw failed(unseenProjectWords(session.url, named, person.login));
1072
+ }
693
1073
  return EXIT.ok;
694
1074
  };
695
1075
  const projects = async (args, io) => {
@@ -706,23 +1086,21 @@ const use = async (args, io) => {
706
1086
  const key = theOne(positionals, "Say which project: console use <key> [--url <origin>] [--account <login>]");
707
1087
  const session = await open(io, values);
708
1088
  const project = await session.client.project(key).get();
709
- // The directory names the console where that is not the default login here, or when asked,
710
- // and the account where the console has several, or when asked; never a token.
711
- const credentials = session.credentials ?? EMPTY_CREDENTIALS;
712
- const pinUrl = text(values, "url") !== undefined ||
713
- (session.via === "login" && credentials.default !== session.url);
714
- const pinAccount = text(values, "account") !== undefined ||
715
- (session.via === "login" && loginsAt(credentials, session.url).length > 1);
1089
+ // The directory names the console every time (ADR-0112): what is the default login on this
1090
+ // machine is another console's on the next, and a file that said only the project would
1091
+ // follow it there. The account only when asked, or where the directory named it before, so
1092
+ // that a file to be committed never carries somebody's account unasked; never a token.
1093
+ const before = await io.directory.load();
1094
+ const pinAccount = session.account !== undefined &&
1095
+ (text(values, "account") !== undefined || before?.account === session.account);
716
1096
  const kept = await io.directory.save({
717
1097
  project: project.key,
718
- ...(pinUrl ? { url: session.url } : {}),
719
- ...(pinAccount && session.account !== undefined ? { account: session.account } : {}),
1098
+ url: session.url,
1099
+ ...(pinAccount ? { account: session.account } : {}),
720
1100
  });
721
- const bound = pinUrl
722
- ? ` at ${session.url}${pinAccount && session.account !== undefined ? ` as ${session.account}` : ""}`
723
- : "";
1101
+ const bound = ` at ${session.url}${pinAccount ? ` as ${session.account}` : ""}`;
724
1102
  answer(io, session, project, () => [
725
- `Working in ${project.name} (${project.key})${bound} from this directory on: kept in ${kept}, which is meant to be committed in a private repository and left out of a public one. What its people ask of agents: console rules.`,
1103
+ `Working in ${project.name} (${project.key})${bound} from this directory on: kept in ${kept}, which names the project and the console, never a token, and is meant to be committed in a private repository and left out of a public one. What its people ask of agents: console rules.`,
726
1104
  // Nothing sends an agent to the console until the checkout says so; the sentence is the
727
1105
  // skill's (references/the-sentence.md), printed here as `skillcdn use` prints its own.
728
1106
  "Then put this sentence into the checkout's agreement (AGENTS.md, or CLAUDE.md where that is the file agents read), as it is, so that every agent working here is sent to the console:",
@@ -782,7 +1160,7 @@ const tasks = async (args, io) => {
782
1160
  if (search === "") {
783
1161
  throw misuse("Say what to search for: console tasks --search <words>");
784
1162
  }
785
- const found = await project.tasks({
1163
+ const filter = {
786
1164
  ...(state === undefined ? {} : { state }),
787
1165
  ...(on(values, "open") || due === "overdue" ? { open: true } : {}),
788
1166
  ...(worker === undefined ? {} : { worker }),
@@ -793,9 +1171,20 @@ const tasks = async (args, io) => {
793
1171
  ...(search === undefined ? {} : { q: search }),
794
1172
  ...(on(values, "archived") ? { archived: true } : {}),
795
1173
  ...page,
796
- });
797
- answer(io, session, found, () => found.items.length === 0
1174
+ };
1175
+ // A line a task and no body: the listing is asked for in the brief form, without the bodies,
1176
+ // which weigh more than the rest of a page together. --json is the console's own answer, whole.
1177
+ const found = session.json ? await project.tasks(filter) : await project.taskBriefs(filter);
1178
+ // A search that finds nothing says how it looked: every word must be in a title, so three
1179
+ // words find nothing where one of them finds the task, and an agent that read "No tasks."
1180
+ // wrote the same work a second time.
1181
+ const none = search === undefined
798
1182
  ? "No tasks."
1183
+ : /\s/.test(search.trim())
1184
+ ? `No tasks: no title holds every word of "${search.trim()}". Fewer words find more: one word of the thing's name, in the language the board is written in.`
1185
+ : `No tasks: no title holds "${search.trim()}".`;
1186
+ answer(io, session, found, () => found.items.length === 0
1187
+ ? none
799
1188
  : found.items.map(formatTaskLine).join("\n") +
800
1189
  formatMore(found.more, page.limit, page.offset));
801
1190
  return EXIT.ok;
@@ -822,321 +1211,378 @@ const categories = async (args, io) => {
822
1211
  answer(io, session, found, () => found.items.length === 0 ? "No categories." : found.items.map(formatCategoryLine).join("\n"));
823
1212
  return EXIT.ok;
824
1213
  };
825
- /** How many pages of a skill, of a file or of a folder the command follows before it stops: far above what one holds. */
826
- const MAX_SKILL_PAGES = 64;
827
- /** How many results a search answers at most: what the deployment allows on one page. */
828
- const MAX_FIND_LIMIT = 25;
829
- /** How many rows, and how many code blocks, one page of a read as data is asked to end after: the most the console takes. */
830
- const DATA_PAGE_ROWS = 5000;
831
- const DATA_PAGE_BLOCKS = 500;
832
- /** The pack of the project as the console lists it, and what its reads are rendered at; none when the pack did not answer. */
833
- async function packOf(reader) {
834
- const listing = await reader.skills();
835
- return { listing, summary: summaryOf(listing) };
836
- }
837
1214
  const SKILLS_OPTIONS = {
838
1215
  search: { type: "string" },
1216
+ path: { type: "string" },
839
1217
  limit: { type: "string" },
840
1218
  cursor: { type: "string" },
841
1219
  rows: { type: "boolean" },
842
1220
  code: { type: "boolean" },
843
1221
  heading: { type: "string" },
1222
+ format: { type: "string" },
1223
+ grep: { type: "string" },
844
1224
  out: { type: "string" },
845
1225
  };
846
1226
  /**
847
- * The tables, or the code blocks, of a document or of every document under a folder, as data
848
- * (ADR-0100): every page the console answers, joined, and printed as one CSV or as the blocks
849
- * as written, or written to a file with `--out`. What a program takes is never a refusal: a
850
- * read the pack refused fails with why, and so does one that did not reach its end.
1227
+ * A read the pack refused, as the command ends on it (ADR-0118): the words on standard error
1228
+ * and the exit of a refusal, as the skillcdn command ends one, where the pack's answer was once
1229
+ * printed as if it were the read. `--json` still prints what the console answered, which says
1230
+ * the status. Thrown by the caller, so that nothing follows it.
851
1231
  */
852
- async function readData(io, session, reader, asked) {
853
- const where = asked.path ?? "the pack";
854
- /** The answer written to a file, or printed: what was read in a line when a file was written. */
855
- const give = async (body, words, summary, name) => {
856
- const printed = session.json ? `${JSON.stringify(body, null, 2)}\n` : words;
857
- if (asked.out === undefined) {
858
- io.stdout(printed);
859
- return EXIT.ok;
860
- }
861
- let saved;
862
- try {
863
- saved = await io.writeBytes(asked.out, new TextEncoder().encode(printed), name);
864
- }
865
- catch {
866
- throw failed(`The file could not be written at ${asked.out}.`);
867
- }
868
- answer(io, session, { path: saved, summary }, () => `Saved ${summary} at ${saved}`);
869
- return EXIT.ok;
870
- };
871
- if (asked.what === "rows") {
872
- const pages = [];
873
- let next;
874
- for (let n = 0; n < MAX_SKILL_PAGES; n += 1) {
875
- const page = await reader.skillRows({
876
- path: asked.path,
877
- heading: asked.heading,
878
- cursor: next,
879
- limit: DATA_PAGE_ROWS,
880
- });
881
- const refusal = dataRefusal("tables", page);
882
- if (refusal !== undefined) {
883
- throw failed(refusal);
884
- }
885
- pages.push(page);
886
- next = page.read?.status === "ready" ? (page.read.nextCursor ?? undefined) : undefined;
887
- if (next === undefined) {
888
- break;
889
- }
890
- }
891
- const whole = joinRows(pages);
892
- const last = pages[pages.length - 1];
893
- if (whole === undefined || last === undefined) {
894
- throw failed("The tables could not be read.");
895
- }
896
- if (next !== undefined) {
897
- throw failed(`The tables under ${where} are more than the command reads at once (${describeRows(whole)} so far): name a folder or a file under it.`);
898
- }
899
- if (whole.tables.length === 0 && !session.json) {
900
- io.stdout(`No tables in ${where}${asked.heading === undefined ? "" : " under that heading"}.\n`);
901
- return EXIT.ok;
902
- }
903
- return give({ ...last, read: whole }, csvOfRows(whole), describeRows(whole), "rows.csv");
1232
+ function refusedRead(io, session, owner, answered, words) {
1233
+ if (session.json) {
1234
+ io.stdout(`${JSON.stringify(answered, null, 2)}\n`);
1235
+ }
1236
+ return failed(owner === "organization" ? `${ORGANIZATION_PACK_LINE}\n${words}` : words);
1237
+ }
1238
+ /** A whole number a flag carries, within its bounds; nothing when it is not given. */
1239
+ function countOf(given, name, bounds) {
1240
+ if (given === undefined) {
1241
+ return undefined;
904
1242
  }
905
- const pages = [];
906
- let next;
907
- for (let n = 0; n < MAX_SKILL_PAGES; n += 1) {
908
- const page = await reader.skillCode({
909
- path: asked.path,
910
- heading: asked.heading,
911
- cursor: next,
912
- limit: DATA_PAGE_BLOCKS,
1243
+ const count = /^\d{1,9}$/.test(given) ? Number(given) : Number.NaN;
1244
+ if (Number.isNaN(count) ||
1245
+ count < bounds.least ||
1246
+ (bounds.most !== undefined && count > bounds.most)) {
1247
+ throw misuse(`--${name} takes an integer ${bounds.most === undefined ? `from ${bounds.least}` : `between ${bounds.least} and ${bounds.most}`}: ${given}`);
1248
+ }
1249
+ return count;
1250
+ }
1251
+ /**
1252
+ * A number a read of a pack takes, checked as the skillcdn command checks it and said in its
1253
+ * words, before anything is asked of the console.
1254
+ */
1255
+ function checkedNumber(given, name, most) {
1256
+ try {
1257
+ readNumber(given, name, most);
1258
+ }
1259
+ catch (error) {
1260
+ throw error instanceof ReadMisuse ? misuse(error.message) : error;
1261
+ }
1262
+ }
1263
+ /**
1264
+ * The flags that say where a pack is read, as they were given, for the command that reads the
1265
+ * next part of a skill (ADR-0124): it is asked as this part was.
1266
+ */
1267
+ function whereGiven(values) {
1268
+ return ["project", "url", "account"].flatMap((name) => {
1269
+ const value = values[name];
1270
+ return typeof value === "string" ? [`--${name}`, value] : [];
1271
+ });
1272
+ }
1273
+ /**
1274
+ * One read of a pack as the skillcdn command makes it (ADR-0124): `readPack` of @skillcdn/cli
1275
+ * over the pack made of the console's answers, in the words of the command the pack is read
1276
+ * with. What the pack refused ends the command as refused (ADR-0118): of one read, in the
1277
+ * pack's own code and words, as that command prints them; of the pack as a whole, in the
1278
+ * console's. A read not asked right is a command not understood. With `data`, nothing is
1279
+ * printed for a refusal even with `--json`: what a program takes is never one.
1280
+ */
1281
+ async function readThrough(io, session, owner, pack, read, options) {
1282
+ try {
1283
+ return await readPack(pack, read, {
1284
+ words: options.words,
1285
+ json: session.json,
1286
+ nextPart: options.nextPart,
913
1287
  });
914
- const refusal = dataRefusal("code blocks", page);
915
- if (refusal !== undefined) {
916
- throw failed(refusal);
1288
+ }
1289
+ catch (error) {
1290
+ if (error instanceof ReadMisuse) {
1291
+ throw misuse(error.message);
917
1292
  }
918
- pages.push(page);
919
- next = page.read?.status === "ready" ? (page.read.nextCursor ?? undefined) : undefined;
920
- if (next === undefined) {
921
- break;
1293
+ const refusal = error instanceof PackRefusal
1294
+ ? { answer: error.answer, words: refusalWords(error.what, error.answer, owner) }
1295
+ : error instanceof PackError
1296
+ ? { answer: pack.answered(), words: `${error.code}: ${error.message}` }
1297
+ : undefined;
1298
+ if (refusal === undefined) {
1299
+ throw error;
922
1300
  }
1301
+ throw options.data === true || refusal.answer === undefined
1302
+ ? failed(refusal.words)
1303
+ : refusedRead(io, session, owner, refusal.answer, refusal.words);
923
1304
  }
924
- const whole = joinCode(pages);
925
- const last = pages[pages.length - 1];
926
- if (whole === undefined || last === undefined) {
927
- throw failed("The code blocks could not be read.");
1305
+ }
1306
+ /**
1307
+ * What `--json` prints for a read: the console's answer, with the pack's own in it as the
1308
+ * skillcdn command's `--json` prints it, the pages of a skill or of a read of data joined.
1309
+ */
1310
+ function jsonOfRead(session, pack, output) {
1311
+ return session.json ? { ...pack.answered(), read: JSON.parse(output.text) } : undefined;
1312
+ }
1313
+ /**
1314
+ * The tables, or the code blocks, of a document or of every document under a folder, as data
1315
+ * (ADR-0100): read and printed as the skillcdn command prints them, one CSV or an array of rows,
1316
+ * the blocks as written, or written to a file with `--out`. What a program takes is never a
1317
+ * refusal: a read the pack refused fails with why.
1318
+ */
1319
+ async function readData(io, session, pack, asked) {
1320
+ const { read } = asked;
1321
+ const output = await readThrough(io, session, asked.owner, pack, read, {
1322
+ words: asked.words,
1323
+ data: true,
1324
+ });
1325
+ // Nothing is printed for nothing, which a program takes as it is; a line beside it says so.
1326
+ if (holdsNothing(output.holds) && asked.out === undefined && !session.json) {
1327
+ io.stderr(`No ${read.read === "rows" ? "tables" : "code blocks"} in ${read.path ?? "the pack"}${read.heading === undefined ? "" : " under that heading"}.\n`);
1328
+ }
1329
+ const made = session.json
1330
+ ? JSON.stringify(jsonOfRead(session, pack, output), null, 2)
1331
+ : output.text;
1332
+ const whole = made.endsWith("\n") || made.length === 0 ? made : `${made}\n`;
1333
+ if (asked.out === undefined) {
1334
+ io.stdout(whole);
1335
+ return EXIT.ok;
928
1336
  }
929
- if (next !== undefined) {
930
- throw failed(`The code blocks under ${where} are more than the command reads at once (${describeCode(whole)} so far): name a folder or a file under it.`);
1337
+ const name = read.read === "code" ? "code.txt" : read.format === "json" ? "rows.json" : "rows.csv";
1338
+ let saved;
1339
+ try {
1340
+ saved = await io.writeBytes(asked.out, new TextEncoder().encode(whole), name);
931
1341
  }
932
- if (whole.blocks.length === 0 && !session.json) {
933
- io.stdout(`No code blocks in ${where}${asked.heading === undefined ? "" : " under that heading"}.\n`);
934
- return EXIT.ok;
1342
+ catch {
1343
+ throw failed(`The file could not be written at ${asked.out}.`);
935
1344
  }
936
- return give({ ...last, read: whole }, textOfCode(whole), describeCode(whole), "code.txt");
1345
+ io.stdout(`${wroteLine(output.holds ?? "", saved)}\n`);
1346
+ return EXIT.ok;
937
1347
  }
938
1348
  const SKILL_OPTIONS = {
939
1349
  file: { type: "string" },
940
1350
  offset: { type: "string" },
941
1351
  limit: { type: "string" },
1352
+ cursor: { type: "string" },
942
1353
  };
943
1354
  /** The line `console skills` ends with: where the plugins' own skills are. */
944
1355
  const PLUGIN_SKILLS_LINE = "The plugins of this console have skills of their own: console plugins lists the plugins, console plugin <key> skills the skills of one.";
945
1356
  /**
946
- * The pack as the words say: whole, a folder of it, a file's outline, or what words find; for
947
- * the project's pack as `console skills`, and for a plugin's as `console plugin <key> skills`.
1357
+ * The pack as the words say: whole, a page of a folder or of a file's outline, or what words
1358
+ * find; for the project's pack as `console skills`, and for a plugin's as
1359
+ * `console plugin <key> skills`. Each as the skillcdn command reads it, through its own reads
1360
+ * (ADR-0124).
948
1361
  */
949
1362
  async function readSkills(io, session, reader, values, positionals, extras) {
1363
+ const owner = extras.owner ?? "project";
1364
+ const say = (value, words) => answerPack(io, session, owner, value, words);
1365
+ // The reads by the names of this pack's own commands: a plugin's are not the project's.
1366
+ const skillCommand = extras.command.replace(/skills$/, "skill");
1367
+ const toolWords = packWords(extras.command, skillCommand);
1368
+ // How a skill is loaded, said after a listing and after what a search found: the pack's own
1369
+ // words there name how a section is read, and a skill read as a file comes without its rules.
1370
+ const loading = `A skill is loaded, its rules first, with ${skillCommand} <the path of its SKILL.md>, a long one in parts; --file reads a file of the pack as it is, without the rules.`;
950
1371
  if (positionals.length > 1) {
951
1372
  throw misuse(`Say one folder: ${extras.command} [<folder>] [--search <words>]`);
952
1373
  }
953
1374
  // The root of the pack is the mounted folder, which the deployment reads as no path at all.
954
1375
  const given = positionals[0];
955
- const folder = given === undefined || given === "/" || given === "." ? undefined : given;
956
1376
  const words = text(values, "search");
1377
+ const within = text(values, "path");
957
1378
  const limit = text(values, "limit");
958
1379
  const cursor = text(values, "cursor");
959
1380
  const rows = on(values, "rows");
960
1381
  const code = on(values, "code");
961
1382
  const heading = text(values, "heading");
962
1383
  const out = text(values, "out");
1384
+ const format = text(values, "format");
1385
+ const grep = text(values, "grep");
963
1386
  const dataUsage = `${extras.command} --rows|--code [<folder|file>] [--heading <words>] [--out <path>]`;
964
1387
  if (rows && code) {
965
1388
  throw misuse(`Say one: --rows for the tables, or --code for the code blocks: ${dataUsage}`);
966
1389
  }
967
- if ((rows || code) && (words !== undefined || limit !== undefined || cursor !== undefined)) {
1390
+ if ((rows || code) &&
1391
+ (words !== undefined || within !== undefined || limit !== undefined || cursor !== undefined)) {
968
1392
  throw misuse(`--rows and --code read a folder or a file whole, and go without --search: ${dataUsage}`);
969
1393
  }
970
1394
  if (!rows && !code && (heading !== undefined || out !== undefined)) {
971
1395
  throw misuse(`--heading and --out go with --rows or --code: ${dataUsage}`);
972
1396
  }
973
- if (words === undefined && (limit !== undefined || cursor !== undefined)) {
974
- throw misuse(`--limit and --cursor go with --search: ${extras.command} --search <words> [--limit <n>] [--cursor <cursor>]`);
1397
+ if (format !== undefined && !rows) {
1398
+ throw misuse(`--format goes with --rows: ${extras.command} --rows [<folder|file>] [--format csv|json]`);
1399
+ }
1400
+ if (grep !== undefined && !code) {
1401
+ throw misuse(`--grep goes with --code: ${extras.command} --code [<folder|file>] [--grep <pattern>]`);
1402
+ }
1403
+ // The folder a search keeps to is said once: after the words, or with --path as the
1404
+ // skillcdn command takes it.
1405
+ if (within !== undefined && words === undefined) {
1406
+ throw misuse(`--path goes with --search; a folder is read with ${extras.command} <folder>: ${extras.command} --search <words> [--path <folder>]`);
1407
+ }
1408
+ if (within !== undefined && given !== undefined) {
1409
+ throw misuse(`Say the folder once: after the words, or with --path: ${extras.command} --search <words> [<folder>]`);
975
1410
  }
976
- const atMost = limit === undefined ? undefined : Number(limit);
977
- if (atMost !== undefined &&
978
- (!Number.isInteger(atMost) || atMost < 1 || atMost > MAX_FIND_LIMIT)) {
979
- throw misuse(`Not a number of results, 1 to ${MAX_FIND_LIMIT}: ${limit}`);
1411
+ const named = given ?? within;
1412
+ const folder = named === undefined || named === "/" || named === "." ? undefined : named;
1413
+ if (words === undefined && given === undefined && (limit !== undefined || cursor !== undefined)) {
1414
+ throw misuse(`--limit and --cursor go with a folder or with --search: ${extras.command} <folder> [--limit <n>] [--cursor <cursor>]`);
980
1415
  }
981
- // As data: the read answers for itself how the pack stands, and fails where it does not.
1416
+ // A page of what words find, or of what a folder holds: the bounds of each, as the pack has them.
1417
+ checkedNumber(limit, "limit", words === undefined ? BROWSE_MAX_LIMIT : FIND_MAX_LIMIT);
1418
+ const listing = await reader.skills();
1419
+ // With --json the console's own addresses stay in a document's outline; in words, the
1420
+ // commands that read its tables and its code blocks.
1421
+ const pack = consolePack(reader, listing, {
1422
+ url: session.url,
1423
+ dataCommand: session.json ? undefined : extras.command,
1424
+ });
1425
+ // As data: a read the pack refused fails with why, and nothing is printed.
982
1426
  if (rows || code) {
983
- return readData(io, session, reader, {
984
- what: rows ? "rows" : "code",
985
- path: folder,
986
- heading,
1427
+ if (pack === undefined) {
1428
+ throw failed(refusalWords(rows ? "tables" : "code blocks", listing, owner));
1429
+ }
1430
+ return readData(io, session, pack, {
1431
+ read: rows
1432
+ ? { read: "rows", path: folder, heading, format }
1433
+ : { read: "code", path: folder, heading, grep },
987
1434
  out,
1435
+ owner,
1436
+ words: toolWords,
988
1437
  });
989
1438
  }
990
- const { listing, summary } = await packOf(reader);
991
- // The pack as it stands; or why it does not answer, which a folder or a search would meet too.
992
- if (summary === undefined || (words === undefined && given === undefined)) {
993
- answer(io, session, listing, () => [formatSkills(listing, extras.own), extras.afterwards]
1439
+ // A pack that does not answer: said as that, which a folder or a search would meet too.
1440
+ if (pack === undefined) {
1441
+ throw refusedRead(io, session, owner, listing, [formatSkills(listing, undefined, extras.own, owner, toolWords), extras.afterwards]
1442
+ .filter((part) => part !== undefined)
1443
+ .join("\n"));
1444
+ }
1445
+ if (words === undefined && given === undefined) {
1446
+ // --json is the console's listing as it answered it; the words are the pack's own, read once more from that answer.
1447
+ const told = session.json
1448
+ ? undefined
1449
+ : await readThrough(io, session, owner, pack, { read: "skills" }, { words: toolWords });
1450
+ say(listing, () => [formatSkills(listing, told?.text, extras.own, owner, toolWords), loading, extras.afterwards]
994
1451
  .filter((part) => part !== undefined)
995
1452
  .join("\n"));
996
1453
  return EXIT.ok;
997
1454
  }
998
1455
  if (words !== undefined) {
999
1456
  // One page of what the words find; more is said, and asked for with --cursor.
1000
- const found = await reader.skillFind(words, { path: folder, limit: atMost, cursor });
1001
- answer(io, session, found, () => formatSkillFind(found, summary));
1457
+ const found = await readThrough(io, session, owner, pack, { read: "find", words, path: folder, cursor, limit }, { words: toolWords });
1458
+ say(jsonOfRead(session, pack, found), () => `${found.text}\n${loading}`);
1002
1459
  return EXIT.ok;
1003
1460
  }
1004
- // The folder whole: its pages until the end, as the pack lists them.
1005
- const pages = [];
1006
- let next;
1007
- let last;
1008
- for (let n = 0; n < MAX_SKILL_PAGES; n += 1) {
1009
- last = await reader.skillBrowse({ path: folder, cursor: next });
1010
- if (last.read?.status !== "ready") {
1011
- break;
1012
- }
1013
- pages.push(last);
1014
- next = last.read.nextCursor ?? undefined;
1015
- if (next === undefined) {
1016
- break;
1017
- }
1461
+ // One page of the folder, or of a file's outline, as the skillcdn command browses: a page
1462
+ // that ends before the folder does names the cursor that continues it.
1463
+ const browsed = await readThrough(io, session, owner, pack, { read: "browse", path: folder, cursor, limit }, { words: toolWords });
1464
+ say(jsonOfRead(session, pack, browsed), () => browsed.text);
1465
+ return EXIT.ok;
1466
+ }
1467
+ /**
1468
+ * The pack a command reads (ADR-0113): the project's where one is named; else the
1469
+ * organization's, which a desk and a folder a repository is about to be made in read, since
1470
+ * neither names a project and the skill that sets one up is in that pack.
1471
+ */
1472
+ async function packNamed(session) {
1473
+ return (await session.projectKey()) === undefined
1474
+ ? { reader: session.client.organizationPack(), owner: "organization" }
1475
+ : { reader: await session.project(), owner: "project" };
1476
+ }
1477
+ /**
1478
+ * A read of the organization's pack at a console from before ADR-0113, which has no such
1479
+ * routes and answers that nothing is at the path: said as what it is, with what still reads a
1480
+ * pack there, where the console's own words would read as a missing skill.
1481
+ */
1482
+ async function readingPack(owner, read) {
1483
+ try {
1484
+ return await read();
1018
1485
  }
1019
- if (last === undefined) {
1020
- throw failed("The folder could not be read.");
1486
+ catch (error) {
1487
+ if (owner === "organization" && error instanceof ApiError && error.code === "not_found") {
1488
+ throw failed(`This console does not read the organization's pack where no project is named: it is older than the command. ${NO_PROJECT}`);
1489
+ }
1490
+ throw error;
1021
1491
  }
1022
- const browsed = last;
1023
- const whole = joinFolder(pages, summary);
1024
- answer(io, session, { ...browsed, read: whole === undefined ? null : bodyOfFolder(whole) }, () => formatSkillBrowse(browsed, whole, extras.command));
1025
- return EXIT.ok;
1492
+ }
1493
+ /**
1494
+ * Prints a read of a pack: as `answer` does, and, where the pack is the organization's, under
1495
+ * the line that says so. `--json` stays what the console answered.
1496
+ */
1497
+ function answerPack(io, session, owner, value, words) {
1498
+ answer(io, session, value, () => owner === "organization" ? `${ORGANIZATION_PACK_LINE}\n${words()}` : words());
1026
1499
  }
1027
1500
  const skills = async (args, io) => {
1028
1501
  const { values, positionals } = parse(args, SKILLS_OPTIONS);
1029
1502
  const session = await open(io, values);
1030
- const project = await session.project();
1031
- return readSkills(io, session, project, values, positionals, {
1503
+ const { reader, owner } = await packNamed(session);
1504
+ return readingPack(owner, () => readSkills(io, session, reader, values, positionals, {
1032
1505
  command: "console skills",
1033
1506
  own: io.skillsDir,
1034
1507
  afterwards: PLUGIN_SKILLS_LINE,
1035
- });
1508
+ owner,
1509
+ }));
1036
1510
  };
1037
- /** The most characters one read of a file asks for: what the console's API allows on one page. */
1038
- const MAX_FILE_LIMIT = 100_000;
1039
- /** A count given as a flag, within its bounds, or nothing; anything else is not understood. */
1040
- function countOf(given, name, bounds) {
1041
- if (given === undefined) {
1042
- return undefined;
1043
- }
1044
- const count = Number(given);
1045
- if (!Number.isInteger(count) ||
1046
- count < bounds.least ||
1047
- (bounds.most !== undefined && count > bounds.most)) {
1048
- const range = bounds.most === undefined ? `${bounds.least} or more` : `${bounds.least} to ${bounds.most}`;
1049
- throw misuse(`Not a number for --${name}, ${range}: ${given}`);
1050
- }
1051
- return count;
1052
- }
1053
1511
  /**
1054
- * One skill of the pack whole, a file of it, or one page of a file; for the project's pack as
1055
- * `console skill`, and for a plugin's as `console plugin <key> skill`.
1512
+ * One skill of the pack, or a page of a file of it; for the project's pack as `console skill`,
1513
+ * and for a plugin's as `console plugin <key> skill`. Each as the skillcdn command reads it,
1514
+ * through its own reads (ADR-0124): a skill whole where a host shows it whole, else in parts,
1515
+ * each ending with the command that reads the next; a file a page at a time. `again` is what
1516
+ * that command says after the cursor, its words: where the pack is read, as it was said for this
1517
+ * part.
1056
1518
  */
1057
- async function readSkill(io, session, reader, values, positionals, command) {
1519
+ async function readSkill(io, session, reader, values, positionals, command, owner = "project", again = []) {
1520
+ const say = (value, words) => answerPack(io, session, owner, value, words);
1521
+ const toolWords = packWords(`${command}s`, command);
1058
1522
  const file = text(values, "file");
1523
+ const cursor = text(values, "cursor");
1059
1524
  // A file is read by its own path from the repository's root; a skill's path beside it would be
1060
1525
  // ignored, which reads as if it mattered, so the two together are not understood.
1061
1526
  if (file !== undefined && positionals.length > 0) {
1062
1527
  throw misuse(`Say one: ${command} <path of its SKILL.md> for a skill, or ${command} --file <path> for a file of the pack.`);
1063
1528
  }
1064
- // A section is a page of a file read as asked (SkillCDN 0.4): the flags mean nothing without one.
1529
+ // A page of a file is asked for by where it begins and how long it is: the flags mean nothing without one.
1065
1530
  if (file === undefined &&
1066
1531
  (text(values, "offset") !== undefined || text(values, "limit") !== undefined)) {
1067
1532
  throw misuse(`--offset and --limit go with --file: ${command} --file <path> [--offset <n>] [--limit <n>]`);
1068
1533
  }
1069
- const offset = countOf(text(values, "offset"), "offset", { least: 0 });
1070
- const limit = countOf(text(values, "limit"), "limit", { least: 1, most: MAX_FILE_LIMIT });
1071
- const { listing, summary } = await packOf(reader);
1072
- if (summary === undefined) {
1073
- answer(io, session, listing, () => formatSkills(listing, io.skillsDir));
1074
- return EXIT.ok;
1534
+ // The next part of a skill is asked for by the cursor its part ended with; a file reads on from an offset.
1535
+ if (file !== undefined && cursor !== undefined) {
1536
+ throw misuse(`--cursor reads the next part of a skill; a file reads on from --offset: ${command} --file <path> [--offset <n>] [--limit <n>]`);
1075
1537
  }
1076
- if (file !== undefined && (offset !== undefined || limit !== undefined)) {
1077
- // One page as asked, the section a search or an outline named; the result says where the
1078
- // file continues, and asks for nothing.
1079
- const page = await reader.skillFile(file, { offset, limit });
1080
- const section = page.read === null ? undefined : joinFile([page], summary, limit);
1081
- answer(io, session, { ...page, read: section === undefined ? null : bodyOfFile(section) }, () => formatSkillFile(page, section));
1082
- return EXIT.ok;
1538
+ checkedNumber(text(values, "offset"), "offset", Number.MAX_SAFE_INTEGER);
1539
+ checkedNumber(text(values, "limit"), "limit", READ_FILE_MAX_LIMIT);
1540
+ const listing = await reader.skills();
1541
+ const pack = consolePack(reader, listing, { url: session.url });
1542
+ if (pack === undefined) {
1543
+ throw refusedRead(io, session, owner, listing, formatSkills(listing, undefined, io.skillsDir, owner, toolWords));
1083
1544
  }
1084
1545
  if (file !== undefined) {
1085
- // The file whole, page after page, as the console reads it from the pack.
1086
- const pages = [];
1087
- let offset;
1088
- let last;
1089
- for (let n = 0; n < MAX_SKILL_PAGES; n += 1) {
1090
- last = await reader.skillFile(file, offset === undefined ? {} : { offset });
1091
- if (last.read === null) {
1092
- break;
1093
- }
1094
- pages.push(last);
1095
- if (last.read.kind !== "file" || last.read.nextOffset === null) {
1096
- break;
1097
- }
1098
- offset = last.read.nextOffset;
1099
- }
1100
- if (last === undefined) {
1101
- throw failed("The file could not be read.");
1102
- }
1103
- const fileRead = last;
1104
- const whole = joinFile(pages, summary);
1105
- answer(io, session, { ...fileRead, read: whole === undefined ? null : bodyOfFile(whole) }, () => formatSkillFile(fileRead, whole));
1546
+ // A page of the file, as the skillcdn command reads one: from --offset, as long as a host
1547
+ // shows whole where --limit says nothing, and where the next begins when the file goes on.
1548
+ const page = await readThrough(io, session, owner, pack, { read: "file", path: file, offset: text(values, "offset"), limit: text(values, "limit") }, { words: toolWords });
1549
+ say(jsonOfRead(session, pack, page), () => page.text);
1106
1550
  return EXIT.ok;
1107
1551
  }
1108
- const wanted = skillPathIn(theOne(positionals, `Say which skill: ${command} <path of its SKILL.md>, or ${command} --file <path> for a file of the pack`), listing.address);
1552
+ const given = theOne(positionals, `Say which skill: ${command} <path of its SKILL.md>, or ${command} --file <path> for a file of the pack`);
1553
+ const wanted = skillPathIn(given, listing.address);
1109
1554
  if ("error" in wanted) {
1110
1555
  throw misuse(wanted.error);
1111
1556
  }
1112
- // The skill whole: its pages until complete, the rules first, as load_skill lays them out.
1113
- const pages = [];
1114
- let cursor;
1115
- let last;
1116
- for (let n = 0; n < MAX_SKILL_PAGES; n += 1) {
1117
- last = await reader.skill(wanted.path, cursor);
1118
- if (last.read?.status !== "ready") {
1119
- break;
1120
- }
1121
- pages.push(last);
1122
- cursor = last.read.skill.nextCursor ?? undefined;
1123
- if (last.read.skill.complete === true || cursor === undefined) {
1124
- break;
1125
- }
1126
- }
1127
- if (last === undefined) {
1128
- throw failed("The skill could not be read.");
1129
- }
1130
- const loaded = last;
1131
- const whole = joinSkill(pages, summary);
1132
- answer(io, session, { ...loaded, read: whole === undefined ? null : bodyOfSkill(whole) }, () => formatSkillLoad(loaded, whole));
1557
+ // The skill, its rules first, as load_skill lays them out: whole, or the part that begins at
1558
+ // the cursor, ending with the command that reads the next, asked as this one was.
1559
+ let continues = false;
1560
+ const loaded = await readThrough(io, session, owner, pack, { read: "skill", path: wanted.path, cursor }, {
1561
+ words: toolWords,
1562
+ // Spelled so that bash and PowerShell run it as it is; where a word has no such spelling,
1563
+ // the command that was run is run again, with the cursor, and the line says why.
1564
+ nextPart: (next) => {
1565
+ continues = true;
1566
+ return (commandLine(command, [given, "--cursor", next, ...again]) ??
1567
+ `the command you ran, with --cursor ${commandWord(next) ?? JSON.stringify(next)} in place of any it had, each word quoted for your shell. ${NO_LINE_TO_RUN}`);
1568
+ },
1569
+ });
1570
+ // A part that is not the last ends with the console's own words after the library's line: a
1571
+ // fresh agent read one part of four, saw that the skill continued, and planned from that part,
1572
+ // since "before using it" did not read as now to a session that meant only to plan.
1573
+ say(jsonOfRead(session, pack, loaded), () => continues ? `${loaded.text}\n${PART_ENDS_HERE}` : loaded.text);
1133
1574
  return EXIT.ok;
1134
1575
  }
1576
+ /**
1577
+ * What a part of a skill ends with where another follows: that the instructions stop here,
1578
+ * what the rest holds, and that the command above is run now.
1579
+ */
1580
+ const PART_ENDS_HERE = "This part stops in the middle of the skill: its later steps, its checkpoints and its rules are in the parts that follow, and nothing above is complete without them. Run that command now, before a plan, an answer or any other step, and each next one, until a part ends without these lines.";
1135
1581
  const skill = async (args, io) => {
1136
1582
  const { values, positionals } = parse(args, SKILL_OPTIONS);
1137
1583
  const session = await open(io, values);
1138
- const project = await session.project();
1139
- return readSkill(io, session, project, values, positionals, "console skill");
1584
+ const { reader, owner } = await packNamed(session);
1585
+ return readingPack(owner, () => readSkill(io, session, reader, values, positionals, "console skill", owner, whereGiven(values)));
1140
1586
  };
1141
1587
  // ---- The plugins (docs/specs/plugins.md, "The command") ----
1142
1588
  // `console plugins` and `console plugin <key> ...` are the two entries: the command sends the
@@ -1202,7 +1648,7 @@ function splitWords(args, own) {
1202
1648
  }
1203
1649
  return { values, words };
1204
1650
  }
1205
- const PLUGIN_USAGE = "console plugin <key> [help [<command>] | <command> [args] | records <collection> | skills | skill <path> | enable | disable | settings | secret <name> | grant <role> | revoke <id>]. console plugins lists the plugins.";
1651
+ const PLUGIN_USAGE = "console plugin <key> [help [<command>] | <command> [args] | records <collection> | events [--kind <kind>] | skills | skill <path> | enable | disable | settings | secret <name> [--key <key>] | grant <role> | revoke <id>]. console plugins lists the plugins.";
1206
1652
  const plugin = async (args, io) => {
1207
1653
  const { values, words } = splitWords(args, PLUGIN_GLOBAL_FLAGS);
1208
1654
  const [key, verb, ...rest] = words;
@@ -1234,6 +1680,8 @@ const plugin = async (args, io) => {
1234
1680
  }
1235
1681
  case "records":
1236
1682
  return pluginRecords(io, session, client, rest, text(values, "project"));
1683
+ case "events":
1684
+ return pluginEvents(io, session, client, rest);
1237
1685
  case "skills": {
1238
1686
  const parsed = parse(rest, SKILLS_OPTIONS);
1239
1687
  return readSkills(io, session, client, parsed.values, parsed.positionals, {
@@ -1242,7 +1690,7 @@ const plugin = async (args, io) => {
1242
1690
  }
1243
1691
  case "skill": {
1244
1692
  const parsed = parse(rest, SKILL_OPTIONS);
1245
- return readSkill(io, session, client, parsed.values, parsed.positionals, `console plugin ${key} skill`);
1693
+ return readSkill(io, session, client, parsed.values, parsed.positionals, `console plugin ${key} skill`, "project", whereGiven(values));
1246
1694
  }
1247
1695
  case "enable":
1248
1696
  return pluginEnable(io, session, client, rest);
@@ -1376,6 +1824,37 @@ function whereValueOf(word) {
1376
1824
  return word;
1377
1825
  }
1378
1826
  /** The records of a collection one may read, a page of them; or one record, or its versions. */
1827
+ /**
1828
+ * A plugin's events, newest first (ADR-0128): what it did and what went wrong in it, as far as
1829
+ * the caller may read it, which the console decides (every event for an administrator; for
1830
+ * anyone else those of the projects they may see, their own commands and the console's word of
1831
+ * the plugin); the failures alone with `--kind plugin.failed`, whether or not it has a board
1832
+ * project. A console before 0.5.1 takes no kind and answers every one: the page is narrowed
1833
+ * here, and that is said, since a page narrowed after it was read may hold fewer than were
1834
+ * asked for.
1835
+ */
1836
+ async function pluginEvents(io, session, client, rest) {
1837
+ const usage = `console plugin ${client.key} events [--kind <kind>] [--limit <n>] [--offset <n>]`;
1838
+ const { values, positionals } = parse(rest, { kind: { type: "string" }, ...PAGE_OPTIONS });
1839
+ if (positionals.length > 0) {
1840
+ throw misuse(`Events take no word but their flags: ${usage}`);
1841
+ }
1842
+ const kind = text(values, "kind");
1843
+ if (kind !== undefined && !/^[a-z_]{1,40}\.[a-z_]{1,40}$/.test(kind)) {
1844
+ throw misuse(`Not a kind of event: ${kind}. A kind is two words with a dot between, as plugin.failed or plugin.command: ${usage}`);
1845
+ }
1846
+ const limit = countOf(text(values, "limit"), "limit", { least: 1, most: EVENTS_PAGE_LIMIT });
1847
+ const offset = countOf(text(values, "offset"), "offset", { least: 0, most: 1_000_000 });
1848
+ const asked = { kind, limit: limit ?? DEFAULT_PAGE_LIMIT, offset: offset ?? 0 };
1849
+ const read = await client.events(asked);
1850
+ const items = kind === undefined ? read.items : read.items.filter((one) => one.kind === kind);
1851
+ const narrowedHere = items.length !== read.items.length;
1852
+ const page = { items, more: read.more };
1853
+ answer(io, session, page, () => `${formatPluginEvents(client.key, page, asked)}${narrowedHere
1854
+ ? `\nThis console is older than 0.5.1 and does not narrow events by kind: of the ${read.items.length} newest read, the ${kind} ones are shown. Read further back with --offset.`
1855
+ : ""}`);
1856
+ return EXIT.ok;
1857
+ }
1379
1858
  async function pluginRecords(io, session, client, rest, project) {
1380
1859
  const { values, positionals } = parse(rest, {
1381
1860
  where: { type: "string", multiple: true },
@@ -1625,19 +2104,26 @@ async function pluginSettings(io, session, client, rest) {
1625
2104
  * shown never; or takes it away.
1626
2105
  */
1627
2106
  async function pluginSecret(io, session, client, rest) {
1628
- const { values, positionals } = parse(rest, { remove: { type: "boolean" } });
1629
- const name = theOne(positionals, `Say which secret: console plugin ${client.key} secret <name> [--remove]; the value is typed at the prompt, unseen, or piped in.`);
2107
+ const { values, positionals } = parse(rest, {
2108
+ remove: { type: "boolean" },
2109
+ key: { type: "string" },
2110
+ });
2111
+ const name = theOne(positionals, `Say which secret: console plugin ${client.key} secret <name> [--key <key>] [--remove]; the value is typed at the prompt, unseen, or piped in.`);
2112
+ // A secret kept per key (ADR-0111) is set and removed one key at a time.
2113
+ const key = text(values, "key");
2114
+ const which = key === undefined ? `the secret ${name}` : `the secret ${name} under ${key}`;
2115
+ const data = key === undefined ? { name } : { name, key };
1630
2116
  if (on(values, "remove")) {
1631
- await client.removeSecret(name);
1632
- answer(io, session, { name, set: false }, () => `Removed the secret ${name} of ${client.key}.`);
2117
+ await client.removeSecret(name, key);
2118
+ answer(io, session, { ...data, set: false }, () => `Removed ${which} of ${client.key}.`);
1633
2119
  return EXIT.ok;
1634
2120
  }
1635
- const value = await secretGiven(io, `Secret ${name} of ${client.key} (typed unseen; Enter ends it): `);
2121
+ const value = await secretGiven(io, `Secret ${name}${key === undefined ? "" : ` under ${key}`} of ${client.key} (typed unseen; Enter ends it): `);
1636
2122
  if (value.length === 0) {
1637
- throw misuse(`Type the value at the prompt, or redirect a file into it: console plugin ${client.key} secret ${name} < file. Never give it on the command line or through echo, which a shell keeps; the console seals it and shows it never.`);
2123
+ throw misuse(`Type the value at the prompt, or redirect a file into it: console plugin ${client.key} secret ${name}${key === undefined ? "" : ` --key ${key}`} < file. Never give it on the command line or through echo, which a shell keeps; the console seals it and shows it never.`);
1638
2124
  }
1639
- await client.setSecret(name, value);
1640
- answer(io, session, { name, set: true }, () => `Set the secret ${name} of ${client.key}: sealed, and shown by nothing from now on.`);
2125
+ await client.setSecret(name, value, key);
2126
+ answer(io, session, { ...data, set: true }, () => `Set ${which} of ${client.key}: sealed, and shown by nothing from now on.`);
1641
2127
  return EXIT.ok;
1642
2128
  }
1643
2129
  /**
@@ -1701,8 +2187,9 @@ function versionOf(given) {
1701
2187
  }
1702
2188
  return version;
1703
2189
  }
1704
- // The rules of the board (ADR-0023): read before a task is taken, written by an owner for the
1705
- // project and by an administrator for the workspace, through the same page the console keeps.
2190
+ // The rules of the board (ADR-0023, ADR-0120): the console's, which always hold, with what the
2191
+ // organization and the project add to them; read before a task is taken, and added to by an
2192
+ // owner for the project and by an administrator for the organization, on the page each keeps.
1706
2193
  const rules = async (args, io) => {
1707
2194
  const [verb, ...rest] = args;
1708
2195
  if (verb === "write") {
@@ -1719,36 +2206,44 @@ const rules = async (args, io) => {
1719
2206
  const none = given === "none";
1720
2207
  const body = none ? undefined : await bodyOf(io, values, given);
1721
2208
  if (!none && body === undefined) {
1722
- throw misuse("Say what the rules are to say: --body <markdown>, --file <path>, - to read standard input, or none to put the written rules away.");
2209
+ throw misuse("Say what is added to the rules: --body <markdown>, --file <path>, - to read standard input, or none to put what was added away.");
1723
2210
  }
1724
2211
  const baseVersion = versionOf(text(values, "base"));
1725
2212
  const session = await open(io, values);
1726
2213
  if (on(values, "workspace")) {
1727
2214
  if (none) {
1728
2215
  const put = await session.client.archiveRules();
1729
- answer(io, session, put, () => "The organization's rules are put away: the console's own hold.");
2216
+ answer(io, session, put, () => "What this organization adds to the rules is put away: the console's stand alone.");
1730
2217
  return EXIT.ok;
1731
2218
  }
2219
+ // A console of before 0.5.1 keeps what is written here as the organization's whole rules,
2220
+ // in the place of its own (ADR-0120): what is added would be all that holds there. Its
2221
+ // answer tells, since it says the workspace's rules whole and no parts, and it is asked
2222
+ // before anything is written.
2223
+ const held = await session.client.rules();
2224
+ if (held.own === undefined) {
2225
+ throw failed("This console is older than 0.5.1 and keeps the organization's rules whole: what is written here would replace the console's rules, not add to them. Update the console first.");
2226
+ }
1732
2227
  const written = await session.client.writeRules({
1733
2228
  body: body ?? "",
1734
2229
  ...(baseVersion === undefined ? {} : { baseVersion }),
1735
2230
  });
1736
2231
  answer(io, session, written, () => written.page === null
1737
- ? "Nothing written: these are the console's own rules as they stand, and they hold already."
1738
- : `Wrote the workspace's rules, version ${written.page.version}.`);
2232
+ ? "Nothing written: that adds nothing to the console's rules, which hold as they stand."
2233
+ : `Wrote what this organization adds to the rules, version ${written.page.version}.`);
1739
2234
  return EXIT.ok;
1740
2235
  }
1741
2236
  const project = await session.project();
1742
2237
  if (none) {
1743
2238
  try {
1744
2239
  const put = await project.archiveDocument(RULES_PATH);
1745
- answer(io, session, put, () => "This project's rules are put away: it adds none now.");
2240
+ answer(io, session, put, () => "What this project adds to the rules is put away: it adds nothing now.");
1746
2241
  }
1747
2242
  catch (error) {
1748
2243
  if (!(error instanceof ApiError) || error.code !== "document.not_found") {
1749
2244
  throw error;
1750
2245
  }
1751
- answer(io, session, null, () => "This project has no rules of its own to put away.");
2246
+ answer(io, session, null, () => "This project adds nothing to the rules: nothing to put away.");
1752
2247
  }
1753
2248
  return EXIT.ok;
1754
2249
  }
@@ -1757,14 +2252,14 @@ const rules = async (args, io) => {
1757
2252
  body: body ?? "",
1758
2253
  ...(baseVersion === undefined ? {} : { baseVersion }),
1759
2254
  });
1760
- answer(io, session, written, () => `Wrote this project's rules, version ${written.version}.`);
2255
+ answer(io, session, written, () => `Wrote what this project adds to the rules, version ${written.version}.`);
1761
2256
  return EXIT.ok;
1762
2257
  }
1763
2258
  const { values } = parse(args, {}, false);
1764
2259
  const session = await open(io, values);
1765
2260
  const key = await session.projectKey();
1766
2261
  const [found, me] = await Promise.all([
1767
- key === undefined ? session.client.rules() : session.client.project(key).rules(),
2262
+ key === undefined ? session.client.rules() : (await session.project()).rules(),
1768
2263
  session.client.me(),
1769
2264
  ]);
1770
2265
  const read = "workspace" in found
@@ -1774,15 +2269,24 @@ const rules = async (args, io) => {
1774
2269
  ...(found.plugins === undefined ? {} : { plugins: found.plugins }),
1775
2270
  }
1776
2271
  : forPerson(found, readingLanguage(me));
1777
- answer(io, session, read, () => formatRules(read, readingLanguage(me)));
2272
+ // The mark of what is printed goes with --json too, for a program that takes a task next.
2273
+ answer(io, session, { ...read, mark: rulesMark(read, readingLanguage(me)) }, () => formatRules(read, readingLanguage(me)));
1778
2274
  return EXIT.ok;
1779
2275
  };
1780
2276
  /**
1781
2277
  * The rules as they read for the person whose token the command holds: `{language}` filled
1782
- * with the language they read in, or with the task's while they have none.
2278
+ * with the language they read in, or with the task's while they have none; in the whole and,
2279
+ * where the console says them apart (ADR-0120), in the console's own and in what is added.
1783
2280
  */
1784
2281
  function forPerson(half, language) {
1785
- return half.body === null ? half : { ...half, body: fillRules(half.body, language) };
2282
+ return {
2283
+ ...half,
2284
+ ...(half.body === null ? {} : { body: fillRules(half.body, language) }),
2285
+ ...(half.own === undefined ? {} : { own: fillRules(half.own, language) }),
2286
+ ...(half.added == null
2287
+ ? {}
2288
+ : { added: { ...half.added, body: fillRules(half.added.body, language) } }),
2289
+ };
1786
2290
  }
1787
2291
  /** The flags that set a task's fields, shared by writing one and changing one. */
1788
2292
  const TASK_FIELDS = {
@@ -1850,8 +2354,24 @@ const newTask = async (args, io) => {
1850
2354
  ...TASK_FIELDS,
1851
2355
  body: { type: "string" },
1852
2356
  file: { type: "string" },
2357
+ take: { type: "boolean" },
2358
+ agent: { type: "string" },
2359
+ rules: { type: "string" },
1853
2360
  });
1854
2361
  const title = theOne(positionals, 'Say the title: console task new "<title>"');
2362
+ // Written and taken in one command (--take): work given in chat is both at once, and a
2363
+ // session that sends its commands together cannot read the number between two of them,
2364
+ // on a board where another agent may have written a task in the meantime.
2365
+ const taken = on(values, "take");
2366
+ if (!taken && (text(values, "rules") !== undefined || text(values, "agent") !== undefined)) {
2367
+ throw misuse('--rules and --agent go with --take, which takes the task as it is written: console task new "<title>" --take [--rules <mark>] [--agent <name>]');
2368
+ }
2369
+ // Refused before anything is written: a task that is done or dropped is not taken, and
2370
+ // written first it would stand on the board as the half of a command that failed.
2371
+ const said = stateOf(text(values, "state"));
2372
+ if (taken && (said === "done" || said === "dropped")) {
2373
+ throw misuse(`A task written as ${said} is not taken. Leave --state out, for ready; or leave --take out.`);
2374
+ }
1855
2375
  const body = await bodyOf(io, values, text(values, "body"));
1856
2376
  const session = await open(io, values);
1857
2377
  const project = await session.project();
@@ -1859,9 +2379,41 @@ const newTask = async (args, io) => {
1859
2379
  const made = await project.createTask({
1860
2380
  title,
1861
2381
  ...(body === undefined ? {} : { body }),
2382
+ // An idea is not taken: what is written to be taken is ready, where no state is said.
2383
+ ...(taken && said === undefined ? { state: "ready" } : {}),
1862
2384
  ...fields,
1863
2385
  });
1864
- answer(io, session, made, () => `Task #${made.number} written: ${made.title}\ntask id: ${made.id}`);
2386
+ const written = `Task #${made.number} written: ${made.title}\ntask id: ${made.id}`;
2387
+ if (!taken) {
2388
+ // With the address of its page, for a person told of the task; a task taken at once says
2389
+ // it in the task's own lines below, once.
2390
+ const page = await taskPage(session, made.number);
2391
+ answer(io, session, made, () => page === undefined ? written : `${written}\n${pageLine(page)}`);
2392
+ return EXIT.ok;
2393
+ }
2394
+ // The number first, before the take is asked for: whatever becomes of the take, the task is
2395
+ // on the board, and the session must know it by its number so as not to write it twice.
2396
+ if (!session.json) {
2397
+ io.stdout(`${written}\n`);
2398
+ }
2399
+ let run;
2400
+ let took;
2401
+ try {
2402
+ run = await runOn(project, made, values);
2403
+ took = await taking(session, project, made, made.id, run, values);
2404
+ }
2405
+ catch (error) {
2406
+ // Said before the console's own words for what failed, which follow as on any command:
2407
+ // which half stands, by the task's number, so that nothing is written or taken twice.
2408
+ if (session.json) {
2409
+ io.stdout(`${JSON.stringify({ written: made, ...(run === undefined ? {} : { run }) }, null, 2)}\n`);
2410
+ }
2411
+ io.stderr(run === undefined
2412
+ ? `Task #${made.number} is written and was not taken: it stands on the board as written. Take it with console take ${made.number}, and do not write it again. What the take ended on:\n`
2413
+ : `Task #${made.number} is written and taken, run ${run.id}, and what a take prints of it was not read. Do not write it or take it again: console task ${made.number} shows the task, console rules the rules. What the reading ended on:\n`);
2414
+ throw error;
2415
+ }
2416
+ answer(io, session, { written: made, ...took.value }, took.words);
1865
2417
  return EXIT.ok;
1866
2418
  };
1867
2419
  const editTask = async (args, io) => {
@@ -1886,7 +2438,8 @@ const editTask = async (args, io) => {
1886
2438
  }
1887
2439
  const found = await project.task(ref);
1888
2440
  const changed = await project.updateTask(found.id, patch);
1889
- answer(io, session, changed, () => formatTask(changed));
2441
+ const page = await taskPage(session, changed.number);
2442
+ answer(io, session, changed, () => formatTask(changed, undefined, undefined, undefined, page));
1890
2443
  return EXIT.ok;
1891
2444
  };
1892
2445
  /** Puts a task away, or every done or dropped task of a goal (ADR-0029); the task by its number or its id. */
@@ -1939,10 +2492,13 @@ const task = async (args, io) => {
1939
2492
  const found = await project.task(ref);
1940
2493
  const [decisions, runs, comments] = await Promise.all([
1941
2494
  project.decisions({ task: found.id }),
1942
- project.runs({ task: found.id }),
2495
+ // The runs are a line each, with their reports counted: the brief form, unless --json asks
2496
+ // for the console's own answer.
2497
+ session.json ? project.runs({ task: found.id }) : project.runBriefs({ task: found.id }),
1943
2498
  project.comments(found.id),
1944
2499
  ]);
1945
- answer(io, session, { task: found, decisions: decisions.items, runs: runs.items, comments: comments.items }, () => formatTask(found, decisions.items, runs.items, comments.items));
2500
+ const page = await taskPage(session, found.number);
2501
+ answer(io, session, { task: found, decisions: decisions.items, runs: runs.items, comments: comments.items }, () => formatTask(found, decisions.items, runs.items, comments.items, page));
1946
2502
  return EXIT.ok;
1947
2503
  };
1948
2504
  /**
@@ -2030,17 +2586,21 @@ const file = async (args, io) => {
2030
2586
  }, () => `Saved ${read.name} (${read.bytes.byteLength} bytes, ${read.contentType}) at ${saved}`);
2031
2587
  return EXIT.ok;
2032
2588
  };
2033
- const take = async (args, io) => {
2034
- const { values, positionals } = parse(args, { agent: { type: "string" } });
2035
- const ref = theOne(positionals, "Say which task: console take <number|id>");
2036
- const session = await open(io, values);
2037
- const project = await session.project();
2038
- const found = await project.task(ref);
2589
+ /** Begins a run on a task, as the agent `--agent` names where it is said: the take itself. */
2590
+ function runOn(project, found, values) {
2039
2591
  const agent = text(values, "agent");
2040
- const run = await project.startRun({
2592
+ return project.startRun({
2041
2593
  taskId: found.id,
2042
2594
  ...(agent === undefined ? {} : { agent }),
2043
2595
  });
2596
+ }
2597
+ /**
2598
+ * What a take answers, once its run began: the task as it stands taken, its comments and the
2599
+ * rules under their mark, or left out by it (`--rules`, ADR-0119). `take` takes a task that
2600
+ * was read by what the person said, `task new --take` the one it has just written; `ref` is
2601
+ * what the task is read again by, now that it is taken.
2602
+ */
2603
+ async function taking(session, project, found, ref, run, values) {
2044
2604
  // The rules come with the run, as they read for the person: everything from here acts
2045
2605
  // within them (ADR-0023); the task is read again, as it stands now that it is taken.
2046
2606
  const [ruling, me, taken, comments, openRuns] = await Promise.all([
@@ -2048,7 +2608,7 @@ const take = async (args, io) => {
2048
2608
  session.client.me(),
2049
2609
  project.task(ref),
2050
2610
  project.comments(found.id),
2051
- project.runs({ open: true, mine: true }),
2611
+ project.runBriefs({ open: true, mine: true }),
2052
2612
  ]);
2053
2613
  // Taking a task with a run open on it ends that run (ADR-0020): said when it happened.
2054
2614
  const tookOver = found.openRuns > 0
@@ -2065,19 +2625,48 @@ const take = async (args, io) => {
2065
2625
  project: forPerson(ruling.project, readingLanguage(me)),
2066
2626
  ...(ruling.plugins === undefined ? {} : { plugins: ruling.plugins }),
2067
2627
  };
2068
- answer(io, session, { run, task: taken, comments: comments.items, rules }, () => [
2069
- `Run ${run.id} began on #${found.number} ${found.title}, as "${run.agent}" for ${calledOf(run.person)}. The task is in progress and theirs.${tookOver}${elsewhere}`,
2070
- // The ids on a line of their own, each named: a run's and a task's begin alike, and a
2071
- // task has a number for people as well.
2072
- `run id: ${run.id} task id: ${found.id} (task #${found.number})`,
2073
- "",
2074
- formatTask(taken, undefined, undefined, comments.items),
2075
- "",
2076
- formatRules(rules, readingLanguage(me)),
2077
- "",
2078
- 'Say how it goes: console report "<what you found or did>". Hand in what you make: console hand-in <https url | file path>.',
2079
- 'Ask when a person must decide: console ask "<question>" --option "..." --option "...". A word for the task\'s people that is not a report: console comment <number> "<markdown>". End with: console finish --summary "<what was done, what is left>".',
2080
- ].join("\n"));
2628
+ // A take gives the rules, whole, unless the session says the mark they have (ADR-0119): a
2629
+ // mark is known only from having been shown them, so a session that never was, a fresh one
2630
+ // or a subagent, gets them whatever it does. A mark that is not theirs, since they changed
2631
+ // or it is of another project's, gets them whole again, and is told so first. The line that
2632
+ // answers a mark stands directly after the run's ids, before the task: a take is cut at its
2633
+ // head by a session that holds the rules, and a rule that changed is what such a cut must
2634
+ // not lose. Without a mark nothing is said there, and the rules follow the task as before.
2635
+ const language = readingLanguage(me);
2636
+ const mark = rulesMark(rules, language);
2637
+ const held = text(values, "rules")?.trim().toLowerCase();
2638
+ const answered = held === undefined ? [] : [held === mark ? formatRulesLeftOut(mark) : formatRulesChanged(held)];
2639
+ const ruled = held === mark ? [] : [formatRules(rules, language), ""];
2640
+ const page = await taskPage(session, taken.number);
2641
+ return {
2642
+ value: { run, task: taken, comments: comments.items, rules: { ...rules, mark } },
2643
+ words: () => [
2644
+ `Run ${run.id} began on #${found.number} ${found.title}, as "${run.agent}" for ${calledOf(run.person)}. The task is in progress and theirs.${tookOver}${elsewhere}`,
2645
+ // The ids on a line of their own, each named: a run's and a task's begin alike, and a
2646
+ // task has a number for people as well.
2647
+ `run id: ${run.id} task id: ${found.id} (task #${found.number})`,
2648
+ ...answered,
2649
+ "",
2650
+ formatTask(taken, undefined, undefined, comments.items, page),
2651
+ "",
2652
+ ...ruled,
2653
+ 'Say how it goes: console report "<what you found or did>". Hand in what you make: console hand-in <https url | file path>.',
2654
+ 'Ask when a person must decide: console ask "<question>" --option "..." --option "...". A word for the task\'s people that is not a report: console comment <number> "<markdown>". End with: console finish --summary "<what was done, what is left>".',
2655
+ ].join("\n"),
2656
+ };
2657
+ }
2658
+ const take = async (args, io) => {
2659
+ const { values, positionals } = parse(args, {
2660
+ agent: { type: "string" },
2661
+ rules: { type: "string" },
2662
+ });
2663
+ const ref = theOne(positionals, "Say which task: console take <number|id> [--rules <mark>]");
2664
+ const session = await open(io, values);
2665
+ const project = await session.project();
2666
+ const found = await project.task(ref);
2667
+ const run = await runOn(project, found, values);
2668
+ const took = await taking(session, project, found, ref, run, values);
2669
+ answer(io, session, took.value, took.words);
2081
2670
  return EXIT.ok;
2082
2671
  };
2083
2672
  const report = async (args, io) => {
@@ -2094,7 +2683,7 @@ const report = async (args, io) => {
2094
2683
  }
2095
2684
  const session = await open(io, values);
2096
2685
  const project = await session.project();
2097
- const runId = await currentRun(project, values);
2686
+ const runId = await currentRun(session, project, values);
2098
2687
  const run = await project.report(runId, { body });
2099
2688
  answer(io, session, run, () => `Reported on run ${run.id}: ${run.reports.length} report${run.reports.length === 1 ? "" : "s"} so far.`);
2100
2689
  return EXIT.ok;
@@ -2128,7 +2717,7 @@ const handIn = async (args, io) => {
2128
2717
  const label = text(values, "label");
2129
2718
  const session = await open(io, values);
2130
2719
  const project = await session.project();
2131
- const runId = await currentRun(project, values);
2720
+ const runId = await currentRun(session, project, values);
2132
2721
  // A URL is handed in as a link, and the console says whether it takes it; anything else
2133
2722
  // names a file on this machine.
2134
2723
  if (/^[a-z][a-z0-9+.-]*:\/\//i.test(what)) {
@@ -2185,7 +2774,7 @@ const ask = async (args, io) => {
2185
2774
  const files = await attachmentsOf(io, texts(values, "attach"));
2186
2775
  const session = await open(io, values);
2187
2776
  const project = await session.project();
2188
- const runId = await currentRun(project, values);
2777
+ const runId = await currentRun(session, project, values);
2189
2778
  // Whom the decision is for (ADR-0042, ADR-0057): the person the agent works for, unless --to
2190
2779
  // names others of the project, each once; several, and any of them may answer.
2191
2780
  const deciderIds = [];
@@ -2207,11 +2796,25 @@ const ask = async (args, io) => {
2207
2796
  : { deciderId: deciderIds[0], deciderIds }),
2208
2797
  }, files);
2209
2798
  const withFiles = files.length === 0 ? "" : `, with ${files.length} file${files.length === 1 ? "" : "s"}`;
2210
- // The id is printed before any waiting, so that a wait cut short loses nothing.
2799
+ // The id is printed before any waiting, so that a wait cut short loses nothing; and the
2800
+ // address of its page, which is what a person told of the decision is given to open.
2211
2801
  io.stdout(session.json
2212
2802
  ? `${JSON.stringify(raised, null, 2)}\n`
2213
- : `Decision ${raised.id} raised on run ${runId}${withFiles}; the run waits for ${deciderLogins(raised)}.\ndecision id: ${raised.id}\n${formatOptions(raised)}\n`);
2214
- return settle(io, session, project, raised, seconds, true);
2803
+ : `Decision ${raised.id} raised on run ${runId}${withFiles}; the run waits for ${deciderLogins(raised)}.\ndecision id: ${raised.id}\n${pageLine(await decisionPage(session, raised.id))}\n${formatOptions(raised)}\n`);
2804
+ // An agent account is attended by nobody, and the answer wakes it (ADR-0085): it waits at no
2805
+ // terminal unless it asked to, and is told to go on with other work, where an attended
2806
+ // agent is told how to keep waiting. A wait it asked for that runs out ends in the same
2807
+ // words: waiting on is not what it is told to do then either.
2808
+ const wakes = raised.raisedBy.kind === "agent"
2809
+ ? `The answer wakes you: go on with other work meanwhile, and with this run when it comes (--run ${runId}). The run stays open while the decision waits.`
2810
+ : undefined;
2811
+ if (wakes !== undefined && text(values, "wait") === undefined) {
2812
+ if (!session.json) {
2813
+ io.stdout(`${wakes}\n`);
2814
+ }
2815
+ return EXIT.waiting;
2816
+ }
2817
+ return settle(io, session, project, raised, seconds, true, wakes);
2215
2818
  };
2216
2819
  /**
2217
2820
  * Writes a person's answer on a decision, in their name through the agent (ADR-0021): the
@@ -2237,7 +2840,8 @@ const answering = async (args, io) => {
2237
2840
  ...(own === undefined ? { option } : { own }),
2238
2841
  ...(note === undefined ? {} : { note }),
2239
2842
  });
2240
- answer(io, session, answered, () => formatDecision(answered, { atItsAddress }));
2843
+ const page = await decisionPage(session, answered.id, atItsAddress);
2844
+ answer(io, session, answered, () => formatDecision(answered, { atItsAddress, page }));
2241
2845
  return EXIT.ok;
2242
2846
  };
2243
2847
  /** Whether a refusal says the decision is not in the project the command works in, or the project is not the person's. */
@@ -2280,6 +2884,27 @@ async function reachDecision(session, id) {
2280
2884
  throw error;
2281
2885
  }
2282
2886
  }
2887
+ /**
2888
+ * The project a write on a decision goes to: the one the command works in; where none is named,
2889
+ * the decision's own, as the console says it of the decision wherever it is (ADR-0068). A desk
2890
+ * names no project, and the wake that brings an answer names the decision alone: what followed
2891
+ * is written from there as the decision was read from there. With a project named nothing is
2892
+ * looked up, and the console answers for that project as before.
2893
+ */
2894
+ async function projectOfDecision(session, id) {
2895
+ if ((await session.projectKey()) !== undefined) {
2896
+ return session.project();
2897
+ }
2898
+ try {
2899
+ return session.client.project((await session.client.decision(id)).project.key);
2900
+ }
2901
+ catch (error) {
2902
+ if (error instanceof ApiError && error.status === 404) {
2903
+ throw new ApiError(404, "decision.not_found", "The decision was not found.");
2904
+ }
2905
+ throw error;
2906
+ }
2907
+ }
2283
2908
  /** Writes an answer on a decision as the command reaches it (ADR-0068): in the project, else wherever it is. */
2284
2909
  async function answerReached(session, id, input) {
2285
2910
  if ((await session.projectKey()) !== undefined) {
@@ -2329,7 +2954,7 @@ const decision = async (args, io) => {
2329
2954
  if (tos.length > 0) {
2330
2955
  // Whom a decision that waits is for, said anew (ADR-0096): the people named take the place
2331
2956
  // of those it was for, each once in the order named.
2332
- const project = await session.project();
2957
+ const project = await projectOfDecision(session, id);
2333
2958
  const deciderIds = [];
2334
2959
  for (const to of tos) {
2335
2960
  const named = await personIdOf(session, to);
@@ -2338,22 +2963,33 @@ const decision = async (args, io) => {
2338
2963
  }
2339
2964
  }
2340
2965
  const addressed = await project.addressDecision(id, deciderIds);
2341
- answer(io, session, addressed, () => formatDecision(addressed));
2966
+ const page = await decisionPage(session, addressed.id);
2967
+ answer(io, session, addressed, () => formatDecision(addressed, { page }));
2342
2968
  return EXIT.ok;
2343
2969
  }
2344
2970
  if (outcome !== undefined) {
2345
2971
  // What followed the decision: the record grows, and is printed as it stands.
2346
- const project = await session.project();
2972
+ const project = await projectOfDecision(session, id);
2347
2973
  const grown = await project.updateDecision(id, { outcome });
2348
- answer(io, session, grown, () => formatDecision(grown));
2974
+ const page = await decisionPage(session, grown.id);
2975
+ answer(io, session, grown, () => formatDecision(grown, { page }));
2349
2976
  return EXIT.ok;
2350
2977
  }
2351
2978
  const { decision: found, waiter, atItsAddress } = await reachDecision(session, id);
2352
2979
  if (seconds === 0) {
2353
- answer(io, session, found, () => formatDecision(found, { atItsAddress }));
2980
+ const page = await decisionPage(session, found.id, atItsAddress);
2981
+ answer(io, session, found, () => formatDecision(found, { atItsAddress, page }));
2354
2982
  return EXIT.ok;
2355
2983
  }
2356
- return settle(io, session, waiter, found, seconds);
2984
+ // An agent account is attended by nobody, and the answer to a decision it raised wakes it
2985
+ // (ADR-0085): a wait of its own that runs out ends in the account's words, as ask's does, and
2986
+ // not in how an attended agent waits on. Whether the command is the account is what the
2987
+ // login kept says (`login --self`), since the decision alone does not: a person's agent may
2988
+ // wait for a decision an account raised, and is told how to keep waiting.
2989
+ const wakes = signedInAsItself(session) && found.raisedBy.login === session.account
2990
+ ? `Decision ${found.id} still waits for a person. The answer wakes you: go on with other work meanwhile, and with its run when it comes${found.run === null ? "" : ` (--run ${found.run.id})`}. The run stays open while the decision waits.`
2991
+ : undefined;
2992
+ return settle(io, session, waiter, found, seconds, false, wakes);
2357
2993
  };
2358
2994
  const docs = async (args, io) => {
2359
2995
  const { values, positionals } = parse(args, {
@@ -2366,8 +3002,10 @@ const docs = async (args, io) => {
2366
3002
  const search = text(values, "search");
2367
3003
  const session = await open(io, values);
2368
3004
  const project = await session.project();
3005
+ // A folder is taken as the listing prints it, `guides/`, and as it is named, `guides`.
3006
+ const folder = positionals[0]?.replace(/\/+$/, "");
2369
3007
  const found = await project.documents({
2370
- ...(positionals[0] === undefined ? {} : { folder: positionals[0] }),
3008
+ ...(folder === undefined || folder === "" ? {} : { folder }),
2371
3009
  ...(search === undefined ? {} : { q: search }),
2372
3010
  ...(on(values, "archived") ? { archived: true } : {}),
2373
3011
  });
@@ -2438,7 +3076,10 @@ const write = async (args, io) => {
2438
3076
  body,
2439
3077
  ...(baseVersion === undefined ? {} : { baseVersion }),
2440
3078
  });
2441
- answer(io, session, written, () => `Wrote ${written.path} (${written.title}), version ${written.version}${written.links.length === 0 ? "" : `; refers to ${written.links.map((link) => link.path).join(", ")}`}`);
3079
+ // The page's address, as a task's and a decision's: what an agent tells a person and hands in.
3080
+ const key = await session.projectKey();
3081
+ const page = key === undefined ? undefined : `${session.url}${docHref(key, written.path)}`;
3082
+ answer(io, session, written, () => `Wrote ${written.path} (${written.title}), version ${written.version}${written.links.length === 0 ? "" : `; refers to ${written.links.map((link) => link.path).join(", ")}`}${page === undefined ? "" : `\n${pageLine(page)}`}`);
2442
3083
  return EXIT.ok;
2443
3084
  };
2444
3085
  const attach = async (args, io) => {
@@ -2587,7 +3228,9 @@ const goal = async (args, io) => {
2587
3228
  const session = await open(io, values);
2588
3229
  const project = await session.project();
2589
3230
  const found = await project.goal(id);
2590
- const towards = await project.tasks({ goal: found.id });
3231
+ const towards = session.json
3232
+ ? await project.tasks({ goal: found.id })
3233
+ : await project.taskBriefs({ goal: found.id });
2591
3234
  answer(io, session, { goal: found, tasks: towards.items }, () => formatGoal(found, towards.items));
2592
3235
  return EXIT.ok;
2593
3236
  };
@@ -2623,19 +3266,40 @@ const decisions = async (args, io) => {
2623
3266
  formatMore(found.more, page.limit, page.offset));
2624
3267
  return EXIT.ok;
2625
3268
  };
3269
+ /**
3270
+ * Says how a run ended, and where that left its task (ADR-0114). The console places the task,
3271
+ * and where is not the command's to know: a finished run leaves it at work where another run is
3272
+ * open on it, and a run that failed or was given up does that too, and on a console of before
3273
+ * 0.5.1 always, or where a person moved it meanwhile. So the task is read once the run is over, and its state said as it stands. On
3274
+ * `--json` the answer is the run as the console gave it, and nothing more is asked.
3275
+ */
3276
+ async function sayEnded(io, session, project, run, status) {
3277
+ let words = "";
3278
+ if (!session.json) {
3279
+ try {
3280
+ const task = await project.task(run.taskId);
3281
+ words = `Run ${run.id} ${status}; task #${task.number} is ${task.state} now.`;
3282
+ }
3283
+ catch (error) {
3284
+ // Said before the console's own words for what failed, which follow as on any command:
3285
+ // the run is over whatever became of the reading, and is not to be ended again.
3286
+ io.stderr(`Run ${run.id} ${status}, and where that left task #${run.taskNumber} was not read. The run is over: do not end it again. console task ${run.taskNumber} shows the task. What the reading ended on:\n`);
3287
+ throw error;
3288
+ }
3289
+ }
3290
+ answer(io, session, run, () => words);
3291
+ }
2626
3292
  const ending = (status) => async (args, io) => {
2627
3293
  const { values } = parse(args, { summary: { type: "string" }, file: { type: "string" }, run: { type: "string" } }, false);
2628
3294
  const summary = await bodyOf(io, values, text(values, "summary"));
2629
3295
  const session = await open(io, values);
2630
3296
  const project = await session.project();
2631
- const runId = await currentRun(project, values);
3297
+ const runId = await currentRun(session, project, values);
2632
3298
  const run = await project.endRun(runId, {
2633
3299
  status,
2634
3300
  ...(summary === undefined ? {} : { summary }),
2635
3301
  });
2636
- answer(io, session, run, () => status === "finished"
2637
- ? `Run ${run.id} finished; the task is up for review.`
2638
- : `Run ${run.id} failed; the task stays as it is.`);
3302
+ await sayEnded(io, session, project, run, status);
2639
3303
  return EXIT.ok;
2640
3304
  };
2641
3305
  const abandon = async (args, io) => {
@@ -2650,12 +3314,12 @@ const abandon = async (args, io) => {
2650
3314
  const summary = await bodyOf(io, values, text(values, "summary"));
2651
3315
  const session = await open(io, values);
2652
3316
  const project = await session.project();
2653
- const runId = positionals[0] ?? (await currentRun(project, values));
3317
+ const runId = positionals[0] ?? (await currentRun(session, project, values));
2654
3318
  const run = await project.endRun(runId, {
2655
3319
  status: "abandoned",
2656
3320
  ...(summary === undefined ? {} : { summary }),
2657
3321
  });
2658
- answer(io, session, run, () => `Run ${run.id} abandoned; the task stays as it is.`);
3322
+ await sayEnded(io, session, project, run, "abandoned");
2659
3323
  return EXIT.ok;
2660
3324
  };
2661
3325
  const runs = async (args, io) => {
@@ -2670,17 +3334,46 @@ const runs = async (args, io) => {
2670
3334
  const project = await session.project();
2671
3335
  const ref = text(values, "task");
2672
3336
  const taskId = ref === undefined ? undefined : (await project.task(ref)).id;
2673
- const found = await project.runs({
3337
+ const mine = on(values, "mine");
3338
+ const filter = {
2674
3339
  ...(taskId === undefined ? {} : { task: taskId }),
2675
3340
  ...(on(values, "open") ? { open: true } : {}),
2676
- ...(on(values, "mine") ? { mine: true } : {}),
3341
+ ...(mine ? { mine: true } : {}),
2677
3342
  ...page,
3343
+ };
3344
+ const [found, agent] = await Promise.all([
3345
+ // A line a run, its reports counted: the brief form, unless --json asks for the console's own.
3346
+ session.json ? project.runs(filter) : project.runBriefs(filter),
3347
+ // With a token, --mine is the runs begun with that token, one agent's, and a person may
3348
+ // have more: an empty listing would read as if they had none, so whose these are is said.
3349
+ mine && !session.json ? tokenNameOf(session) : undefined,
3350
+ ]);
3351
+ const others = "A run of yours begun through another agent, or before a new sign-in, is listed without --mine, where each line says whom it is for and through which agent.";
3352
+ answer(io, session, found, () => {
3353
+ if (found.items.length === 0) {
3354
+ return agent === undefined
3355
+ ? "No runs."
3356
+ : `No runs begun through this agent (${agent}). ${others}`;
3357
+ }
3358
+ const listed = found.items.map(formatRunLine).join("\n") + formatMore(found.more, page.limit, page.offset);
3359
+ return agent === undefined
3360
+ ? listed
3361
+ : `${listed}\nThese are the runs begun through this agent (${agent}). ${others}`;
2678
3362
  });
2679
- answer(io, session, found, () => found.items.length === 0
2680
- ? "No runs."
2681
- : found.items.map(formatRunLine).join("\n") + formatMore(found.more, page.limit, page.offset));
2682
3363
  return EXIT.ok;
2683
3364
  };
3365
+ /** What the token the command acts with is called, or nothing where it acts on a session or cannot be asked. */
3366
+ async function tokenNameOf(session) {
3367
+ try {
3368
+ return (await session.client.me()).agent ?? undefined;
3369
+ }
3370
+ catch (error) {
3371
+ if (error instanceof ApiError) {
3372
+ return undefined;
3373
+ }
3374
+ throw error;
3375
+ }
3376
+ }
2684
3377
  const run = async (args, io) => {
2685
3378
  const { values, positionals } = parse(args, {});
2686
3379
  const id = theOne(positionals, "Say which run: console run <id>");
@@ -2703,12 +3396,16 @@ function portOf(value) {
2703
3396
  }
2704
3397
  /**
2705
3398
  * A console of the person's own, served from this machine (ADR-0014): the build's pages here,
2706
- * and everything under /api/ carried to the console with the token, which the pages never see.
3399
+ * and everything under /api/ carried to the console with the token, which the pages never see;
3400
+ * and, with --records, what a desk keeps under /records/ (ADR-0117), for the desk's pages.
2707
3401
  */
2708
3402
  const serve = async (args, io) => {
2709
- const { values, positionals } = parse(args, { port: { type: "string" } });
3403
+ const { values, positionals } = parse(args, {
3404
+ port: { type: "string" },
3405
+ records: { type: "string" },
3406
+ });
2710
3407
  if (positionals.length > 1) {
2711
- throw misuse("Say at most one directory: console serve [<dir>] [--port <n>]");
3408
+ throw misuse("Say at most one directory: console serve [<dir>] [--port <n>] [--records <dir>]");
2712
3409
  }
2713
3410
  const [dir] = positionals;
2714
3411
  const port = portOf(text(values, "port"));
@@ -2734,16 +3431,41 @@ const serve = async (args, io) => {
2734
3431
  throw error;
2735
3432
  }
2736
3433
  }
3434
+ const kept = text(values, "records");
3435
+ let records;
3436
+ if (kept !== undefined) {
3437
+ try {
3438
+ records = await loadRecordsRoot(kept);
3439
+ }
3440
+ catch (error) {
3441
+ if (error instanceof RecordsRootError) {
3442
+ throw failed(`No records to serve: ${error.message}. Name the records/ of a desk: console serve <dir> --records <desk>/records`);
3443
+ }
3444
+ throw error;
3445
+ }
3446
+ }
3447
+ // Whether the records are there is asked before anything listens: the line says what the
3448
+ // command found when it began. Asked after, a directory made in the moment between, by a
3449
+ // session that began keeping something as the pages came up, read as there all along.
3450
+ const recordsThere = records === undefined ? false : await records.there();
2737
3451
  const listening = await listen((bound) => createServeHandler({
2738
3452
  upstream: session.url,
2739
3453
  token: session.token,
2740
3454
  fetch: io.fetch,
2741
3455
  port: bound,
2742
3456
  web,
3457
+ records,
2743
3458
  }), port);
3459
+ // A desk has its records/ once it keeps something (ADR-0122): until then the line says that
3460
+ // nothing is kept there, and that what comes to be is served with no restart.
3461
+ const served = kept === undefined || records === undefined
3462
+ ? ""
3463
+ : recordsThere
3464
+ ? ` The records in ${kept} are at ${listening.url}records/, read as they are when they are asked for.`
3465
+ : ` Nothing is kept in ${kept} yet: what comes to be kept there is at ${listening.url}records/ from then on, with no restart.`;
2744
3466
  io.stdout(web === undefined
2745
- ? `Serving the API of ${me.workspace.name} (${session.url}) at ${listening.url}api/ as ${person.login}, for a development server to send its /api/ requests to. Stop with Ctrl+C.\n`
2746
- : `Serving ${dir} at ${listening.url} as ${person.login}: the pages are there, and everything under /api/ goes to ${me.workspace.name} (${session.url}) with your token, which the pages never see. Stop with Ctrl+C.\n`);
3467
+ ? `Serving the API of ${me.workspace.name} (${session.url}) at ${listening.url}api/ as ${person.login}, for a development server to send its /api/ requests to.${served} Stop with Ctrl+C.\n`
3468
+ : `Serving ${dir} at ${listening.url} as ${person.login}: the pages are there, and everything under /api/ goes to ${me.workspace.name} (${session.url}) with your token, which the pages never see.${served} Stop with Ctrl+C.\n`);
2747
3469
  await listening.closed;
2748
3470
  return EXIT.ok;
2749
3471
  };
@@ -2789,6 +3511,41 @@ const machineLine = (text) => {
2789
3511
  .slice(0, MAX_RUNNER_LINE_LENGTH);
2790
3512
  return line.length === 0 ? "unknown" : line;
2791
3513
  };
3514
+ /**
3515
+ * Keeps a runner going across its `runner.json` (ADR-0144): a runner that ended for its file is
3516
+ * followed by another, begun with the file as it is now, in this process. Where the file stopped
3517
+ * reading in between, the agent having written it again in the turn that was under way, the next
3518
+ * runner begins with the file as it last read, so that there is always one: it then says what is
3519
+ * wrong with the file to the agent, whose session it is the only way to. Answers how the last
3520
+ * runner ended, once one ended for anything else or whoever runs the command asked it to stop.
3521
+ */
3522
+ export async function keepRunning(input) {
3523
+ let good = input.first;
3524
+ let running = input.start(good);
3525
+ let asked = false;
3526
+ void input.stopped.then(() => {
3527
+ asked = true;
3528
+ running.stop();
3529
+ });
3530
+ for (;;) {
3531
+ const how = await running.run();
3532
+ if (how !== "changed" || asked) {
3533
+ return how;
3534
+ }
3535
+ const next = await input.read();
3536
+ if (next.ok) {
3537
+ good = next.config;
3538
+ }
3539
+ else {
3540
+ input.say(`${next.problem}: the runner starts again with the runner.json it last read`);
3541
+ }
3542
+ running = input.start(good);
3543
+ // Asked to stop while the file was read: the runner just begun ends at once.
3544
+ if (asked) {
3545
+ running.stop();
3546
+ }
3547
+ }
3548
+ }
2792
3549
  // The runner of an agent account (ADR-0085, docs/specs/runner.md): started in the account's
2793
3550
  // desk, on the command signed in as the account itself. It keeps the agent's session going,
2794
3551
  // feeds it what the console sends and reports what it does, until it is stopped.
@@ -2809,22 +3566,35 @@ const runner = async (args, io) => {
2809
3566
  if (me.person.kind !== "agent" || me.session?.kind !== "command") {
2810
3567
  throw failed("A runner is an agent account's own, on the command signed in as the account itself: console login --self, approved in a browser signed in as the account.");
2811
3568
  }
2812
- const written = await host.readText("runner.json");
2813
- const read = written === undefined
2814
- ? { ok: true, config: DEFAULT_RUNNER_CONFIG }
2815
- : parseRunnerConfig(written);
2816
- if (!read.ok) {
2817
- throw failed(`${read.problem}. Nothing of it is used: put it right, or remove it to run with the defaults.`);
2818
- }
2819
3569
  const modules = ownRunnerModules({ user: host.user });
2820
- const driverOf = modules.drivers.get(read.config.driver);
2821
- if (driverOf === undefined) {
2822
- throw failed(`runner.json names the driver ${read.config.driver}, which this command does not have. It has: ${modules.drivers.names().join(", ")}.`);
2823
- }
2824
- const unknown = read.config.wake.find((name) => modules.wakeSources.get(name) === undefined);
2825
- if (unknown !== undefined) {
2826
- throw failed(`runner.json names the wake source ${unknown}, which this command does not have. It has: ${modules.wakeSources.names().join(", ")}.`);
2827
- }
3570
+ /**
3571
+ * The desk's runner.json as it stands: its text, what it says, and the driver it names; or
3572
+ * what is wrong with it in a few words. No file is the defaults.
3573
+ */
3574
+ const readConfig = async () => {
3575
+ const written = await host.readText("runner.json");
3576
+ const parsed = written === undefined
3577
+ ? { ok: true, config: DEFAULT_RUNNER_CONFIG }
3578
+ : parseRunnerConfig(written);
3579
+ if (!parsed.ok) {
3580
+ return { ok: false, problem: parsed.problem };
3581
+ }
3582
+ const driverOf = modules.drivers.get(parsed.config.driver);
3583
+ if (driverOf === undefined) {
3584
+ return {
3585
+ ok: false,
3586
+ problem: `runner.json names the driver ${parsed.config.driver}, which this command does not have. It has: ${modules.drivers.names().join(", ")}`,
3587
+ };
3588
+ }
3589
+ const unknown = parsed.config.wake.find((name) => modules.wakeSources.get(name) === undefined);
3590
+ if (unknown !== undefined) {
3591
+ return {
3592
+ ok: false,
3593
+ problem: `runner.json names the wake source ${unknown}, which this command does not have. It has: ${modules.wakeSources.names().join(", ")}`,
3594
+ };
3595
+ }
3596
+ return { ok: true, config: parsed.config, driverOf, text: written ?? "" };
3597
+ };
2828
3598
  // A header says the hour and the minute in the workspace's zone, or the machine's where it has none.
2829
3599
  const zone = me.workspace.timeZone ?? undefined;
2830
3600
  let clock;
@@ -2844,70 +3614,100 @@ const runner = async (args, io) => {
2844
3614
  });
2845
3615
  }
2846
3616
  const statePath = workPath("runner-state.json");
2847
- const running = createRunner({
2848
- client: session.client,
2849
- driver: driverOf({
2850
- spawn: host.spawn,
2851
- cwd: host.cwd,
2852
- command: read.config.product?.command,
2853
- args: read.config.product?.args,
2854
- version: io.version,
2855
- }),
2856
- config: read.config,
2857
- cwd: host.cwd,
2858
- machine: {
2859
- name: machineLine(io.hostname ?? ""),
2860
- os: machineLine(host.os),
2861
- user: machineLine(modules.boundaries.get("os-user")?.user() ?? host.user),
2862
- },
2863
- version: io.version ?? "0.0.0",
2864
- // A runner whose own version is not known has nothing to hold the package's against.
2865
- installed: io.version === undefined ? undefined : io.installedVersion,
2866
- // What installs the console's version here, the way this command was installed.
2867
- updateCommand: () => updateWords(io, io.consoleVersion?.()),
2868
- now: io.now,
2869
- random: host.random,
2870
- time: (iso) => clock.format(new Date(iso)),
2871
- files: {
2872
- write: (path, text) => host.writePrivate(workPath(path), text),
2873
- remove: (path) => host.remove(workPath(path)),
2874
- },
2875
- state: {
2876
- load: async () => runnerStateOf(await host.readText(statePath)),
2877
- save: (state) => host.writePrivate(statePath, `${JSON.stringify(state)}\n`),
2878
- },
2879
- log: (line) => io.stdout(`${new Date(io.now()).toISOString()} ${line}\n`),
2880
- // The autosave's git: in the desk, asking nobody at a terminal, its words read and let go.
2881
- // A step that reaches the git host is handed the account's token for it, as the clone of
2882
- // the desk was: answered from the environment of that one command, and only to the host
2883
- // the workspace keeps its desks at.
2884
- git: async (args, handed) => {
2885
- const origin = gitOriginOf(deskRemoteOf(me.workspace, me.person?.handle ?? ""));
2886
- const child = host.spawn("git", args, {
3617
+ const person = me.person;
3618
+ /** A runner for the desk's runner.json as it is read now: begun again whenever the file changed (ADR-0144). */
3619
+ const runnerOf = (read) => {
3620
+ const { driverOf } = read;
3621
+ return createRunner({
3622
+ client: session.client,
3623
+ driver: driverOf({
3624
+ spawn: host.spawn,
2887
3625
  cwd: host.cwd,
2888
- env: handed?.token === undefined || origin === undefined
2889
- ? { GIT_TERMINAL_PROMPT: "0" }
2890
- : gitTokenEnv(handed.token, origin),
2891
- });
2892
- child.end();
2893
- for await (const _ of child.lines) {
2894
- // Nothing of what git prints is kept.
2895
- }
2896
- return (await child.exited).code;
2897
- },
2898
- // The wake sources the desk names beside the console's own stream, which the runner listens to itself.
2899
- wakes: {
2900
- sources: read.config.wake.flatMap((name) => {
2901
- const source = modules.wakeSources.get(name);
2902
- return source === undefined || source.run === undefined ? [] : [source];
3626
+ command: read.config.product?.command,
3627
+ args: read.config.product?.args,
3628
+ version: io.version,
2903
3629
  }),
2904
- fetch: (url, init) => io.fetch(url, { ...init, headers: { ...init.headers } }),
2905
- socket: (url) => host.socket(url),
3630
+ config: read.config,
3631
+ reconfigured: async () => {
3632
+ const now = await readConfig();
3633
+ return !now.ok ? { problem: now.problem } : now.text === read.text ? "same" : "changed";
3634
+ },
3635
+ cwd: host.cwd,
3636
+ machine: {
3637
+ name: machineLine(io.hostname ?? ""),
3638
+ os: machineLine(host.os),
3639
+ user: machineLine(modules.boundaries.get("os-user")?.user() ?? host.user),
3640
+ },
3641
+ version: io.version ?? "0.0.0",
3642
+ // A runner whose own version is not known has nothing to hold the package's against.
3643
+ installed: io.version === undefined ? undefined : io.installedVersion,
3644
+ // What installs the console's version here, the way this command was installed.
3645
+ updateCommand: () => updateWords(io, io.consoleVersion?.()),
3646
+ now: io.now,
3647
+ random: host.random,
3648
+ time: (iso) => clock.format(new Date(iso)),
3649
+ files: {
3650
+ write: (path, text) => host.writePrivate(workPath(path), text),
3651
+ remove: (path) => host.remove(workPath(path)),
3652
+ },
3653
+ state: {
3654
+ load: async () => runnerStateOf(await host.readText(statePath)),
3655
+ save: (state) => host.writePrivate(statePath, `${JSON.stringify(state)}\n`),
3656
+ },
3657
+ log: (line) => io.stdout(`${new Date(io.now()).toISOString()} ${line}\n`),
3658
+ // The autosave's git: in the desk, asking nobody at a terminal, its words read and let go.
3659
+ // A step that reaches the git host is handed the account's token for it, as the clone of
3660
+ // the desk was: answered from the environment of that one command, and only to the host
3661
+ // the workspace keeps its desks at.
3662
+ git: async (args, handed) => {
3663
+ const origin = gitOriginOf(deskRemoteOf(me.workspace, me.person?.handle ?? ""));
3664
+ const child = host.spawn("git", args, {
3665
+ cwd: host.cwd,
3666
+ env: handed?.token === undefined || origin === undefined
3667
+ ? { GIT_TERMINAL_PROMPT: "0" }
3668
+ : gitTokenEnv(handed.token, origin),
3669
+ });
3670
+ child.end();
3671
+ for await (const _ of child.lines) {
3672
+ // Nothing of what git prints is kept.
3673
+ }
3674
+ return (await child.exited).code;
3675
+ },
3676
+ // The wake sources the desk names beside the console's own stream, which the runner listens to itself.
3677
+ wakes: {
3678
+ sources: read.config.wake.flatMap((name) => {
3679
+ const source = modules.wakeSources.get(name);
3680
+ return source === undefined || source.run === undefined ? [] : [source];
3681
+ }),
3682
+ fetch: (url, init) => io.fetch(url, { ...init, headers: { ...init.headers } }),
3683
+ socket: (url) => host.socket(url),
3684
+ },
3685
+ });
3686
+ };
3687
+ const first = await readConfig();
3688
+ if (!first.ok) {
3689
+ throw failed(`${first.problem}. Nothing of it is used: put it right, or remove it to run with the defaults.`);
3690
+ }
3691
+ io.stdout(`The runner of @${person.handle ?? person.login} at ${me.workspace.name} (${session.url}) starts in ${host.cwd}. Stop with Ctrl+C.\n`);
3692
+ // The machine is held awake while the runner runs, where the system has a way that needs no
3693
+ // administrator (ADR-0140): said in the runner's own lines, either way.
3694
+ const said = (line) => io.stdout(`${new Date(io.now()).toISOString()} ${line}\n`);
3695
+ void host
3696
+ .keepAwake?.()
3697
+ .then((awake) => said("by" in awake
3698
+ ? `the machine is kept from sleeping while the runner runs (${awake.by})`
3699
+ : `the machine is not kept from sleeping by the runner (${awake.problem}): set it never to sleep when idle`));
3700
+ const how = await keepRunning({
3701
+ first,
3702
+ read: async () => {
3703
+ const next = await readConfig();
3704
+ return next.ok ? { ok: true, config: next } : next;
2906
3705
  },
3706
+ start: runnerOf,
3707
+ stopped: host.untilStopped(),
3708
+ say: said,
2907
3709
  });
2908
- io.stdout(`The runner of @${me.person.handle ?? me.person.login} at ${me.workspace.name} (${session.url}) starts in ${host.cwd}. Stop with Ctrl+C.\n`);
2909
- void host.untilStopped().then(() => running.stop());
2910
- if ((await running.run()) === "updated") {
3710
+ if (how === "updated") {
2911
3711
  // The service that keeps a runner starts it again whenever it ends; one started by hand is
2912
3712
  // started again by hand.
2913
3713
  io.stdout("The command was updated: the runner ended, and the service that keeps it starts it again with the new one. Started by hand: console runner\n");
@@ -3022,8 +3822,13 @@ const agentNew = async (args, io) => {
3022
3822
  formatAgentLine(made),
3023
3823
  made.person.invited === true
3024
3824
  ? host === "gh"
3025
- ? // A login at a git host goes to whoever registers it, and the console lets that one in.
3026
- `It is a member now, and work can be assigned to it. It signs in as ${made.person.login}: that account has to be the organization's own at the git host already, since until its first sign-in binds it here the console lets in whoever holds that login.`
3825
+ ? // A login at a git host goes to whoever registers it: what the first sign-in is held
3826
+ // to is said (ADR-0126), and by a console older than the answer, the login alone.
3827
+ made.firstSignIn === "account"
3828
+ ? `It is a member now, and work can be assigned to it. It signs in as ${made.person.login}: confirmed at the git host, so that account alone is let in as it, whatever it is called by then.`
3829
+ : made.firstSignIn === "member"
3830
+ ? `It is a member now, and work can be assigned to it. It signs in as ${made.person.login}: not confirmed, since the organization at the git host has no member called so, or could not be asked. It is let in once it is a member there, and nobody else is under that login.`
3831
+ : `It is a member now, and work can be assigned to it. It signs in as ${made.person.login}: ${made.firstSignIn === "login" ? "not confirmed, since this console reads no organization at the git host. That" : "that"} account has to be the organization's own at the git host already, since until its first sign-in binds it here the console lets in whoever holds that login.`
3027
3832
  : `It is a member now, and work can be assigned to it. It signs in as ${made.person.login}: that account is made at the provider before its machine is set up, and its first sign-in with it binds it here.`
3028
3833
  : `${made.person.login} is an agent account from now on, with everything it did.`,
3029
3834
  ...(made.onboarding === null || made.onboarding === undefined
@@ -3054,6 +3859,13 @@ async function secretValue(io, values, prompt) {
3054
3859
  }
3055
3860
  return value;
3056
3861
  }
3862
+ /**
3863
+ * The kind of git host the workspace names, where it names one: what a token for git is held to
3864
+ * the shape of. Asked for the secret that is one alone, since no other is held to a host's shape.
3865
+ */
3866
+ const gitHostFor = async (client, name) => name === GIT_TOKEN_SECRET
3867
+ ? ((await client.me().catch(() => undefined))?.workspace.services?.git?.kind ?? undefined)
3868
+ : undefined;
3057
3869
  const SECRET_FLAGS = {
3058
3870
  set: { type: "boolean" },
3059
3871
  remove: { type: "boolean" },
@@ -3085,11 +3897,13 @@ const secret = async (args, io) => {
3085
3897
  if (on(values, "set")) {
3086
3898
  const expiresOn = expiryOf(io, values);
3087
3899
  const value = await secretValue(io, values, `Value of ${name} (typed unseen; Enter ends it): `);
3900
+ const host = await gitHostFor(session.client, name);
3088
3901
  const kept = await session.client.setSecret(name, {
3089
3902
  value,
3090
3903
  ...(expiresOn === undefined ? {} : { expiresOn }),
3091
3904
  });
3092
- answer(io, session, kept, () => `Kept: ${formatSecretLine(kept)}`);
3905
+ const notes = secretNotes(name, value, host);
3906
+ answer(io, session, kept, () => [`Kept: ${formatSecretLine(kept)}`, ...notes].join("\n"));
3093
3907
  return EXIT.ok;
3094
3908
  }
3095
3909
  // The value alone, for whatever reads it next; the reading is on the account's record.
@@ -3103,7 +3917,21 @@ const agentSecrets = async (args, io) => {
3103
3917
  const { values, positionals } = parse(args, {});
3104
3918
  const handle = handleOf(theOne(positionals, "Say whose: console agent secrets <handle>"));
3105
3919
  const session = await open(io, values);
3106
- const found = await session.client.agentSecrets(handle);
3920
+ let found;
3921
+ try {
3922
+ found = await session.client.agentSecrets(handle);
3923
+ }
3924
+ catch (error) {
3925
+ // An account that asks for its own secrets by the supervisor's command is told which
3926
+ // command is its own, where the console's refusal says only whose this one is.
3927
+ if (error instanceof ApiError && error.code === "auth.forbidden") {
3928
+ const me = await session.client.me().catch(() => undefined);
3929
+ if (me?.person?.kind === "agent" && me.person.handle === handle) {
3930
+ throw failed(`auth.forbidden: console agent secrets is a supervisor's command, and you are @${handle} yourself. Your own store is read with console secrets, and one secret of it with console secret <name>.`);
3931
+ }
3932
+ }
3933
+ throw error;
3934
+ }
3107
3935
  answer(io, session, found, () => found.items.length === 0
3108
3936
  ? `@${handle} keeps no secret yet.`
3109
3937
  : found.items.map((item) => formatSecretLine(item)).join("\n"));
@@ -3121,11 +3949,125 @@ const agentSecret = async (args, io) => {
3121
3949
  }
3122
3950
  const expiresOn = expiryOf(io, values);
3123
3951
  const value = await secretValue(io, values, `Value of ${name} for @${handle} (typed unseen; Enter ends it): `);
3952
+ const host = await gitHostFor(session.client, name);
3124
3953
  const kept = await session.client.seedAgentSecret(handle, name, {
3125
3954
  value,
3126
3955
  ...(expiresOn === undefined ? {} : { expiresOn }),
3127
3956
  });
3128
- answer(io, session, kept, () => `Seeded for @${handle}, which alone reads it back: ${formatSecretLine(kept)}`);
3957
+ const notes = secretNotes(name, value, host);
3958
+ answer(io, session, kept, () => [`Seeded for @${handle}, which alone reads it back: ${formatSecretLine(kept)}`, ...notes].join("\n"));
3959
+ return EXIT.ok;
3960
+ };
3961
+ const OWN_WAKE_FLAGS = {
3962
+ file: { type: "string" },
3963
+ in: { type: "string" },
3964
+ at: { type: "string" },
3965
+ key: { type: "string" },
3966
+ cancel: { type: "boolean" },
3967
+ };
3968
+ const OWN_WAKE_USAGE = 'Say when, or nothing for now: console agent wake me ["<words>"] [--in <minutes> | --at <HH:MM>] [--key <name>] | agent wake me --cancel [--key <name>]';
3969
+ /** The hour and the minute it is in a time zone, as minutes of its day; in the machine's own where the zone names none. */
3970
+ function minutesOfDayIn(zone, now) {
3971
+ let parts;
3972
+ try {
3973
+ parts = new Intl.DateTimeFormat("en-GB", {
3974
+ hour: "2-digit",
3975
+ minute: "2-digit",
3976
+ hourCycle: "h23",
3977
+ ...(zone === undefined ? {} : { timeZone: zone }),
3978
+ }).formatToParts(now);
3979
+ }
3980
+ catch {
3981
+ parts = new Intl.DateTimeFormat("en-GB", {
3982
+ hour: "2-digit",
3983
+ minute: "2-digit",
3984
+ hourCycle: "h23",
3985
+ }).formatToParts(now);
3986
+ }
3987
+ const of = (type) => Number(parts.find((part) => part.type === type)?.value ?? "0");
3988
+ return of("hour") * 60 + of("minute");
3989
+ }
3990
+ /**
3991
+ * When a wake for later is raised, as the flags say it: so many minutes from now, or the next
3992
+ * time the workspace's clock says an hour and a minute; nothing where neither flag is given.
3993
+ */
3994
+ export function ownWakeMoment(given, zone, now) {
3995
+ if (given.in !== undefined && given.at !== undefined) {
3996
+ throw misuse(OWN_WAKE_USAGE);
3997
+ }
3998
+ if (given.in !== undefined) {
3999
+ const minutes = Number(given.in);
4000
+ if (!Number.isInteger(minutes) || minutes < 1 || minutes > MAX_OWN_WAKE_DAYS * 24 * 60) {
4001
+ throw misuse(`Not a number of minutes, from 1 to ${MAX_OWN_WAKE_DAYS * 24 * 60}: ${given.in}`);
4002
+ }
4003
+ return new Date(now.getTime() + minutes * 60_000);
4004
+ }
4005
+ if (given.at !== undefined) {
4006
+ const clock = /^([01]?[0-9]|2[0-3]):([0-5][0-9])$/.exec(given.at);
4007
+ if (clock === null) {
4008
+ throw misuse(`Not an hour and a minute, as 14:30: ${given.at}`);
4009
+ }
4010
+ const wanted = Number(clock[1]) * 60 + Number(clock[2]);
4011
+ // The next time the clock says so: later today, or tomorrow where that hour has passed.
4012
+ const day = 24 * 60;
4013
+ const ahead = (wanted - minutesOfDayIn(zone, now) + day) % day || day;
4014
+ const at = new Date(now.getTime() + ahead * 60_000);
4015
+ at.setSeconds(0, 0);
4016
+ // Where the zone's clock is put forward or back before then, the moment is off by that
4017
+ // much: moved by what the clock says there, once, where the clock then says the hour asked
4018
+ // for and the moment is still to come. An hour the clock skips that night is no hour of
4019
+ // that day: the moment stays the one counted, just past it.
4020
+ const off = ((wanted - minutesOfDayIn(zone, at) + day + day / 2) % day) - day / 2;
4021
+ const moved = new Date(at.getTime() + off * 60_000);
4022
+ return off !== 0 && moved.getTime() > now.getTime() && minutesOfDayIn(zone, moved) === wanted
4023
+ ? moved
4024
+ : at;
4025
+ }
4026
+ return undefined;
4027
+ }
4028
+ // A wake an agent account raises for itself (ADR-0145), by its own command: now, for whoever
4029
+ // prepared its machine or signed something in there to say so and for the agent to go on; or
4030
+ // kept for a moment to come, for an agent that has something to look at again.
4031
+ const ownWake = async (args, io) => {
4032
+ const { values, positionals } = parse(args, OWN_WAKE_FLAGS);
4033
+ const [, words, ...rest] = positionals;
4034
+ if (rest.length > 0) {
4035
+ throw misuse(OWN_WAKE_USAGE);
4036
+ }
4037
+ const key = text(values, "key");
4038
+ if (key !== undefined && !/^[a-z0-9][a-z0-9-]{0,39}$/.test(key)) {
4039
+ throw misuse(`Not a name for a wake, which is up to 40 lowercase letters, digits and hyphens: ${key}`);
4040
+ }
4041
+ const session = await open(io, values);
4042
+ /** A console of before knows no such route: said as what it is. */
4043
+ const asked = async (ask) => {
4044
+ try {
4045
+ return await ask();
4046
+ }
4047
+ catch (error) {
4048
+ if (error instanceof ApiError && error.status === 404 && error.code === "not_found") {
4049
+ throw failed("This console does not take an account's own wake yet: it does from 0.5.2 on.");
4050
+ }
4051
+ throw error;
4052
+ }
4053
+ };
4054
+ if (on(values, "cancel")) {
4055
+ const named = key ?? OWN_WAKE_KEY;
4056
+ await asked(() => session.client.cancelOwnWake(named));
4057
+ answer(io, session, { cancelled: named }, () => `The wake ${named} is taken away.`);
4058
+ return EXIT.ok;
4059
+ }
4060
+ const said = ((await bodyOf(io, values, words)) ?? "").trim();
4061
+ const me = await session.client.me();
4062
+ const at = ownWakeMoment({ in: text(values, "in"), at: text(values, "at") }, me.workspace.timeZone ?? undefined, new Date(io.now()));
4063
+ const raised = await asked(() => session.client.raiseOwnWake({
4064
+ ...(said.length === 0 ? {} : { text: said }),
4065
+ ...(at === undefined ? {} : { at: at.toISOString() }),
4066
+ ...(key === undefined ? {} : { key }),
4067
+ }));
4068
+ answer(io, session, raised, () => raised.kept === null
4069
+ ? `Raised, as signal #${raised.signal?.number ?? "?"} of your record: your runner takes it as it takes any wake.`
4070
+ : `Kept: ${formatOwnWakeLine(raised.kept)}\nTake it away: console agent wake me --cancel${raised.kept.key === OWN_WAKE_KEY ? "" : ` --key ${raised.kept.key}`}. A second under the same name takes its place.`);
3129
4071
  return EXIT.ok;
3130
4072
  };
3131
4073
  /** The kinds of signal a supervisor sends with words: which need them, and which take them. */
@@ -3142,6 +4084,20 @@ const WORDED_SIGNALS = {
3142
4084
  // with the same conversation or with a new one, a wake; in their own name, on the account's
3143
4085
  // record. What it says is given as words, or with --file, or on standard input as `-`.
3144
4086
  const agentSignal = async (kind, args, io) => {
4087
+ // An account's own wake is another command under the same word: console agent wake me,
4088
+ // wherever `me` stands among its flags.
4089
+ if (kind === "wake") {
4090
+ let whom;
4091
+ try {
4092
+ whom = parse(args, OWN_WAKE_FLAGS).positionals[0];
4093
+ }
4094
+ catch {
4095
+ whom = undefined;
4096
+ }
4097
+ if (whom === "me") {
4098
+ return ownWake(args, io);
4099
+ }
4100
+ }
3145
4101
  const { values, positionals } = parse(args, { file: { type: "string" } });
3146
4102
  const [given, words, ...rest] = positionals;
3147
4103
  const needs = WORDED_SIGNALS[kind]?.needs === true;
@@ -3211,10 +4167,19 @@ const agentSignals = async (args, io) => {
3211
4167
  ...(limit === undefined ? {} : { limit: Number(limit) }),
3212
4168
  ...(before === undefined ? {} : { before: Number(before) }),
3213
4169
  });
3214
- answer(io, session, found, () => found.items.length === 0
4170
+ // What the account keeps for later (ADR-0145) stands over the record's first page: it is no
4171
+ // signal yet. A console of before keeps none, and says nothing of it.
4172
+ const kept = before === undefined
4173
+ ? await session.client
4174
+ .ownWakes(handle)
4175
+ .then((wakes) => wakes.items)
4176
+ .catch(() => [])
4177
+ : [];
4178
+ answer(io, session, kept.length === 0 ? found : { ...found, kept }, () => found.items.length === 0 && kept.length === 0
3215
4179
  ? "No signal yet."
3216
4180
  : [
3217
- ...found.items.map(formatSignalLine),
4181
+ ...kept.map(formatOwnWakeLine),
4182
+ ...found.items.map((signal) => formatSignalLine(signal, found.delivered)),
3218
4183
  ...(found.more
3219
4184
  ? [
3220
4185
  `More before: console agent signals ${handle} --before ${found.items.at(-1)?.number}`,
@@ -3260,6 +4225,8 @@ const SETUP_FLAGS = {
3260
4225
  refresh: { type: "boolean" },
3261
4226
  "new-desk": { type: "boolean" },
3262
4227
  "no-service": { type: "boolean" },
4228
+ driver: { type: "string" },
4229
+ "no-browser": { type: "boolean" },
3263
4230
  };
3264
4231
  /** The end of what a program said, for a refusal to carry: one line, bounded. */
3265
4232
  function lastWords(ran) {
@@ -3342,7 +4309,9 @@ async function deskOf(machine, values) {
3342
4309
  * host where the account keeps the token that reads it there, which is an account that pushed a
3343
4310
  * desk before; written from the template otherwise, and no file that is there is written over.
3344
4311
  */
3345
- async function settleDesk(io, machine, client, person, workspace, url, values) {
4312
+ async function settleDesk(io, machine, client, person, workspace, url, values,
4313
+ /** What a look at the machine found, for a setup that looked: the driver and the browser a new desk names. */
4314
+ look) {
3346
4315
  const desk = await deskOf(machine, values);
3347
4316
  const handle = person.handle ?? "";
3348
4317
  if ((await machine.exists(machine.path(desk, "runner.json"))) ||
@@ -3365,6 +4334,7 @@ async function settleDesk(io, machine, client, person, workspace, url, values) {
3365
4334
  throw failed(`The desk could not be cloned from ${remote}: ${lastWords(cloned)}. Put that right and run this again; or begin a new desk here with --new-desk, where the account never pushed one.`);
3366
4335
  }
3367
4336
  io.stdout(`The desk is cloned from ${remote} into ${desk}.\n`);
4337
+ await settleDeskGit(io, machine, desk, url, person.login, deskRemoteOf(workspace, handle));
3368
4338
  return desk;
3369
4339
  }
3370
4340
  const written = [];
@@ -3372,6 +4342,14 @@ async function settleDesk(io, machine, client, person, workspace, url, values) {
3372
4342
  agent: { name: person.name ?? handle, handle, title: person.title ?? null },
3373
4343
  console: { url, workspace: workspace.name },
3374
4344
  services: deskServicesOf(workspace, handle),
4345
+ // The product found on the machine, and its browser: what the runner starts with.
4346
+ runner: look === undefined
4347
+ ? undefined
4348
+ : {
4349
+ ...DEFAULT_RUNNER_CONFIG,
4350
+ ...(look.driver === undefined ? {} : { driver: look.driver }),
4351
+ ...(look.browser === undefined ? {} : { browser: look.browser }),
4352
+ },
3375
4353
  })) {
3376
4354
  const file = machine.path(desk, path);
3377
4355
  if (!(await machine.exists(file))) {
@@ -3379,9 +4357,48 @@ async function settleDesk(io, machine, client, person, workspace, url, values) {
3379
4357
  written.push(path);
3380
4358
  }
3381
4359
  }
3382
- io.stdout(`A new desk is written at ${desk} (${written.join(", ")}). It is the agent's from now on: to edit, to make a repository of, and to push to its git host.\n`);
4360
+ io.stdout(`A new desk is written at ${desk} (${written.join(", ")}). It is the agent's from now on: to edit and to push to its git host.\n`);
4361
+ await settleDeskGit(io, machine, desk, url, person.login, deskRemoteOf(workspace, handle));
3383
4362
  return desk;
3384
4363
  }
4364
+ /**
4365
+ * The desk's own git settings (ADR-0140): a repository where it is none yet, and for the host
4366
+ * the workspace keeps its desks at, a credential helper that reads the account's token from its
4367
+ * store when git asks, in place of whatever the machine has configured. The agent then pushes
4368
+ * with nothing typed, and no copy of the token is left in a keychain or a file. Nothing where
4369
+ * the workspace names no git host, the command does not know how it was started, or git is not
4370
+ * there; what did not succeed is said and the setup goes on.
4371
+ */
4372
+ async function settleDeskGit(io, machine, desk, url, login, remote) {
4373
+ const origin = gitOriginOf(remote);
4374
+ if (origin === undefined || machine.self === undefined) {
4375
+ return;
4376
+ }
4377
+ const git = (args) => machine.run("git", ["-C", desk, ...args]);
4378
+ if (!(await machine.exists(machine.path(desk, ".git")))) {
4379
+ if ((await git(["init", "--quiet"])).code !== 0) {
4380
+ return;
4381
+ }
4382
+ }
4383
+ // The helper as git's own shell runs it: every word in single quotes, a path with its
4384
+ // slashes forward, which that shell takes on every system.
4385
+ const word = (text) => `'${text.replaceAll("\\", "/").replaceAll("'", "'\\''")}'`;
4386
+ const read = [...machine.self, "secret", GIT_TOKEN_SECRET, "--url", url, "--account", login]
4387
+ .map(word)
4388
+ .join(" ");
4389
+ const helper = `!f() { test "$1" = get && printf 'username=x-access-token\\npassword=%s\\n' "$(${read})"; }; f`;
4390
+ const key = `credential.${origin}.helper`;
4391
+ const kept = await git(["config", "--local", "--get-all", key]);
4392
+ if (kept.code === 0 && kept.out.includes(GIT_TOKEN_SECRET)) {
4393
+ return;
4394
+ }
4395
+ // An empty helper first: whatever the machine has configured for that host is left out.
4396
+ const cleared = await git(["config", "--local", "--replace-all", key, ""]);
4397
+ const added = cleared.code === 0 ? await git(["config", "--local", "--add", key, helper]) : cleared;
4398
+ io.stdout(added.code === 0
4399
+ ? `The desk's git reads the account's ${GIT_TOKEN_SECRET} from its store when ${origin} asks: nothing is typed, and no copy is kept elsewhere.\n`
4400
+ : `The desk's git was not set to read the account's token from its store (${lastWords(added)}); the agent hands it to git itself.\n`);
4401
+ }
3385
4402
  /**
3386
4403
  * The service that keeps the runner running (ADR-0085), by the module of this platform: its
3387
4404
  * files written and, for a first setup, its commands run; answers where the runner's own lines
@@ -3491,7 +4508,11 @@ async function signInAsAccount(io, machine, url, setup) {
3491
4508
  const opened = URL.canParse(begun.url) && new URL(begun.url).origin === url
3492
4509
  ? await machine.open(begun.url)
3493
4510
  : false;
3494
- io.stdout(`${opened ? `The page is opened in this machine's browser: ${begun.url}` : `Open ${begun.url} in this machine's browser`}. Sign in there as ${login}, check that the page shows the code ${begun.code}, and say that it is you. On a machine without a screen, open the address in any browser that is signed in as the account.\nWaiting for that, until ${begun.expiresAt}.\n`);
4511
+ // The end of the wait is a moment as any other the command prints (ADR-0035), as a login's
4512
+ // is: in the workspace's time zone where a login at this console kept it, as the API gave it
4513
+ // where none has.
4514
+ setMomentZone(credentials.logins.find((kept) => kept.url === url)?.timeZone);
4515
+ io.stdout(`${opened ? `The page is opened in this machine's browser: ${begun.url}` : `Open ${begun.url} in this machine's browser`}. Sign in there as ${login}, check that the page shows the code ${begun.code}, and say that it is you. On a machine without a screen, open the address in any browser that is signed in as the account.\nWaiting for that, until ${moment(begun.expiresAt)}.\n`);
3495
4516
  let secret;
3496
4517
  for (;;) {
3497
4518
  await io.sleep(begun.interval * 1000);
@@ -3528,11 +4549,48 @@ async function awaitRunner(io, client, handle, heardBefore, log) {
3528
4549
  const heard = found?.state?.heardAt ?? null;
3529
4550
  const said = found?.runner?.machine ?? null;
3530
4551
  if (heard !== null && heard !== heardBefore && said !== null) {
3531
- io.stdout(`The runner is heard from: ${said.name}, ${said.os}, OS account ${said.user}. @${handle} is set up on this machine, and its page shows it.\n`);
3532
- return;
4552
+ io.stdout(`The runner is heard from: ${said.name}, ${said.os}, OS account ${said.user}. @${handle} is set up on this machine.\n`);
4553
+ return true;
4554
+ }
4555
+ }
4556
+ io.stdout(`The runner is not heard from yet. Its own lines are in ${log}: read them, since they say what it lacks; the account's page says when it is heard from.\n`);
4557
+ return false;
4558
+ }
4559
+ /** How often, and how many times, a setup looks whether the agent's first session has begun. */
4560
+ const FIRST_SESSION_PAUSE_MS = 2000;
4561
+ const FIRST_SESSION_TRIES = 30;
4562
+ /**
4563
+ * What a setup ends with (ADR-0140): whether the agent's first session has begun, where to
4564
+ * watch it, and that the machine's part ends here, since everything after is the agent's own.
4565
+ */
4566
+ async function handOver(io, machine, client, url, handle,
4567
+ /** Where the runner's own lines are. */
4568
+ log) {
4569
+ let began = false;
4570
+ for (let tries = 0; tries < FIRST_SESSION_TRIES && !began; tries += 1) {
4571
+ const found = await client.agent(handle).catch(() => undefined);
4572
+ began = (found?.runner?.session ?? null) !== null;
4573
+ if (!began) {
4574
+ await io.sleep(FIRST_SESSION_PAUSE_MS);
3533
4575
  }
3534
4576
  }
3535
- io.stdout(`The runner is not heard from yet. Its own lines are in ${log}; the account's page says when it is.\n`);
4577
+ const plate = await client.work().catch(() => undefined);
4578
+ const first = plate?.tasks.find((one) => one.task.title === onboardingTitle(handle));
4579
+ const lines = [
4580
+ began
4581
+ ? `@${handle}'s session has begun: the agent is at work.`
4582
+ : `No session has begun yet: one begins when something wakes @${handle}.`,
4583
+ `Watch it: ${url}${agentHref(handle)}`,
4584
+ ...(first === undefined
4585
+ ? []
4586
+ : [
4587
+ `Its first task: #${first.task.number} "${first.task.title}" in ${first.project.key}, ${url}${taskHref(first.project.key, first.task.number)}`,
4588
+ ]),
4589
+ `That is the machine prepared: stop here. What comes next, its sign-ins, its tokens, its desk's repository, its profile and its messenger, is @${handle}'s own, done in its own session: do none of it for it.`,
4590
+ `What you change on this machine afterwards, say to it: console agent wake me "<what changed>"`,
4591
+ awakeWords(machine.platform, await heldAwake(machine), log),
4592
+ ];
4593
+ io.stdout(`${lines.join("\n")}\n`);
3536
4594
  }
3537
4595
  // Derives a machine again (ADR-0088): by the account's own command, in its desk, when the
3538
4596
  // services or the account changed. It writes what is missing of the desk and the service where
@@ -3605,21 +4663,212 @@ const agentSetup = async (args, io) => {
3605
4663
  }
3606
4664
  const { handle } = setup.account;
3607
4665
  io.stdout(`\nSetting this machine up for @${handle}, in the OS account ${machine.user}${io.hostname === undefined ? "" : ` on ${io.hostname}`}.\n`);
4666
+ // The machine first (ADR-0140): everything that is missing is said at once, before anyone is
4667
+ // asked to sign in, and nothing is set up on a machine the runner could not work on.
4668
+ const driver = text(values, "driver");
4669
+ if (driver !== undefined &&
4670
+ ownRunnerModules({ user: machine.user }).drivers.get(driver) === undefined) {
4671
+ throw misuse(`Not a driver this command has: ${driver}. It has: ${ownRunnerModules({ user: machine.user }).drivers.names().join(", ")}.`);
4672
+ }
4673
+ const look = await lookAtMachine(machine, { driver, browser: !on(values, "no-browser") });
4674
+ if (look.missing.length > 0) {
4675
+ throw failed(`This machine lacks what the setup needs. Install each yourself, without asking, and run the line again:\n${look.missing.map((line) => `- ${line}`).join("\n")}`);
4676
+ }
4677
+ io.stdout(`The machine has what the setup needs: git${look.product === undefined ? "" : `, ${look.product}`}${look.browser === undefined ? "" : ", Google Chrome"}.\n${look.notes.map((line) => `${line}\n`).join("")}`);
3608
4678
  const client = await signInAsAccount(io, machine, url, setup);
3609
4679
  const me = await client.me();
3610
4680
  if (me.person === null) {
3611
4681
  throw failed("The console does not know this sign-in any more. Run the line again.");
3612
4682
  }
3613
4683
  const heardBefore = (await client.agent(handle).catch(() => undefined))?.state?.heardAt ?? null;
3614
- const desk = await settleDesk(io, machine, client, me.person, me.workspace, url, values);
4684
+ const desk = await settleDesk(io, machine, client, me.person, me.workspace, url, values, look);
3615
4685
  if (on(values, "no-service")) {
3616
4686
  io.stdout(`No service is written, as asked. Start the runner yourself and keep it running: ${runnerByHand(desk, url, me.person.login, machine.platform)}\n`);
3617
4687
  return EXIT.ok;
3618
4688
  }
3619
4689
  const log = await settleService(io, machine, desk, url, me.person.login, "load");
3620
- if (log !== undefined) {
3621
- await awaitRunner(io, client, handle, heardBefore, log);
4690
+ if (log !== undefined && (await awaitRunner(io, client, handle, heardBefore, log))) {
4691
+ await handOver(io, machine, client, url, handle, log);
4692
+ }
4693
+ return EXIT.ok;
4694
+ };
4695
+ const DESK_USAGE = "Say at most one directory: console desk [<directory>] [--web]";
4696
+ /**
4697
+ * What is next in a new desk, in order, as a person says it to their agent there (ADR-0115,
4698
+ * ADR-0122): first the desk is set up as a repository, by the skill for that in the
4699
+ * organization's pack; then the person is asked what they want to keep and to see, and the
4700
+ * desk is shaped to it, by the skill the command ships, named with its place.
4701
+ */
4702
+ function deskNext(web, skillsDir) {
4703
+ return [
4704
+ `Set this desk up as a repository of mine${web ? " and bring its pages up" : ""}, with the skill for it in the organization's pack where it has one: console skills --search "desk setup" --limit 5`,
4705
+ `Ask me what I want to keep and to see here, and shape the desk to it, as the skill keeping-a-desk says, shipped with the console command${skillsDir === undefined ? " (console skills says where it is)" : `: ${ownSkillPath(skillsDir, "keeping-a-desk")}`}`,
4706
+ ];
4707
+ }
4708
+ /** The files of the shell of a desk's pages as they are written: the two words the template leaves filled in. */
4709
+ function deskWebFiles(template, version, title) {
4710
+ return [...template]
4711
+ .filter(([path]) => !path.split("/").some((part) => part === ".." || part.length === 0))
4712
+ .map(([path, body]) => [
4713
+ path,
4714
+ body.replaceAll("__VERSION__", version).replaceAll("__TITLE__", title),
4715
+ ]);
4716
+ }
4717
+ /** A count with its word, the word in the plural where the count is not one. */
4718
+ const counted = (count, one, many = `${one}s`) => `${count} ${count === 1 ? one : many}`;
4719
+ // The check of a desk's records (ADR-0117): every file under `records/` read as the format's
4720
+ // schemas read it, and each problem said with its file. It asks nothing of the console and
4721
+ // needs no sign-in: an agent that wrote a record runs it before it commits, and nobody needs
4722
+ // a page to know that the records are right.
4723
+ const deskCheck = async (args, io) => {
4724
+ const { values, positionals } = parse(args, {});
4725
+ if (positionals.length > 1) {
4726
+ throw misuse("Say at most one directory: console desk check [<directory>]");
4727
+ }
4728
+ const at = io.recordsAt?.(positionals[0] ?? ".");
4729
+ if (at === undefined) {
4730
+ throw failed("A desk's records cannot be read from here.");
4731
+ }
4732
+ const found = await checkRecords(at.files);
4733
+ if (on(values, "json")) {
4734
+ io.stdout(`${JSON.stringify({ directory: at.directory, ...found }, null, 2)}\n`);
4735
+ }
4736
+ else if (!found.found) {
4737
+ io.stdout(`No collection is kept in ${at.directory}: ${RECORDS_DIR}/${RECORDS_INDEX_FILE} is not there. What else is under ${RECORDS_DIR}/ is the desk's own shape, and not this check's to read. Where a collection is wanted, the skill keeping-a-desk says how one is kept (collections.md).\n`);
4738
+ }
4739
+ else {
4740
+ const kept = found.collections.map((one) => ` ${one.key}: ${counted(one.items, "item")}, ${counted(one.uses, "use")}, ${counted(one.metricRows, "row of figures", "rows of figures")}`);
4741
+ io.stdout([
4742
+ ...found.problems.map((one) => `${one.file}: ${one.problem}`),
4743
+ ...found.notes.map((one) => `note: ${one.file}: ${one.problem}`),
4744
+ ...(found.problems.length === 0
4745
+ ? [
4746
+ `The records in ${at.directory} read right: ${counted(found.collections.length, "collection")}.`,
4747
+ ]
4748
+ : found.collections.length === 0
4749
+ ? []
4750
+ : ["What reads:"]),
4751
+ ...kept,
4752
+ "",
4753
+ ].join("\n"));
4754
+ }
4755
+ if (found.problems.length > 0) {
4756
+ throw failed(`${counted(found.problems.length, "problem")} in the records of ${at.directory}. Mend the files and run this again.`);
4757
+ }
4758
+ return EXIT.ok;
4759
+ };
4760
+ // A person's desk (ADR-0115): its files, the least (ADR-0122), each only where no file of that
4761
+ // name is there, in `desk` here, as an agent account's is called, or the directory named; with
4762
+ // --web, the shell of the desk's pages in `web/`, where that holds nothing yet. The command
4763
+ // writes and stops, and its last lines say what is next, in order, for an agent to go on with:
4764
+ // making the desk a repository is a skill's, of the organization's pack, and shaping it to what
4765
+ // the person asks to keep and to see is the skill keeping-a-desk's, which the command ships.
4766
+ // An agent account's desk is setup's: for one, the command writes the shell alone, with --web,
4767
+ // into the desk it names.
4768
+ const desk = async (args, io) => {
4769
+ if (args[0] === "check") {
4770
+ return deskCheck(args.slice(1), io);
4771
+ }
4772
+ const { values, positionals } = parse(args, { web: { type: "boolean" } });
4773
+ if (positionals.length > 1) {
4774
+ throw misuse(DESK_USAGE);
3622
4775
  }
4776
+ const session = await open(io, values);
4777
+ const me = await session.client.me();
4778
+ const person = me.person;
4779
+ if (person === null) {
4780
+ throw failed("The console does not know this token. Sign in again: console login");
4781
+ }
4782
+ // An agent account's desk is setup's, and none of its own files is written here (ADR-0115).
4783
+ // The shell of its pages is the one thing this command writes for it, into the desk it names
4784
+ // (ADR-0122): a desk's pages are its member's, whichever kind of member that is.
4785
+ const ofAgent = person.kind === "agent";
4786
+ if (ofAgent && !on(values, "web")) {
4787
+ throw failed(`${whoOf(person)} is an agent account: its desk is settled by console agent setup, on its own machine, and nothing is written here. In that desk, console agent setup --refresh derives it again, and console desk . --web writes the shell of its pages.`);
4788
+ }
4789
+ const machine = io.machine;
4790
+ if (machine === undefined) {
4791
+ throw failed("A desk cannot be written from here.");
4792
+ }
4793
+ const [named] = positionals;
4794
+ // A desk made under a directory that works in a project would work in it too, and every
4795
+ // checkout under its work/ with it: what the folder above says, a desk must not inherit.
4796
+ const above = named === undefined || !isAbsolute(named) ? await io.directory.load() : undefined;
4797
+ if (above !== undefined) {
4798
+ throw failed(`This directory works in the project ${above.project} (${DIRECTORY_FILE} here or in a directory above), and a desk made inside it would work there too. A desk is bound to no project: make it elsewhere, console desk <directory>.`);
4799
+ }
4800
+ const dir = machine.path(named ?? DESK_FOLDER);
4801
+ if (ofAgent && !(await machine.exists(machine.path(dir, "AGENTS.md")))) {
4802
+ throw failed(`${dir} holds no AGENTS.md, so it is no desk, and nothing is written. An agent account's desk is settled by console agent setup; in it: console desk . --web`);
4803
+ }
4804
+ const input = {
4805
+ person: { name: person.name ?? person.login, login: person.login },
4806
+ console: { url: session.url, workspace: me.workspace.name },
4807
+ // The language to write to them in (A-F6): theirs, else the workspace's, else none is said.
4808
+ language: readingLanguage(me) ?? undefined,
4809
+ };
4810
+ // The shell of the pages is settled before anything is written, so that a command that cannot
4811
+ // write it writes nothing.
4812
+ const webDir = machine.path(dir, "web");
4813
+ const webKept = on(values, "web") && (await machine.holds(webDir));
4814
+ let shell;
4815
+ if (on(values, "web") && !webKept) {
4816
+ const template = await io.deskWebTemplate?.();
4817
+ if (template === undefined || template.size === 0) {
4818
+ throw failed(`This command's package carries no shell of a desk's pages (template/desk-web): nothing is written.${ofAgent ? "" : " Without --web, the desk alone is written."}`);
4819
+ }
4820
+ if (io.version === undefined) {
4821
+ throw failed(`This command does not know its version, so it cannot say which package the desk's pages are built on: nothing is written.${ofAgent ? "" : " Without --web, the desk alone is written."}`);
4822
+ }
4823
+ shell = deskWebFiles(template, io.version, deskWebTitleOf(input.person));
4824
+ }
4825
+ const written = [];
4826
+ const kept = [];
4827
+ for (const [path, body] of ofAgent ? [] : personDeskFiles(input)) {
4828
+ const file = machine.path(dir, path);
4829
+ if (await machine.exists(file)) {
4830
+ kept.push(path);
4831
+ }
4832
+ else {
4833
+ await machine.write(file, body, 0o644);
4834
+ written.push(path);
4835
+ }
4836
+ }
4837
+ const lines = ofAgent
4838
+ ? []
4839
+ : [
4840
+ written.length === 0
4841
+ ? `The desk at ${dir} is there already, and is left as it is.`
4842
+ : kept.length === 0
4843
+ ? `A new desk is written at ${dir} (${written.join(", ")}), for ${person.login}. It is yours from now on: to edit, and to make a repository of.`
4844
+ : `The desk at ${dir} gains ${written.join(", ")}; ${kept.join(", ")} ${kept.length === 1 ? "was there and is left as it is" : "were there and are left as they are"}.`,
4845
+ ];
4846
+ const shellNames = (shell ?? []).map(([path]) => path);
4847
+ for (const [path, body] of shell ?? []) {
4848
+ await machine.write(machine.path(webDir, ...path.split("/")), body, 0o644);
4849
+ }
4850
+ if (shell !== undefined) {
4851
+ lines.push(`The shell of its pages is written in ${webDir} (${shellNames.join(", ")}), on @skillcdn/console ${io.version}: one empty page of your own until you say what you want to see, served from this machine by console serve once it is built${shellNames.includes("README.md") ? "; its README.md says how" : ""}.`);
4852
+ }
4853
+ else if (webKept) {
4854
+ lines.push(`${webDir} holds something already, and is left as it is.`);
4855
+ }
4856
+ const web = on(values, "web")
4857
+ ? { directory: webDir, written: shellNames, version: shell === undefined ? null : io.version }
4858
+ : null;
4859
+ // An agent account that asked for the shell is shaping its desk already: nothing is next.
4860
+ // So is a person who asked for the shell in a desk that was there: the two lines printed
4861
+ // again sent a fresh agent back to the repository's setup in the middle of building a page.
4862
+ const shaping = ofAgent || (web !== null && written.length === 0);
4863
+ const next = shaping ? [] : deskNext(web !== null, io.skillsDir);
4864
+ answer(io, session, { directory: dir, written, kept, web, next }, () => (next.length === 0
4865
+ ? lines
4866
+ : [
4867
+ ...lines,
4868
+ "Next, in that folder, say these to your agent in order; an agent that ran this command goes on with them there:",
4869
+ "",
4870
+ ...next.map((line, index) => `${index + 1}. ${line}`),
4871
+ ]).join("\n"));
3623
4872
  return EXIT.ok;
3624
4873
  };
3625
4874
  // One agent account by its handle; with --avatar, its picture written as a file (ADR-0084): the
@@ -3974,7 +5223,21 @@ const PROJECT_FIELDS = {
3974
5223
  skills: { type: "string" },
3975
5224
  color: { type: "string" },
3976
5225
  symbol: { type: "string" },
5226
+ glyph: { type: "string" },
3977
5227
  };
5228
+ /** An icon of the pack as a flag names it, `null` for `none`; a name that is none of the pack's is answered with the pack's names. */
5229
+ function glyphOrNoneOf(value) {
5230
+ if (value === undefined) {
5231
+ return undefined;
5232
+ }
5233
+ if (value === "none") {
5234
+ return null;
5235
+ }
5236
+ if (!isIconName(value)) {
5237
+ throw misuse(`No icon of the pack is called ${value}. The pack's icons: ${ICON_NAMES.join(", ")}; none takes the icon away.`);
5238
+ }
5239
+ return value;
5240
+ }
3978
5241
  /** What the flags say of a project; `none` clears what may be cleared. */
3979
5242
  async function projectFieldsOf(io, values) {
3980
5243
  const description = await bodyOf(io, values, text(values, "description"));
@@ -3982,6 +5245,7 @@ async function projectFieldsOf(io, values) {
3982
5245
  const skills = orNone(text(values, "skills"));
3983
5246
  const color = colorOrNoneOf(text(values, "color"));
3984
5247
  const symbol = orNone(text(values, "symbol"));
5248
+ const glyph = glyphOrNoneOf(text(values, "glyph"));
3985
5249
  return {
3986
5250
  ...(description === undefined
3987
5251
  ? {}
@@ -3990,6 +5254,7 @@ async function projectFieldsOf(io, values) {
3990
5254
  ...(skills === undefined ? {} : { skillsAddress: skills }),
3991
5255
  ...(color === undefined ? {} : { color }),
3992
5256
  ...(symbol === undefined ? {} : { symbol }),
5257
+ ...(glyph === undefined ? {} : { glyph }),
3993
5258
  };
3994
5259
  }
3995
5260
  const newProject = async (args, io) => {
@@ -4007,7 +5272,7 @@ const editProject = async (args, io) => {
4007
5272
  const name = text(values, "name");
4008
5273
  const patch = { ...(name === undefined ? {} : { name }), ...(await projectFieldsOf(io, values)) };
4009
5274
  if (Object.keys(patch).length === 0) {
4010
- throw misuse("Say what to change: --name, --description, --visibility, --skills, --color or --symbol; none clears the description, the skills address, the colour or the symbol.");
5275
+ throw misuse("Say what to change: --name, --description, --visibility, --skills, --color, --symbol or --glyph; none clears the description, the skills address, the colour, the symbol or the icon.");
4011
5276
  }
4012
5277
  const session = await open(io, values);
4013
5278
  const changed = await session.client.project(key).update(patch);
@@ -4261,6 +5526,7 @@ const COMMANDS = {
4261
5526
  whoami,
4262
5527
  serve,
4263
5528
  runner,
5529
+ desk,
4264
5530
  projects,
4265
5531
  use,
4266
5532
  work,
@@ -4314,7 +5580,7 @@ function help(io, name) {
4314
5580
  io.stdout(usage(io.version, io.skillsDir));
4315
5581
  return EXIT.ok;
4316
5582
  }
4317
- const found = helpFor(name);
5583
+ const found = helpFor(name, io.skillsDir);
4318
5584
  if (found === undefined) {
4319
5585
  throw misuse(`Not a command: ${name}. The commands: ${Object.keys(COMMAND_HELP).join(", ")}`);
4320
5586
  }
@@ -4536,6 +5802,10 @@ export async function runCli(argv, io) {
4536
5802
  io.stderr(`${error.message}\n`);
4537
5803
  return error.exit;
4538
5804
  }
5805
+ if (error instanceof UnseenProject) {
5806
+ io.stderr(`${error.words}\n`);
5807
+ return EXIT.failed;
5808
+ }
4539
5809
  if (error instanceof ApiError) {
4540
5810
  io.stderr(`${error.code}: ${error.message}\n${hintFor(error, io, seen)}`);
4541
5811
  return error.code === "client.outdated" ||