@skillcdn/console 0.4.7 → 0.5.1

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 (599) hide show
  1. package/README.md +74 -14
  2. package/SKILLCDN.md +5 -3
  3. package/dist/agent-page.d.ts +44 -0
  4. package/dist/agent-page.d.ts.map +1 -0
  5. package/dist/agent-page.js +415 -0
  6. package/dist/agent-page.js.map +1 -0
  7. package/dist/agent-stream.d.ts +52 -0
  8. package/dist/agent-stream.d.ts.map +1 -0
  9. package/dist/agent-stream.js +155 -0
  10. package/dist/agent-stream.js.map +1 -0
  11. package/dist/api.d.ts +12 -6
  12. package/dist/api.d.ts.map +1 -1
  13. package/dist/api.js +11 -5
  14. package/dist/api.js.map +1 -1
  15. package/dist/avatar.d.ts +137 -0
  16. package/dist/avatar.d.ts.map +1 -0
  17. package/dist/avatar.js +1216 -0
  18. package/dist/avatar.js.map +1 -0
  19. package/dist/charts.d.ts +103 -0
  20. package/dist/charts.d.ts.map +1 -0
  21. package/dist/charts.js +182 -0
  22. package/dist/charts.js.map +1 -0
  23. package/dist/cli/cli.d.ts +39 -1
  24. package/dist/cli/cli.d.ts.map +1 -1
  25. package/dist/cli/cli.js +2424 -296
  26. package/dist/cli/cli.js.map +1 -1
  27. package/dist/cli/command-words.d.ts +20 -0
  28. package/dist/cli/command-words.d.ts.map +1 -0
  29. package/dist/cli/command-words.js +51 -0
  30. package/dist/cli/command-words.js.map +1 -0
  31. package/dist/cli/credentials.d.ts +59 -5
  32. package/dist/cli/credentials.d.ts.map +1 -1
  33. package/dist/cli/credentials.js +128 -16
  34. package/dist/cli/credentials.js.map +1 -1
  35. package/dist/cli/directory.d.ts +19 -4
  36. package/dist/cli/directory.d.ts.map +1 -1
  37. package/dist/cli/directory.js +16 -8
  38. package/dist/cli/directory.js.map +1 -1
  39. package/dist/cli/format.d.ts +91 -8
  40. package/dist/cli/format.d.ts.map +1 -1
  41. package/dist/cli/format.js +386 -57
  42. package/dist/cli/format.js.map +1 -1
  43. package/dist/cli/help.d.ts +13 -4
  44. package/dist/cli/help.d.ts.map +1 -1
  45. package/dist/cli/help.js +202 -62
  46. package/dist/cli/help.js.map +1 -1
  47. package/dist/cli/main.js +94 -0
  48. package/dist/cli/main.js.map +1 -1
  49. package/dist/cli/pack.d.ts +69 -36
  50. package/dist/cli/pack.d.ts.map +1 -1
  51. package/dist/cli/pack.js +241 -188
  52. package/dist/cli/pack.js.map +1 -1
  53. package/dist/cli/plugin-check.d.ts +42 -0
  54. package/dist/cli/plugin-check.d.ts.map +1 -1
  55. package/dist/cli/plugin-check.js +221 -36
  56. package/dist/cli/plugin-check.js.map +1 -1
  57. package/dist/cli/plugin-cli.d.ts +6 -1
  58. package/dist/cli/plugin-cli.d.ts.map +1 -1
  59. package/dist/cli/plugin-cli.js +21 -4
  60. package/dist/cli/plugin-cli.js.map +1 -1
  61. package/dist/cli/plugin-main.js +1 -0
  62. package/dist/cli/plugin-main.js.map +1 -1
  63. package/dist/cli/runner-host.d.ts +36 -0
  64. package/dist/cli/runner-host.d.ts.map +1 -0
  65. package/dist/cli/runner-host.js +154 -0
  66. package/dist/cli/runner-host.js.map +1 -0
  67. package/dist/cli/serve.d.ts +33 -1
  68. package/dist/cli/serve.d.ts.map +1 -1
  69. package/dist/cli/serve.js +275 -6
  70. package/dist/cli/serve.js.map +1 -1
  71. package/dist/cli/setup-machine.d.ts +36 -0
  72. package/dist/cli/setup-machine.d.ts.map +1 -0
  73. package/dist/cli/setup-machine.js +109 -0
  74. package/dist/cli/setup-machine.js.map +1 -0
  75. package/dist/client.d.ts +189 -10
  76. package/dist/client.d.ts.map +1 -1
  77. package/dist/client.js +192 -57
  78. package/dist/client.js.map +1 -1
  79. package/dist/compat.d.ts +1 -1
  80. package/dist/compat.js +2 -2
  81. package/dist/components/agent-page.d.ts +384 -0
  82. package/dist/components/agent-page.d.ts.map +1 -0
  83. package/dist/components/agent-page.js +985 -0
  84. package/dist/components/agent-page.js.map +1 -0
  85. package/dist/components/agents.d.ts +102 -0
  86. package/dist/components/agents.d.ts.map +1 -0
  87. package/dist/components/agents.js +246 -0
  88. package/dist/components/agents.js.map +1 -0
  89. package/dist/components/calendar.d.ts +17 -17
  90. package/dist/components/calendar.d.ts.map +1 -1
  91. package/dist/components/calendar.js +7 -2
  92. package/dist/components/calendar.js.map +1 -1
  93. package/dist/components/charts.d.ts +157 -0
  94. package/dist/components/charts.d.ts.map +1 -0
  95. package/dist/components/charts.js +182 -0
  96. package/dist/components/charts.js.map +1 -0
  97. package/dist/components/comments.d.ts +2 -0
  98. package/dist/components/comments.d.ts.map +1 -1
  99. package/dist/components/comments.js +1 -1
  100. package/dist/components/comments.js.map +1 -1
  101. package/dist/components/connect.d.ts.map +1 -1
  102. package/dist/components/connect.js +7 -2
  103. package/dist/components/connect.js.map +1 -1
  104. package/dist/components/decision-form.d.ts +21 -0
  105. package/dist/components/decision-form.d.ts.map +1 -1
  106. package/dist/components/decision-form.js +20 -6
  107. package/dist/components/decision-form.js.map +1 -1
  108. package/dist/components/decision-list.d.ts +24 -0
  109. package/dist/components/decision-list.d.ts.map +1 -1
  110. package/dist/components/decision-list.js +54 -5
  111. package/dist/components/decision-list.js.map +1 -1
  112. package/dist/components/desk-records.d.ts +102 -0
  113. package/dist/components/desk-records.d.ts.map +1 -0
  114. package/dist/components/desk-records.js +221 -0
  115. package/dist/components/desk-records.js.map +1 -0
  116. package/dist/components/desk.d.ts +85 -0
  117. package/dist/components/desk.d.ts.map +1 -0
  118. package/dist/components/desk.js +135 -0
  119. package/dist/components/desk.js.map +1 -0
  120. package/dist/components/event-feed.d.ts.map +1 -1
  121. package/dist/components/event-feed.js +26 -1
  122. package/dist/components/event-feed.js.map +1 -1
  123. package/dist/components/home.d.ts +12 -1
  124. package/dist/components/home.d.ts.map +1 -1
  125. package/dist/components/home.js +175 -16
  126. package/dist/components/home.js.map +1 -1
  127. package/dist/components/my-decisions.d.ts +5 -0
  128. package/dist/components/my-decisions.d.ts.map +1 -1
  129. package/dist/components/my-decisions.js +3 -3
  130. package/dist/components/my-decisions.js.map +1 -1
  131. package/dist/components/people.d.ts +17 -0
  132. package/dist/components/people.d.ts.map +1 -1
  133. package/dist/components/people.js +55 -19
  134. package/dist/components/people.js.map +1 -1
  135. package/dist/components/picker.d.ts +2 -0
  136. package/dist/components/picker.d.ts.map +1 -1
  137. package/dist/components/picker.js +1 -1
  138. package/dist/components/picker.js.map +1 -1
  139. package/dist/components/pictures.d.ts +38 -10
  140. package/dist/components/pictures.d.ts.map +1 -1
  141. package/dist/components/pictures.js +195 -40
  142. package/dist/components/pictures.js.map +1 -1
  143. package/dist/components/plugin-events.d.ts +29 -0
  144. package/dist/components/plugin-events.d.ts.map +1 -0
  145. package/dist/components/plugin-events.js +139 -0
  146. package/dist/components/plugin-events.js.map +1 -0
  147. package/dist/components/plugin-frame.d.ts.map +1 -1
  148. package/dist/components/plugin-frame.js +14 -37
  149. package/dist/components/plugin-frame.js.map +1 -1
  150. package/dist/components/plugin-settings.d.ts.map +1 -1
  151. package/dist/components/plugin-settings.js +58 -7
  152. package/dist/components/plugin-settings.js.map +1 -1
  153. package/dist/components/projects.d.ts.map +1 -1
  154. package/dist/components/projects.js +30 -10
  155. package/dist/components/projects.js.map +1 -1
  156. package/dist/components/rules.d.ts +8 -10
  157. package/dist/components/rules.d.ts.map +1 -1
  158. package/dist/components/rules.js +36 -14
  159. package/dist/components/rules.js.map +1 -1
  160. package/dist/components/sessions.d.ts.map +1 -1
  161. package/dist/components/sessions.js +8 -4
  162. package/dist/components/sessions.js.map +1 -1
  163. package/dist/components/setup.d.ts +59 -0
  164. package/dist/components/setup.d.ts.map +1 -0
  165. package/dist/components/setup.js +93 -0
  166. package/dist/components/setup.js.map +1 -0
  167. package/dist/components/sign-in.js +1 -1
  168. package/dist/components/sign-in.js.map +1 -1
  169. package/dist/components/task-form.d.ts.map +1 -1
  170. package/dist/components/task-form.js +2 -2
  171. package/dist/components/task-form.js.map +1 -1
  172. package/dist/components/task-list.d.ts +7 -6
  173. package/dist/components/task-list.d.ts.map +1 -1
  174. package/dist/components/task-list.js.map +1 -1
  175. package/dist/components/task-view.d.ts +3 -0
  176. package/dist/components/task-view.d.ts.map +1 -1
  177. package/dist/components/task-view.js +1 -1
  178. package/dist/components/task-view.js.map +1 -1
  179. package/dist/components/ui.d.ts +78 -8
  180. package/dist/components/ui.d.ts.map +1 -1
  181. package/dist/components/ui.js +88 -9
  182. package/dist/components/ui.js.map +1 -1
  183. package/dist/components/work.d.ts +5 -5
  184. package/dist/components/work.d.ts.map +1 -1
  185. package/dist/components/work.js.map +1 -1
  186. package/dist/components/workspace.d.ts +17 -0
  187. package/dist/components/workspace.d.ts.map +1 -1
  188. package/dist/components/workspace.js +129 -2
  189. package/dist/components/workspace.js.map +1 -1
  190. package/dist/connect-page.d.ts.map +1 -1
  191. package/dist/connect-page.js +5 -2
  192. package/dist/connect-page.js.map +1 -1
  193. package/dist/console.css +7551 -4580
  194. package/dist/console.d.ts +20 -0
  195. package/dist/console.d.ts.map +1 -1
  196. package/dist/console.js +331 -57
  197. package/dist/console.js.map +1 -1
  198. package/dist/data.d.ts +22 -1
  199. package/dist/data.d.ts.map +1 -1
  200. package/dist/data.js +62 -34
  201. package/dist/data.js.map +1 -1
  202. package/dist/desk-page.d.ts +38 -0
  203. package/dist/desk-page.d.ts.map +1 -0
  204. package/dist/desk-page.js +184 -0
  205. package/dist/desk-page.js.map +1 -0
  206. package/dist/desk-records-page.d.ts +18 -0
  207. package/dist/desk-records-page.d.ts.map +1 -0
  208. package/dist/desk-records-page.js +130 -0
  209. package/dist/desk-records-page.js.map +1 -0
  210. package/dist/desk-records.d.ts +247 -0
  211. package/dist/desk-records.d.ts.map +1 -0
  212. package/dist/desk-records.js +543 -0
  213. package/dist/desk-records.js.map +1 -0
  214. package/dist/desk.d.ts +122 -0
  215. package/dist/desk.d.ts.map +1 -0
  216. package/dist/desk.js +211 -0
  217. package/dist/desk.js.map +1 -0
  218. package/dist/feed-stream.d.ts +39 -0
  219. package/dist/feed-stream.d.ts.map +1 -0
  220. package/dist/feed-stream.js +117 -0
  221. package/dist/feed-stream.js.map +1 -0
  222. package/dist/glances.d.ts +39 -0
  223. package/dist/glances.d.ts.map +1 -0
  224. package/dist/glances.js +94 -0
  225. package/dist/glances.js.map +1 -0
  226. package/dist/home-tiles.d.ts +69 -5
  227. package/dist/home-tiles.d.ts.map +1 -1
  228. package/dist/home-tiles.js +347 -9
  229. package/dist/home-tiles.js.map +1 -1
  230. package/dist/i18n/en.d.ts +773 -3
  231. package/dist/i18n/en.d.ts.map +1 -1
  232. package/dist/i18n/en.js +770 -9
  233. package/dist/i18n/en.js.map +1 -1
  234. package/dist/i18n/ko.d.ts.map +1 -1
  235. package/dist/i18n/ko.js +736 -9
  236. package/dist/i18n/ko.js.map +1 -1
  237. package/dist/index.d.ts +19 -7
  238. package/dist/index.d.ts.map +1 -1
  239. package/dist/index.js +17 -5
  240. package/dist/index.js.map +1 -1
  241. package/dist/limits.d.ts +67 -0
  242. package/dist/limits.d.ts.map +1 -1
  243. package/dist/limits.js +67 -0
  244. package/dist/limits.js.map +1 -1
  245. package/dist/onboarding.d.ts +21 -0
  246. package/dist/onboarding.d.ts.map +1 -0
  247. package/dist/onboarding.js +43 -0
  248. package/dist/onboarding.js.map +1 -0
  249. package/dist/persona.d.ts +34 -0
  250. package/dist/persona.d.ts.map +1 -0
  251. package/dist/persona.js +71 -0
  252. package/dist/persona.js.map +1 -0
  253. package/dist/plugin/context.d.ts +42 -11
  254. package/dist/plugin/context.d.ts.map +1 -1
  255. package/dist/plugin/limits.d.ts +2 -0
  256. package/dist/plugin/limits.d.ts.map +1 -1
  257. package/dist/plugin/limits.js +2 -0
  258. package/dist/plugin/limits.js.map +1 -1
  259. package/dist/plugin/manifest.d.ts +13 -0
  260. package/dist/plugin/manifest.d.ts.map +1 -1
  261. package/dist/plugin/manifest.js +34 -4
  262. package/dist/plugin/manifest.js.map +1 -1
  263. package/dist/plugin/rest-schemas.d.ts +56 -0
  264. package/dist/plugin/rest-schemas.d.ts.map +1 -1
  265. package/dist/plugin/rest-schemas.js +42 -0
  266. package/dist/plugin/rest-schemas.js.map +1 -1
  267. package/dist/plugin/sandbox.d.ts.map +1 -1
  268. package/dist/plugin/sandbox.js +4 -1
  269. package/dist/plugin/sandbox.js.map +1 -1
  270. package/dist/plugin/testing.d.ts +6 -2
  271. package/dist/plugin/testing.d.ts.map +1 -1
  272. package/dist/plugin/testing.js +52 -10
  273. package/dist/plugin/testing.js.map +1 -1
  274. package/dist/plugin.d.ts +1 -1
  275. package/dist/plugin.d.ts.map +1 -1
  276. package/dist/plugin.js +1 -1
  277. package/dist/plugin.js.map +1 -1
  278. package/dist/records.d.ts +283 -0
  279. package/dist/records.d.ts.map +1 -0
  280. package/dist/records.js +543 -0
  281. package/dist/records.js.map +1 -0
  282. package/dist/router.d.ts +50 -3
  283. package/dist/router.d.ts.map +1 -1
  284. package/dist/router.js +78 -7
  285. package/dist/router.js.map +1 -1
  286. package/dist/routes.d.ts +12 -2
  287. package/dist/routes.d.ts.map +1 -1
  288. package/dist/routes.js +14 -1
  289. package/dist/routes.js.map +1 -1
  290. package/dist/rules.d.ts +30 -11
  291. package/dist/rules.d.ts.map +1 -1
  292. package/dist/rules.js +99 -42
  293. package/dist/rules.js.map +1 -1
  294. package/dist/runner/acp.d.ts +20 -0
  295. package/dist/runner/acp.d.ts.map +1 -0
  296. package/dist/runner/acp.js +1132 -0
  297. package/dist/runner/acp.js.map +1 -0
  298. package/dist/runner/claude.d.ts +13 -0
  299. package/dist/runner/claude.d.ts.map +1 -0
  300. package/dist/runner/claude.js +615 -0
  301. package/dist/runner/claude.js.map +1 -0
  302. package/dist/runner/codex.d.ts +19 -0
  303. package/dist/runner/codex.d.ts.map +1 -0
  304. package/dist/runner/codex.js +597 -0
  305. package/dist/runner/codex.js.map +1 -0
  306. package/dist/runner/config.d.ts +35 -0
  307. package/dist/runner/config.d.ts.map +1 -0
  308. package/dist/runner/config.js +74 -0
  309. package/dist/runner/config.js.map +1 -0
  310. package/dist/runner/desk.d.ts +81 -0
  311. package/dist/runner/desk.d.ts.map +1 -0
  312. package/dist/runner/desk.js +303 -0
  313. package/dist/runner/desk.js.map +1 -0
  314. package/dist/runner/launchd.d.ts +7 -0
  315. package/dist/runner/launchd.d.ts.map +1 -0
  316. package/dist/runner/launchd.js +78 -0
  317. package/dist/runner/launchd.js.map +1 -0
  318. package/dist/runner/message.d.ts +66 -0
  319. package/dist/runner/message.d.ts.map +1 -0
  320. package/dist/runner/message.js +181 -0
  321. package/dist/runner/message.js.map +1 -0
  322. package/dist/runner/modules.d.ts +13 -0
  323. package/dist/runner/modules.d.ts.map +1 -0
  324. package/dist/runner/modules.js +30 -0
  325. package/dist/runner/modules.js.map +1 -0
  326. package/dist/runner/process.d.ts +7 -0
  327. package/dist/runner/process.d.ts.map +1 -0
  328. package/dist/runner/process.js +65 -0
  329. package/dist/runner/process.js.map +1 -0
  330. package/dist/runner/redact.d.ts +48 -0
  331. package/dist/runner/redact.d.ts.map +1 -0
  332. package/dist/runner/redact.js +214 -0
  333. package/dist/runner/redact.js.map +1 -0
  334. package/dist/runner/registry.d.ts +37 -0
  335. package/dist/runner/registry.d.ts.map +1 -0
  336. package/dist/runner/registry.js +26 -0
  337. package/dist/runner/registry.js.map +1 -0
  338. package/dist/runner/runner.d.ts +130 -0
  339. package/dist/runner/runner.d.ts.map +1 -0
  340. package/dist/runner/runner.js +1551 -0
  341. package/dist/runner/runner.js.map +1 -0
  342. package/dist/runner/slack.d.ts +16 -0
  343. package/dist/runner/slack.d.ts.map +1 -0
  344. package/dist/runner/slack.js +157 -0
  345. package/dist/runner/slack.js.map +1 -0
  346. package/dist/runner/systemd-user.d.ts +7 -0
  347. package/dist/runner/systemd-user.d.ts.map +1 -0
  348. package/dist/runner/systemd-user.js +93 -0
  349. package/dist/runner/systemd-user.js.map +1 -0
  350. package/dist/runner/task-scheduler.d.ts +38 -0
  351. package/dist/runner/task-scheduler.d.ts.map +1 -0
  352. package/dist/runner/task-scheduler.js +216 -0
  353. package/dist/runner/task-scheduler.js.map +1 -0
  354. package/dist/runner/types.d.ts +315 -0
  355. package/dist/runner/types.d.ts.map +1 -0
  356. package/dist/runner/types.js +24 -0
  357. package/dist/runner/types.js.map +1 -0
  358. package/dist/runner.d.ts +18 -0
  359. package/dist/runner.d.ts.map +1 -0
  360. package/dist/runner.js +20 -0
  361. package/dist/runner.js.map +1 -0
  362. package/dist/schemas.d.ts +6082 -1295
  363. package/dist/schemas.d.ts.map +1 -1
  364. package/dist/schemas.js +930 -31
  365. package/dist/schemas.js.map +1 -1
  366. package/dist/services.d.ts +110 -0
  367. package/dist/services.d.ts.map +1 -0
  368. package/dist/services.js +305 -0
  369. package/dist/services.js.map +1 -0
  370. package/dist/setup-guide.d.ts +64 -0
  371. package/dist/setup-guide.d.ts.map +1 -0
  372. package/dist/setup-guide.js +256 -0
  373. package/dist/setup-guide.js.map +1 -0
  374. package/dist/setup-page.d.ts +6 -0
  375. package/dist/setup-page.d.ts.map +1 -0
  376. package/dist/setup-page.js +29 -0
  377. package/dist/setup-page.js.map +1 -0
  378. package/dist/sse.d.ts +15 -0
  379. package/dist/sse.d.ts.map +1 -0
  380. package/dist/sse.js +73 -0
  381. package/dist/sse.js.map +1 -0
  382. package/dist/tab-title.d.ts +6 -0
  383. package/dist/tab-title.d.ts.map +1 -0
  384. package/dist/tab-title.js +22 -0
  385. package/dist/tab-title.js.map +1 -0
  386. package/dist/tokens.d.ts.map +1 -1
  387. package/dist/tokens.js +3 -0
  388. package/dist/tokens.js.map +1 -1
  389. package/dist/use-action.d.ts +5 -2
  390. package/dist/use-action.d.ts.map +1 -1
  391. package/dist/use-action.js +6 -1
  392. package/dist/use-action.js.map +1 -1
  393. package/dist/vocabulary.d.ts +84 -4
  394. package/dist/vocabulary.d.ts.map +1 -1
  395. package/dist/vocabulary.js +115 -3
  396. package/dist/vocabulary.js.map +1 -1
  397. package/docs/specs/cli.md +147 -41
  398. package/docs/specs/plugins.md +37 -27
  399. package/docs/specs/records.md +113 -0
  400. package/docs/specs/rest.md +155 -20
  401. package/docs/specs/runner.md +347 -0
  402. package/package.json +12 -3
  403. package/skills/building-a-console/SKILL.md +4 -4
  404. package/skills/building-a-console/references/configuring.md +1 -0
  405. package/skills/building-a-plugin/SKILL.md +7 -7
  406. package/skills/deploying-a-console/SKILL.md +4 -4
  407. package/skills/deploying-a-console/references/resources.md +48 -8
  408. package/skills/deploying-a-console/references/running-it-again.md +3 -2
  409. package/skills/keeping-a-desk/SKILL.md +133 -0
  410. package/skills/keeping-a-desk/collections.md +96 -0
  411. package/skills/planning-the-board/SKILL.md +14 -18
  412. package/skills/planning-the-board/references/a-task.md +2 -2
  413. package/skills/planning-the-board/references/project-rules.md +13 -14
  414. package/skills/planning-the-board/references/setting-up.md +22 -9
  415. package/skills/running-an-agent/SKILL.md +107 -0
  416. package/skills/running-an-agent/references/slack-app.md +61 -0
  417. package/skills/working-the-board/SKILL.md +66 -39
  418. package/skills/working-the-board/references/terms.md +9 -5
  419. package/skills/working-the-board/references/the-pack.md +14 -9
  420. package/skills/working-the-board/references/the-sentence.md +2 -2
  421. package/src/agent-page.tsx +1039 -0
  422. package/src/agent-stream.ts +199 -0
  423. package/src/api.ts +317 -2
  424. package/src/avatar.ts +1506 -0
  425. package/src/charts.ts +250 -0
  426. package/src/cli/cli.ts +3210 -503
  427. package/src/cli/command-words.ts +56 -0
  428. package/src/cli/credentials.ts +188 -16
  429. package/src/cli/directory.ts +28 -10
  430. package/src/cli/format.ts +470 -67
  431. package/src/cli/help.ts +233 -61
  432. package/src/cli/main.ts +89 -0
  433. package/src/cli/pack.ts +332 -263
  434. package/src/cli/plugin-check.ts +275 -34
  435. package/src/cli/plugin-cli.ts +28 -4
  436. package/src/cli/plugin-main.ts +1 -0
  437. package/src/cli/runner-host.ts +188 -0
  438. package/src/cli/serve.ts +320 -5
  439. package/src/cli/setup-machine.ts +153 -0
  440. package/src/client.ts +711 -126
  441. package/src/compat.ts +2 -2
  442. package/src/components/agent-page.tsx +1946 -0
  443. package/src/components/agents.tsx +638 -0
  444. package/src/components/calendar.tsx +74 -53
  445. package/src/components/charts.tsx +680 -0
  446. package/src/components/comments.tsx +3 -0
  447. package/src/components/connect.tsx +37 -2
  448. package/src/components/decision-form.tsx +89 -51
  449. package/src/components/decision-list.tsx +140 -4
  450. package/src/components/desk-records.tsx +724 -0
  451. package/src/components/desk.tsx +471 -0
  452. package/src/components/event-feed.tsx +30 -1
  453. package/src/components/home.tsx +353 -12
  454. package/src/components/my-decisions.tsx +8 -2
  455. package/src/components/people.tsx +300 -203
  456. package/src/components/picker.tsx +3 -1
  457. package/src/components/pictures.tsx +256 -44
  458. package/src/components/plugin-events.ts +159 -0
  459. package/src/components/plugin-frame.tsx +14 -38
  460. package/src/components/plugin-settings.tsx +178 -22
  461. package/src/components/projects.tsx +33 -15
  462. package/src/components/rules.tsx +96 -36
  463. package/src/components/sessions.tsx +7 -4
  464. package/src/components/setup.tsx +252 -0
  465. package/src/components/sign-in.tsx +1 -1
  466. package/src/components/task-form.tsx +11 -2
  467. package/src/components/task-list.tsx +7 -6
  468. package/src/components/task-view.tsx +4 -0
  469. package/src/components/ui.tsx +169 -25
  470. package/src/components/work.tsx +9 -9
  471. package/src/components/workspace.tsx +345 -4
  472. package/src/connect-page.tsx +15 -2
  473. package/src/console.tsx +657 -83
  474. package/src/data.ts +109 -43
  475. package/src/desk-page.tsx +332 -0
  476. package/src/desk-records-page.tsx +256 -0
  477. package/src/desk-records.ts +808 -0
  478. package/src/desk.ts +329 -0
  479. package/src/feed-stream.ts +144 -0
  480. package/src/glances.ts +132 -0
  481. package/src/home-tiles.ts +411 -9
  482. package/src/i18n/en.ts +828 -10
  483. package/src/i18n/ko.ts +792 -10
  484. package/src/index.ts +172 -3
  485. package/src/limits.ts +67 -0
  486. package/src/onboarding.ts +84 -0
  487. package/src/persona.ts +100 -0
  488. package/src/plugin/context.ts +55 -12
  489. package/src/plugin/limits.ts +2 -0
  490. package/src/plugin/manifest.ts +42 -3
  491. package/src/plugin/rest-schemas.ts +46 -0
  492. package/src/plugin/sandbox.ts +4 -1
  493. package/src/plugin/testing.ts +63 -12
  494. package/src/plugin.ts +2 -0
  495. package/src/records.ts +702 -0
  496. package/src/router.ts +120 -10
  497. package/src/routes.ts +17 -1
  498. package/src/rules.ts +109 -44
  499. package/src/runner/acp.ts +1267 -0
  500. package/src/runner/claude.ts +695 -0
  501. package/src/runner/codex.ts +691 -0
  502. package/src/runner/config.ts +97 -0
  503. package/src/runner/desk.ts +377 -0
  504. package/src/runner/launchd.ts +86 -0
  505. package/src/runner/message.ts +232 -0
  506. package/src/runner/modules.ts +30 -0
  507. package/src/runner/process.ts +72 -0
  508. package/src/runner/redact.ts +242 -0
  509. package/src/runner/registry.ts +67 -0
  510. package/src/runner/runner.ts +1879 -0
  511. package/src/runner/slack.ts +180 -0
  512. package/src/runner/systemd-user.ts +103 -0
  513. package/src/runner/task-scheduler.ts +236 -0
  514. package/src/runner/types.ts +334 -0
  515. package/src/runner.ts +110 -0
  516. package/src/schemas.ts +1183 -30
  517. package/src/services.ts +424 -0
  518. package/src/setup-guide.ts +336 -0
  519. package/src/setup-page.tsx +46 -0
  520. package/src/sse.ts +84 -0
  521. package/src/styles/README.md +111 -0
  522. package/src/styles/base.css +130 -0
  523. package/src/styles/console.css +85 -7095
  524. package/src/styles/drawn-by-pages.json +256 -0
  525. package/src/styles/pages/agents.css +1195 -0
  526. package/src/styles/pages/board.css +380 -0
  527. package/src/styles/pages/calendar.css +214 -0
  528. package/src/styles/pages/connect.css +182 -0
  529. package/src/styles/pages/decisions.css +370 -0
  530. package/src/styles/pages/desk.css +126 -0
  531. package/src/styles/pages/documents.css +273 -0
  532. package/src/styles/pages/feed.css +118 -0
  533. package/src/styles/pages/home.css +718 -0
  534. package/src/styles/pages/people.css +90 -0
  535. package/src/styles/pages/plugins.css +212 -0
  536. package/src/styles/pages/roadmap.css +377 -0
  537. package/src/styles/pages/settings.css +171 -0
  538. package/src/styles/pages/shell.css +208 -0
  539. package/src/styles/pages/sign-in.css +178 -0
  540. package/src/styles/pages/task.css +108 -0
  541. package/src/styles/pages/thread.css +331 -0
  542. package/src/styles/pages/work.css +68 -0
  543. package/src/styles/parts/avatar.css +82 -0
  544. package/src/styles/parts/badge.css +227 -0
  545. package/src/styles/parts/bars.css +80 -0
  546. package/src/styles/parts/button.css +99 -0
  547. package/src/styles/parts/calendar.css +547 -0
  548. package/src/styles/parts/callout.css +41 -0
  549. package/src/styles/parts/category.css +8 -0
  550. package/src/styles/parts/chart.css +173 -0
  551. package/src/styles/parts/chip.css +90 -0
  552. package/src/styles/parts/code.css +48 -0
  553. package/src/styles/parts/count.css +27 -0
  554. package/src/styles/parts/crumbs.css +61 -0
  555. package/src/styles/parts/detail.css +110 -0
  556. package/src/styles/parts/empty.css +21 -0
  557. package/src/styles/parts/eyebrow.css +9 -0
  558. package/src/styles/parts/facts.css +147 -0
  559. package/src/styles/parts/figures.css +65 -0
  560. package/src/styles/parts/files.css +38 -0
  561. package/src/styles/parts/filters.css +42 -0
  562. package/src/styles/parts/form.css +109 -0
  563. package/src/styles/parts/frame.css +45 -0
  564. package/src/styles/parts/input.css +243 -0
  565. package/src/styles/parts/legend.css +48 -0
  566. package/src/styles/parts/links.css +37 -0
  567. package/src/styles/parts/mark.css +79 -0
  568. package/src/styles/parts/menu.css +147 -0
  569. package/src/styles/parts/page.css +174 -0
  570. package/src/styles/parts/pager.css +19 -0
  571. package/src/styles/parts/panel.css +33 -0
  572. package/src/styles/parts/person.css +257 -0
  573. package/src/styles/parts/picker.css +185 -0
  574. package/src/styles/parts/progress.css +25 -0
  575. package/src/styles/parts/prose.css +128 -0
  576. package/src/styles/parts/rows.css +63 -0
  577. package/src/styles/parts/series.css +32 -0
  578. package/src/styles/parts/settings.css +101 -0
  579. package/src/styles/parts/share.css +25 -0
  580. package/src/styles/parts/spark.css +23 -0
  581. package/src/styles/parts/spinner.css +29 -0
  582. package/src/styles/parts/stat.css +69 -0
  583. package/src/styles/parts/steps.css +68 -0
  584. package/src/styles/parts/tabs.css +175 -0
  585. package/src/styles/parts/text.css +61 -0
  586. package/src/styles/parts/toggle.css +71 -0
  587. package/src/styles/parts/workers.css +37 -0
  588. package/src/styles/tokens.css +295 -0
  589. package/src/tab-title.ts +25 -0
  590. package/src/tokens.ts +3 -0
  591. package/src/use-action.ts +7 -2
  592. package/src/vocabulary.ts +151 -3
  593. package/template/desk-web/README.md +8 -0
  594. package/template/desk-web/index.html +13 -0
  595. package/template/desk-web/package.json +25 -0
  596. package/template/desk-web/src/main.tsx +24 -0
  597. package/template/desk-web/src/page.tsx +51 -0
  598. package/template/desk-web/tsconfig.json +16 -0
  599. package/template/desk-web/vite.config.ts +15 -0
package/src/cli/cli.ts CHANGED
@@ -1,11 +1,29 @@
1
- import { basename, extname } from "node:path";
1
+ import { basename, extname, isAbsolute } from "node:path";
2
2
  import { parseArgs } from "node:util";
3
+ import { deflateSync } from "node:zlib";
4
+ import {
5
+ PackError,
6
+ type PackRead,
7
+ ReadMisuse,
8
+ type ReadOutput,
9
+ readNumber,
10
+ readPack,
11
+ wroteLine,
12
+ } from "@skillcdn/cli";
13
+ import {
14
+ BROWSE_MAX_LIMIT,
15
+ FIND_MAX_LIMIT,
16
+ READ_FILE_MAX_LIMIT,
17
+ type ToolWords,
18
+ } from "@skillcdn/core";
19
+ import { avatarScanlines, MAX_AVATAR_PIXELS, pngFile } from "../avatar.js";
3
20
  import {
4
21
  ApiError,
5
22
  type ConsoleClient,
6
23
  createClient,
7
24
  type FetchLike,
8
25
  type FileUpload,
26
+ type PackClient,
9
27
  type PluginClient,
10
28
  type ProjectClient,
11
29
  } from "../client.js";
@@ -20,19 +38,37 @@ import {
20
38
  VERSION_HEADER,
21
39
  formatVersion as versionText,
22
40
  } from "../compat.js";
41
+ import { normalizeConnectCode } from "../connect.js";
23
42
  import { addDays, dayOf as dayOfDate, firstDayOfWeek, isDay, weekOf } from "../dates.js";
24
43
  import {
25
44
  DEFAULT_PAGE_LIMIT,
45
+ EVENTS_PAGE_LIMIT,
26
46
  LIST_LIMIT,
27
47
  MAX_DECIDERS,
28
48
  MAX_OPTIONS,
49
+ MAX_RUNNER_LINE_LENGTH,
50
+ MAX_SIGNALS_PAGE_LIMIT,
29
51
  MIN_OPTIONS,
30
52
  } from "../limits.js";
31
53
  import { capabilityWords } from "../plugin/capabilities.js";
32
54
  import { PLUGIN_LIST_LIMIT } from "../plugin/limits.js";
55
+ import { checkRecords, RECORDS_DIR, RECORDS_INDEX_FILE, type RecordsFiles } from "../records.js";
56
+ import { decisionHref, docHref, myDecisionHref, taskHref } from "../router.js";
33
57
  import { fillRules, RULES_PATH, RULES_TITLE } from "../rules.js";
58
+ import { DEFAULT_RUNNER_CONFIG, parseRunnerConfig } from "../runner/config.js";
59
+ import {
60
+ DESK_FOLDER,
61
+ deskFiles,
62
+ deskServicesOf,
63
+ deskWebTitleOf,
64
+ personDeskFiles,
65
+ } from "../runner/desk.js";
66
+ import { ownRunnerModules } from "../runner/modules.js";
67
+ import { createRunner, GIT_TOKEN_SECRET, type RunnerState } from "../runner/runner.js";
68
+ import type { ServiceCommand } from "../runner/types.js";
34
69
  import {
35
70
  hostOfLogin,
71
+ type RestAgentSetup,
36
72
  type RestAnswerInput,
37
73
  type RestClaim,
38
74
  type RestDecision,
@@ -43,12 +79,14 @@ import {
43
79
  type RestPluginEnableInput,
44
80
  type RestPluginGrantInput,
45
81
  type RestPluginInvocation,
46
- type RestSkillBrowse,
47
- type RestSkillFile,
48
- type RestSkillLoad,
49
- type RestSkills,
82
+ type RestRules,
83
+ type RestRun,
84
+ type RestRunBrief,
85
+ type RestTask,
50
86
  type RestTaskPatch,
51
87
  } from "../schemas.js";
88
+ import { agentLoginOf, deskRemoteOf } from "../services.js";
89
+ import { setupGuideOf, setupGuideText, setupSentenceOf } from "../setup-guide.js";
52
90
  import {
53
91
  COLOR_NAMES,
54
92
  CONSOLE_LANGUAGES,
@@ -65,6 +103,8 @@ import {
65
103
  type ProjectRole,
66
104
  type ProjectVisibility,
67
105
  type ProviderKey,
106
+ SERVICE_ROLES,
107
+ type ServiceRole,
68
108
  TASK_PRIORITIES,
69
109
  TASK_STATES,
70
110
  type TaskPriority,
@@ -72,20 +112,36 @@ import {
72
112
  WEEK_STARTS,
73
113
  } from "../vocabulary.js";
74
114
  import { loadWebRoot, type WebRoot, WebRootError } from "../web.js";
115
+ import { commandLine, commandWord, NO_LINE_TO_RUN } from "./command-words.js";
75
116
  import {
76
117
  type CredentialStore,
77
118
  type Credentials,
78
119
  CredentialsError,
79
120
  EMPTY_CREDENTIALS,
121
+ fitsFile,
122
+ keepsNothing,
123
+ lasts,
80
124
  loginsAt,
125
+ type PendingConnection,
126
+ pendingAt,
81
127
  type Resolution,
82
128
  resolveLogin,
83
129
  withLogin,
84
130
  withoutLogin,
131
+ withoutPending,
132
+ withPending,
85
133
  } from "./credentials.js";
86
- import { type DirectorySettings, type DirectoryStore, THE_SENTENCE } from "./directory.js";
87
134
  import {
135
+ DIRECTORY_FILE,
136
+ type DirectorySettings,
137
+ type DirectoryStore,
138
+ THE_SENTENCE,
139
+ } from "./directory.js";
140
+ import {
141
+ calledOf,
88
142
  deciderLogins,
143
+ formatAgent,
144
+ formatAgentLine,
89
145
  formatAnswer,
90
146
  formatCategoryLine,
91
147
  formatComment,
@@ -104,6 +160,7 @@ import {
104
160
  formatPersonWork,
105
161
  formatPlugin,
106
162
  formatPluginAsks,
163
+ formatPluginEvents,
107
164
  formatPluginGrantLine,
108
165
  formatPluginHelp,
109
166
  formatPluginRecord,
@@ -114,8 +171,12 @@ import {
114
171
  formatProject,
115
172
  formatProjectLine,
116
173
  formatRules,
174
+ formatRulesChanged,
175
+ formatRulesLeftOut,
117
176
  formatRun,
118
177
  formatRunLine,
178
+ formatSecretLine,
179
+ formatSignalLine,
119
180
  formatTask,
120
181
  formatTaskLine,
121
182
  formatTeamLine,
@@ -125,28 +186,35 @@ import {
125
186
  formatWorkspace,
126
187
  localized,
127
188
  moment,
189
+ pageLine,
190
+ rulesMark,
128
191
  setMomentZone,
129
192
  } from "./format.js";
130
193
  import { COMMAND_HELP, helpFor, ownSkillPath, usage } from "./help.js";
131
194
  import { describeInstall, type Install, updateCommandFor } from "./install.js";
132
195
  import type { NoticeStore } from "./notices.js";
133
196
  import {
134
- bodyOfFile,
135
- bodyOfFolder,
136
- bodyOfSkill,
137
- formatSkillBrowse,
138
- formatSkillFile,
139
- formatSkillFind,
140
- formatSkillLoad,
197
+ type ConsolePack,
198
+ consolePack,
141
199
  formatSkills,
142
- joinFile,
143
- joinFolder,
144
- joinSkill,
145
- type PackSummary,
200
+ holdsNothing,
201
+ ORGANIZATION_PACK_LINE,
202
+ type PackOwner,
203
+ PackRefusal,
204
+ packWords,
205
+ refusalWords,
146
206
  skillPathIn,
147
- summaryOf,
148
207
  } from "./pack.js";
149
- import { createServeHandler, DEFAULT_SERVE_PORT, type Listen } from "./serve.js";
208
+ import { type RunnerHost, workPath } from "./runner-host.js";
209
+ import {
210
+ createServeHandler,
211
+ DEFAULT_SERVE_PORT,
212
+ type Listen,
213
+ loadRecordsRoot,
214
+ type RecordsRoot,
215
+ RecordsRootError,
216
+ } from "./serve.js";
217
+ import type { Ran, SetupMachine } from "./setup-machine.js";
150
218
 
151
219
  // The `console` command (docs/specs/cli.md): the agent's side of the console. A thin client of
152
220
  // the REST API with no logic of its own: every command is one or two requests and the words to
@@ -161,7 +229,7 @@ export const EXIT = {
161
229
  failed: 1,
162
230
  /** The command was not understood. */
163
231
  usage: 2,
164
- /** The decision still waits for a person. */
232
+ /** What was waited for still waits for a person: a decision's answer, or a connection's approval. */
165
233
  waiting: 3,
166
234
  /** The command and the console do not go together (ADR-0025): stderr says which to update, and how. */
167
235
  incompatible: 4,
@@ -178,6 +246,12 @@ const WAIT_PAUSE_MS = 500;
178
246
  const DEFAULT_ASK_WAIT_SECONDS = 60;
179
247
  /** The longest wait a person may ask for: a day. */
180
248
  const MAX_WAIT_SECONDS = 86_400;
249
+ /**
250
+ * How long `login` waits for the approval of a connection a call before it began, where no
251
+ * terminal shows its words as they are printed (ADR-0129): within the two minutes an agent's
252
+ * host gives a command before it cuts it off.
253
+ */
254
+ const DEFAULT_LOGIN_WAIT_SECONDS = 90;
181
255
 
182
256
  export interface CliIo {
183
257
  readonly env: Readonly<Record<string, string | undefined>>;
@@ -194,6 +268,14 @@ export interface CliIo {
194
268
  readonly readSecret?: ((prompt: string) => Promise<string>) | undefined;
195
269
  /** The name of the machine, for the agent to say where it runs; nothing when unknown. */
196
270
  readonly hostname?: string | undefined;
271
+ /** The machine's own time zone, for a moment printed before the workspace's is known. */
272
+ readonly timeZone?: string | undefined;
273
+ /**
274
+ * Whether a terminal shows the command's words as they are printed. Where none does, whoever
275
+ * runs the command sees them when it ends, so `login` says its code and ends, and waits for
276
+ * the approval in the next call (ADR-0129). Left out, one is taken to be there.
277
+ */
278
+ readonly terminal?: boolean | undefined;
197
279
  /** A file named with `--file`, as text. */
198
280
  readonly readFile: (path: string) => Promise<string>;
199
281
  /** A file handed in, as bytes. */
@@ -211,6 +293,14 @@ export interface CliIo {
211
293
  readonly userAgent?: string | undefined;
212
294
  /** Where the command is installed, so that an update is told the way it takes effect; nothing when unknown. */
213
295
  readonly install?: Install | undefined;
296
+ /**
297
+ * The version of the package as it stands on this machine now, read again from its manifest:
298
+ * another than `version` once the package was updated under a command that runs on, which is
299
+ * what a runner ends for (ADR-0101). Left out, a runner never ends for an update.
300
+ */
301
+ readonly installedVersion?: (() => Promise<string | undefined>) | undefined;
302
+ /** The console's version as its last answer said it (ADR-0025); the command sets it for itself. */
303
+ readonly consoleVersion?: (() => string | undefined) | undefined;
214
304
  /** What the command last said of the versions; left out, it says it every time. */
215
305
  readonly notices?: NoticeStore | undefined;
216
306
  /** The oldest console this command works with (ADR-0038); left out, the package's own floor. */
@@ -221,6 +311,24 @@ export interface CliIo {
221
311
  readonly skillsDir?: string | undefined;
222
312
  /** How `serve` listens on the loopback (ADR-0014); left out, the command cannot serve. */
223
313
  readonly listen?: Listen | undefined;
314
+ /** What `runner` needs of the machine (ADR-0085); left out, the command cannot run one. */
315
+ readonly runner?: RunnerHost | undefined;
316
+ /** What `agent setup` needs of the machine (ADR-0088), and `desk` of its files; left out, the command sets none up and writes no desk. */
317
+ readonly machine?: SetupMachine | undefined;
318
+ /**
319
+ * The shell of a desk's pages as the package carries it (ADR-0115), `template/desk-web`
320
+ * beside `dist/`: its files as text, by their path in it with forward slashes; nothing where
321
+ * the package carries none. Left out, `desk --web` has no shell to write.
322
+ */
323
+ readonly deskWebTemplate?: (() => Promise<ReadonlyMap<string, string> | undefined>) | undefined;
324
+ /**
325
+ * The records of a desk on this machine (ADR-0117), for `desk check`: the desk's directory in
326
+ * full, and the files of its `records/` as the format's check reads them. Left out, the
327
+ * command checks none.
328
+ */
329
+ readonly recordsAt?:
330
+ | ((directory: string) => { readonly directory: string; readonly files: RecordsFiles })
331
+ | undefined;
224
332
  }
225
333
 
226
334
  /** The command stops with an exit code and a word on stderr. */
@@ -301,6 +409,101 @@ interface Session {
301
409
  project(): Promise<ProjectClient>;
302
410
  /** The key of that project, or nothing when none is named. */
303
411
  projectKey(): Promise<string | undefined>;
412
+ /** The key with what named it, for `whoami` to say (ADR-0112); nothing when none is named. */
413
+ projectNamed(): { readonly key: string; readonly source: ProjectSource } | undefined;
414
+ }
415
+
416
+ /**
417
+ * What named the project a command works in, in the order they win: the flag, the environment,
418
+ * the directory's file, with the directory that holds it where the store says.
419
+ */
420
+ type ProjectSource =
421
+ | { readonly kind: "flag" }
422
+ | { readonly kind: "environment" }
423
+ | { readonly kind: "directory"; readonly directory: string | undefined };
424
+
425
+ /**
426
+ * What is said of a project the console does not have, or does not show the member: the key,
427
+ * the console and what named the key, then the two things a person can do about it, each
428
+ * something to ask for or to do. An agent that reads only "not found" guesses at causes; one of
429
+ * these two is always the one. `login` is the member's, where the command knows it. Both are
430
+ * said as what is done and by whom, never as a command to whoever reads: an agent told to do
431
+ * as it saw fit took "bind this directory anew" for its own step, bound the checkout to another
432
+ * project and went on with no task. Which key is right is the repository's agreement's to say,
433
+ * or the person's.
434
+ */
435
+ function unseenProjectWords(
436
+ url: string,
437
+ named: { readonly key: string; readonly source: ProjectSource },
438
+ login: string | undefined,
439
+ ): string {
440
+ const right =
441
+ "the right one, the key the repository's agreement names or the one the person says";
442
+ const mend =
443
+ named.source.kind === "directory"
444
+ ? `the directory is bound to ${right}, with console use <key>`
445
+ : named.source.kind === "environment"
446
+ ? `CONSOLE_PROJECT is set to ${right}, or unset`
447
+ : `--project is given ${right}`;
448
+ return [
449
+ `project.not_found: ${url} has no project ${named.key}, or it is not yours to see. The key is named by ${sourceWords(named.source)}.`,
450
+ `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.`,
451
+ ].join("\n");
452
+ }
453
+
454
+ /**
455
+ * The console's refusal of the project a directory or the environment names, with the words
456
+ * above: still the refusal it was, for the code that reads one (a decision is looked for
457
+ * elsewhere when its project is not found), and said in full where the command ends on it.
458
+ */
459
+ class UnseenProject extends ApiError {
460
+ readonly words: string;
461
+
462
+ constructor(refusal: ApiError, words: string) {
463
+ super(refusal.status, refusal.code, refusal.message);
464
+ this.name = "UnseenProject";
465
+ this.words = words;
466
+ }
467
+ }
468
+
469
+ /**
470
+ * A project's client whose refusals as `project.not_found` carry `words`: every command that
471
+ * works in the directory's project goes through one, so that the refusal names the key, the
472
+ * console and what named it wherever it is met, and no command says it for itself.
473
+ */
474
+ function namingUnseen(project: ProjectClient, words: () => string): ProjectClient {
475
+ return new Proxy(project, {
476
+ get(target, property, receiver) {
477
+ const member: unknown = Reflect.get(target, property, receiver);
478
+ if (typeof member !== "function") {
479
+ return member;
480
+ }
481
+ return (...args: unknown[]): unknown => {
482
+ const result: unknown = Reflect.apply(member, target, args);
483
+ return result instanceof Promise
484
+ ? result.catch((error: unknown) => {
485
+ throw error instanceof ApiError && error.code === "project.not_found"
486
+ ? new UnseenProject(error, words())
487
+ : error;
488
+ })
489
+ : result;
490
+ };
491
+ },
492
+ });
493
+ }
494
+
495
+ /** Where a project's key came from, as `whoami` and its refusal say it. */
496
+ function sourceWords(source: ProjectSource): string {
497
+ switch (source.kind) {
498
+ case "flag":
499
+ return "--project";
500
+ case "environment":
501
+ return "CONSOLE_PROJECT";
502
+ case "directory":
503
+ return source.directory === undefined
504
+ ? DIRECTORY_FILE
505
+ : `${DIRECTORY_FILE} in ${source.directory}`;
506
+ }
304
507
  }
305
508
 
306
509
  const NO_PROJECT =
@@ -320,6 +523,21 @@ async function loadCredentials(io: CliIo): Promise<Credentials | undefined> {
320
523
  }
321
524
  }
322
525
 
526
+ /**
527
+ * What is about to be kept, where the credentials file would read it back; else the command
528
+ * stops, and nothing is written. What a console answered comes to rest in that file, and
529
+ * anything at an address may answer to nobody: kept beyond the file's own bounds, it would have
530
+ * every later command stop on a file it cannot read, at every console.
531
+ */
532
+ function fitting(next: Credentials, url: string): Credentials {
533
+ if (!fitsFile(next)) {
534
+ throw failed(
535
+ `${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.`,
536
+ );
537
+ }
538
+ return next;
539
+ }
540
+
323
541
  /** The console a directory is bound to, as an origin, when it names one. */
324
542
  function directoryOrigin(settings: DirectorySettings | undefined): string | undefined {
325
543
  if (settings?.url === undefined) {
@@ -384,8 +602,19 @@ async function open(io: CliIo, values: Values): Promise<Session> {
384
602
  : undefined,
385
603
  );
386
604
  const client = clientOf(io, url, token);
387
- const projectKey = async () =>
388
- text(values, "project") ?? io.env.CONSOLE_PROJECT ?? directory?.project;
605
+ const projectNamed = (): ReturnType<Session["projectNamed"]> => {
606
+ const flagged = text(values, "project");
607
+ if (flagged !== undefined) {
608
+ return { key: flagged, source: { kind: "flag" } };
609
+ }
610
+ if (io.env.CONSOLE_PROJECT !== undefined) {
611
+ return { key: io.env.CONSOLE_PROJECT, source: { kind: "environment" } };
612
+ }
613
+ return directory === undefined
614
+ ? undefined
615
+ : { key: directory.project, source: { kind: "directory", directory: directory.directory } };
616
+ };
617
+ const projectKey = async () => projectNamed()?.key;
389
618
  return {
390
619
  client,
391
620
  url,
@@ -395,12 +624,19 @@ async function open(io: CliIo, values: Values): Promise<Session> {
395
624
  credentials,
396
625
  json: on(values, "json"),
397
626
  projectKey,
627
+ projectNamed,
398
628
  async project() {
399
- const key = await projectKey();
400
- if (key === undefined) {
629
+ const named = projectNamed();
630
+ if (named === undefined) {
401
631
  throw failed(NO_PROJECT);
402
632
  }
403
- return client.project(key);
633
+ // A key typed on the command is in front of whoever typed it; one the directory or the
634
+ // environment named is not, and is said with the refusal.
635
+ return named.source.kind === "flag"
636
+ ? client.project(named.key)
637
+ : namingUnseen(client.project(named.key), () =>
638
+ unseenProjectWords(url, named, resolved.account),
639
+ );
404
640
  },
405
641
  };
406
642
  }
@@ -411,17 +647,38 @@ function answer(io: CliIo, session: Session, value: unknown, words: () => string
411
647
  }
412
648
 
413
649
  /** The run a command on a run means: the one named, else the one open run of this token in the project. */
414
- async function currentRun(project: ProjectClient, values: Values): Promise<string> {
650
+ async function currentRun(
651
+ session: Session,
652
+ project: ProjectClient,
653
+ values: Values,
654
+ ): Promise<string> {
415
655
  const given = text(values, "run");
416
656
  if (given !== undefined) {
417
657
  return given;
418
658
  }
419
- const { items } = await project.runs({ open: true, mine: true });
659
+ // The brief form: a command on a run asks which run is open every time, and needs no report
660
+ // of it, where a long run has many.
661
+ const { items } = await project.runBriefs({ open: true, mine: true });
420
662
  const [only] = items;
421
663
  if (only !== undefined && items.length === 1) {
422
664
  return only.id;
423
665
  }
424
666
  if (items.length === 0) {
667
+ // A run is its person's, and `mine` is this token's: a run begun through another of the
668
+ // person's agents, or before the command was signed in again, is open all the same, and
669
+ // goes on by its id. It is named before any word of taking, since taking its task again
670
+ // would end it, a run that waits for a decision included.
671
+ const theirs = await openRunsOfThePerson(session, project);
672
+ if (theirs.length > 0) {
673
+ const one = theirs.length === 1;
674
+ throw failed(
675
+ [
676
+ `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:`,
677
+ ...theirs.map((run) => ` ${formatRunLine(run)}`),
678
+ `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.`,
679
+ ].join("\n"),
680
+ );
681
+ }
425
682
  throw failed(
426
683
  "run.none: no run of yours is open in this project. Take a task first: console take <number>; or name a run: --run <id>",
427
684
  );
@@ -431,6 +688,30 @@ async function currentRun(project: ProjectClient, values: Values): Promise<strin
431
688
  );
432
689
  }
433
690
 
691
+ /**
692
+ * The open runs of the project that are for the person the command acts as, whichever of their
693
+ * agents began them: what a command on a run looks through when none was begun with its own
694
+ * token. A courtesy before a refusal: where the console does not answer it, there are none.
695
+ */
696
+ async function openRunsOfThePerson(
697
+ session: Session,
698
+ project: ProjectClient,
699
+ ): Promise<readonly RestRunBrief[]> {
700
+ try {
701
+ const [me, open] = await Promise.all([
702
+ session.client.me(),
703
+ project.runBriefs({ open: true, limit: LIST_LIMIT }),
704
+ ]);
705
+ const person = me.person;
706
+ return person === null ? [] : open.items.filter((run) => run.person.id === person.id);
707
+ } catch (error) {
708
+ if (error instanceof ApiError) {
709
+ return [];
710
+ }
711
+ throw error;
712
+ }
713
+ }
714
+
434
715
  /** A Markdown body: from `--file`, from standard input for `-`, or as given. */
435
716
  async function bodyOf(
436
717
  io: CliIo,
@@ -693,6 +974,8 @@ async function settle(
693
974
  decision: RestDecision,
694
975
  seconds: number,
695
976
  shown = false,
977
+ /** What is said where the decision still waits, in place of how an attended agent waits on. */
978
+ waiting?: string,
696
979
  ): Promise<number> {
697
980
  const outcome =
698
981
  decision.answer === null && seconds > 0
@@ -703,13 +986,64 @@ async function settle(
703
986
  io.stdout(`${JSON.stringify(outcome, null, 2)}\n`);
704
987
  }
705
988
  } else {
706
- io.stdout(`${outcome.answer === null ? stillWaiting(outcome.id) : formatAnswer(outcome)}\n`);
989
+ io.stdout(
990
+ `${outcome.answer === null ? (waiting ?? stillWaiting(outcome.id)) : formatAnswer(outcome)}\n`,
991
+ );
707
992
  }
708
993
  return outcome.answer === null ? EXIT.waiting : EXIT.ok;
709
994
  }
710
995
 
996
+ /**
997
+ * Whether the command is signed in as the account itself (ADR-0084), which is how an agent
998
+ * account's own command is: what the login kept says, and nothing the environment's pair does.
999
+ */
1000
+ function signedInAsItself(session: Session): boolean {
1001
+ return (
1002
+ session.via === "login" &&
1003
+ session.credentials?.logins.find(
1004
+ (kept) => kept.url === session.url && kept.account === session.account,
1005
+ )?.self === true
1006
+ );
1007
+ }
1008
+
1009
+ /**
1010
+ * The address of a task's page at the console the command talks to: the console's origin and
1011
+ * the path the pages route a task by (ADR-0010), made here and asked of no console. An agent
1012
+ * that tells a person of a task links this, and not the console's front page; nothing where
1013
+ * the command works in no project.
1014
+ */
1015
+ async function taskPage(session: Session, number: number): Promise<string | undefined> {
1016
+ const key = await session.projectKey();
1017
+ return key === undefined ? undefined : `${session.url}${taskHref(key, number)}`;
1018
+ }
1019
+
1020
+ /**
1021
+ * The address of a decision's page: in the project the command reached it in, else the
1022
+ * decision's own (ADR-0068), which whoever it reaches may open, in that project or not.
1023
+ */
1024
+ async function decisionPage(session: Session, id: string, atItsAddress = false): Promise<string> {
1025
+ const key = atItsAddress ? undefined : await session.projectKey();
1026
+ return `${session.url}${key === undefined ? myDecisionHref(id) : decisionHref(key, id)}`;
1027
+ }
1028
+
711
1029
  type Command = (args: readonly string[], io: CliIo) => Promise<number>;
712
1030
 
1031
+ /**
1032
+ * Who the command is, in a few words: the login and the role, and an agent account by its
1033
+ * handle first, which is what it is called by everywhere and what its setup's guide says the
1034
+ * command names.
1035
+ */
1036
+ function whoOf(person: {
1037
+ readonly login: string;
1038
+ readonly role: string;
1039
+ readonly kind?: string | undefined;
1040
+ readonly handle?: string | null | undefined;
1041
+ }): string {
1042
+ return person.kind === "agent" && typeof person.handle === "string" && person.handle.length > 0
1043
+ ? `@${person.handle} (${person.login}, ${person.role})`
1044
+ : `${person.login} (${person.role})`;
1045
+ }
1046
+
713
1047
  /**
714
1048
  * Checks a token against the console, keeps it as the login at that console for that account,
715
1049
  * and says who it is. A token the login replaces is given up at the console on the way.
@@ -720,6 +1054,10 @@ async function keep(
720
1054
  token: string,
721
1055
  agent: string | undefined,
722
1056
  asDefault: boolean,
1057
+ /** Whether what is kept is the command's own session, signed in as the account itself (ADR-0084). */
1058
+ self = false,
1059
+ /** Where the words go: nowhere, for a command that says its own. */
1060
+ say: (text: string) => void = io.stdout,
723
1061
  ): Promise<number> {
724
1062
  const me = await clientOf(io, url, token).me();
725
1063
  const person = me.person;
@@ -729,12 +1067,6 @@ async function keep(
729
1067
  );
730
1068
  }
731
1069
  const credentials = (await loadCredentials(io)) ?? EMPTY_CREDENTIALS;
732
- const replaced = loginsAt(credentials, url).find((login) => login.account === person.login);
733
- if (replaced !== undefined && replaced.token !== token) {
734
- await clientOf(io, url, replaced.token)
735
- .giveUpToken()
736
- .catch(() => undefined);
737
- }
738
1070
  const next = withLogin(
739
1071
  credentials,
740
1072
  {
@@ -743,14 +1075,37 @@ async function keep(
743
1075
  token,
744
1076
  agent,
745
1077
  since: new Date(io.now()).toISOString(),
1078
+ ...(self ? { self: true } : {}),
746
1079
  timeZone: me.workspace.timeZone ?? undefined,
747
1080
  },
1081
+ io.now(),
748
1082
  { default: asDefault },
749
1083
  );
750
- const kept = await io.store.save(next);
1084
+ // A login kept at a console ends the connection that waited there (ADR-0129): its secret
1085
+ // is spent, and is kept no longer. Asked whether it can be kept before the token it replaces
1086
+ // is given up, so that none is given up for one that never was.
1087
+ const keeping = fitting(withoutPending(next, url, io.now()), url);
1088
+ const replaced = loginsAt(credentials, url).find((login) => login.account === person.login);
1089
+ if (replaced !== undefined && replaced.token !== token) {
1090
+ await clientOf(io, url, replaced.token)
1091
+ .giveUpToken()
1092
+ .catch(() => undefined);
1093
+ }
1094
+ const kept = await io.store.save(keeping);
751
1095
  const standing = next.default === url ? ", the default console here" : "";
752
- io.stdout(
753
- `${agent === undefined ? "Signed in" : `Connected as "${agent}"`} to ${me.workspace.name} at ${url} as ${person.login} (${person.role})${standing}. The token is kept in ${kept}.\nNext, say which project this directory works in: console use <key> (console projects lists them).\n`,
1096
+ // Last, what holds where, never a next step: the line once said to bind this directory
1097
+ // next, and a folder that is no checkout of a project's repository, a desk or a home
1098
+ // directory, was bound to a project because it said so.
1099
+ const binding =
1100
+ "Only a project's checkout is bound to it: console use <key> (console projects lists them).";
1101
+ // Where it is kept: the file, for a person at a terminal. Where no terminal shows the words,
1102
+ // an agent reads them, and the path of the one file it must never open is not handed to it.
1103
+ const where =
1104
+ io.terminal === false ? "on this machine by the command, and never shown" : `in ${kept}`;
1105
+ say(
1106
+ self
1107
+ ? `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`
1108
+ : `${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`,
754
1109
  );
755
1110
  return EXIT.ok;
756
1111
  }
@@ -758,7 +1113,13 @@ async function keep(
758
1113
  const login: Command = async (args, io) => {
759
1114
  const { values } = parse(
760
1115
  args,
761
- { "token-stdin": { type: "boolean" }, agent: { type: "string" }, default: { type: "boolean" } },
1116
+ {
1117
+ "token-stdin": { type: "boolean" },
1118
+ agent: { type: "string" },
1119
+ self: { type: "boolean" },
1120
+ default: { type: "boolean" },
1121
+ wait: { type: "string" },
1122
+ },
762
1123
  false,
763
1124
  );
764
1125
  const credentials = await loadCredentials(io);
@@ -778,30 +1139,167 @@ const login: Command = async (args, io) => {
778
1139
  // A connection (ADR-0011): a code a person approves on the console's own pages, and the token
779
1140
  // handed over here once, never shown.
780
1141
  const client = clientOf(io, url);
781
- // "<agent> on <machine>": the pages say the agent and keep the machine for a hover.
782
- const agent = text(values, "agent") ?? agentOf(io.env) ?? "An agent";
783
- const begun = await client.connect({
784
- agent: io.hostname === undefined ? agent : `${agent} on ${io.hostname}`,
785
- });
786
- io.stdout(
787
- `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`,
788
- );
1142
+ // With --self the command asks to be the account itself (ADR-0084): whoever approves says
1143
+ // "this is me", and what is handed over is a session of the command's, in place of a token.
1144
+ const self = on(values, "self");
1145
+ // Where no terminal shows the command's words as they are printed, whoever runs it sees them
1146
+ // when it ends: an agent's host held the address and the code back until its own limit, two
1147
+ // minutes on, while a person waited for them. There the call that begins a connection says
1148
+ // them and ends, and the next call waits for the approval (ADR-0129).
1149
+ const attended = io.terminal !== false;
1150
+ const wait = text(values, "wait");
1151
+ const waitGiven = wait === undefined ? undefined : secondsOf(wait, 0);
1152
+ // The end of the wait is a moment as any other the command prints (ADR-0035): in the
1153
+ // workspace's time zone where a login at this console kept it, which is one zone whoever
1154
+ // signed in; on a first sign-in, when none is known yet, in the machine's own, since an agent
1155
+ // relays the moment to a person; as the API gave it where the machine says none.
1156
+ setMomentZone(credentials?.logins.find((login) => login.url === url)?.timeZone ?? io.timeZone);
1157
+ const again = `console login --url ${url}${self ? " --self" : ""}`;
1158
+ /** Whom the code is shown to, and what they do with it. */
1159
+ const asked = (page: string, code: string): string =>
1160
+ self
1161
+ ? `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.`
1162
+ : `To connect this agent, a person opens ${page} signed in, checks that the page shows the code ${code}, names the agent and approves.`;
1163
+ /** Forgets the connection kept for this console, and any whose code ran out; writes nothing where none was kept. */
1164
+ const forget = async (): Promise<void> => {
1165
+ const kept = await loadCredentials(io);
1166
+ if (kept === undefined || (kept.pending ?? []).length === 0) {
1167
+ return;
1168
+ }
1169
+ const next = withoutPending(kept, url, io.now());
1170
+ if (keepsNothing(next)) {
1171
+ await io.store.clear();
1172
+ } else {
1173
+ await io.store.save(next);
1174
+ }
1175
+ };
1176
+
1177
+ // A connection a call before this one began at this console, of the kind this call asks for:
1178
+ // it is gone on with, and no new code is made while its code lasts.
1179
+ let waiting = pendingAt(credentials, url);
1180
+ if (waiting !== undefined && ((waiting.self === true) !== self || !lasts(waiting, io.now()))) {
1181
+ const ranOut = !lasts(waiting, io.now());
1182
+ await forget();
1183
+ if (ranOut) {
1184
+ io.stdout(`The code ${waiting.code} ran out before a person approved it. A new one:\n`);
1185
+ }
1186
+ waiting = undefined;
1187
+ }
789
1188
  for (;;) {
790
- await io.sleep(begun.interval * 1000);
791
- let claim: RestClaim;
792
- try {
793
- claim = await client.claimConnection(begun.secret);
794
- } catch (error) {
795
- if (error instanceof ApiError && error.code === "connect.not_found") {
1189
+ const resumed = waiting !== undefined;
1190
+ if (waiting === undefined) {
1191
+ // "<agent> on <machine>": the pages say the agent and keep the machine for a hover.
1192
+ const agent = text(values, "agent") ?? agentOf(io.env) ?? "An agent";
1193
+ const begun = await client.connect({
1194
+ agent: io.hostname === undefined ? agent : `${agent} on ${io.hostname}`,
1195
+ ...(self ? { as: "self" as const } : {}),
1196
+ });
1197
+ waiting = {
1198
+ url,
1199
+ secret: begun.secret,
1200
+ code: begun.code,
1201
+ page: begun.url,
1202
+ expiresAt: begun.expiresAt,
1203
+ interval: begun.interval,
1204
+ ...(self ? { self: true } : {}),
1205
+ ...(asDefault ? { default: true } : {}),
1206
+ };
1207
+ // Kept only where this call may end before the approval: at a terminal, with no wait
1208
+ // said, the secret stays in the process as it always did.
1209
+ if (!attended || waitGiven !== undefined) {
1210
+ await io.store.save(
1211
+ fitting(
1212
+ withPending((await loadCredentials(io)) ?? EMPTY_CREDENTIALS, waiting, io.now()),
1213
+ url,
1214
+ ),
1215
+ );
1216
+ }
1217
+ }
1218
+ const pending: PendingConnection = waiting;
1219
+ const until = moment(pending.expiresAt);
1220
+ const end = Date.parse(pending.expiresAt);
1221
+ const seconds =
1222
+ waitGiven ?? (attended ? MAX_WAIT_SECONDS : resumed ? DEFAULT_LOGIN_WAIT_SECONDS : 0);
1223
+ // A call that begins a connection and waits for nothing says what a person does and ends:
1224
+ // the words reach whoever ran it now, and the next call waits. A call that goes on with a
1225
+ // connection says nothing before its wait where no terminal would show it.
1226
+ const told = !resumed && seconds === 0;
1227
+ if (!resumed || attended) {
1228
+ // The telling is a sentence of its own, before the one that names the command: read in
1229
+ // one sentence, an agent ran the command first and told its person after. And the wait
1230
+ // of the next call is said apart from the code's end, which an agent took for how long
1231
+ // that call waits, and gave it half an hour. At a terminal, told not to wait, the next
1232
+ // call there waits while the code lasts, and says so.
1233
+ const next = attended
1234
+ ? `it waits for the approval while the code lasts, until ${until}`
1235
+ : `it waits for the approval up to ${DEFAULT_LOGIN_WAIT_SECONDS} seconds a call, and the code lasts until ${until}`;
1236
+ io.stdout(
1237
+ told
1238
+ ? `${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`
1239
+ : `${asked(pending.page, pending.code)}\nWaiting for that, until ${until}.\n`,
1240
+ );
1241
+ }
1242
+ if (told) {
1243
+ return EXIT.ok;
1244
+ }
1245
+ // Where the call may end before the approval, it waits no longer than it was given, and no
1246
+ // longer than the code lasts; at a terminal with no wait said, until the console says how
1247
+ // the connection ended, as before.
1248
+ const bounded = waitGiven !== undefined || !attended;
1249
+ const deadline = Math.min(
1250
+ io.now() + seconds * 1000,
1251
+ Number.isFinite(end) ? end : Number.POSITIVE_INFINITY,
1252
+ );
1253
+ // A connection gone on with is claimed at once, since its person may have approved between
1254
+ // the two calls; one begun now, after the breath the console asked for, as before.
1255
+ let first = resumed;
1256
+ let gone = false;
1257
+ for (;;) {
1258
+ if (!first) {
1259
+ if (bounded && io.now() + pending.interval * 1000 > deadline) {
1260
+ break;
1261
+ }
1262
+ await io.sleep(pending.interval * 1000);
1263
+ }
1264
+ first = false;
1265
+ let claim: RestClaim;
1266
+ try {
1267
+ claim = await client.claimConnection(pending.secret);
1268
+ } catch (error) {
1269
+ if (error instanceof ApiError && error.code === "connect.not_found") {
1270
+ gone = true;
1271
+ break;
1272
+ }
1273
+ throw error;
1274
+ }
1275
+ if (claim.status === "connected") {
1276
+ return keep(io, url, claim.secret, claim.token.name, asDefault || pending.default === true);
1277
+ }
1278
+ if (claim.status === "signed_in") {
1279
+ return keep(io, url, claim.secret, undefined, asDefault || pending.default === true, true);
1280
+ }
1281
+ }
1282
+ if (gone) {
1283
+ await forget();
1284
+ if (!resumed) {
796
1285
  throw failed(
797
1286
  "The connection was not approved in time, or the person said it was not theirs. Run console login again for a new code.",
798
1287
  );
799
1288
  }
800
- throw error;
801
- }
802
- if (claim.status === "connected") {
803
- return keep(io, url, claim.secret, claim.token.name, asDefault);
1289
+ // A connection kept from a call before, which the console no longer knows: its code ran
1290
+ // out there, or a person said it was not theirs. It is forgotten, and a new one begun.
1291
+ io.stdout(
1292
+ `The code ${pending.code} is good no longer: it ran out, or a person said the connection was not theirs. A new one:\n`,
1293
+ );
1294
+ waiting = undefined;
1295
+ continue;
804
1296
  }
1297
+ // The wait this call was given is over and the code still lasts: the connection stays kept,
1298
+ // and the same command goes on waiting for it.
1299
+ io.stdout(
1300
+ `${self ? "Not signed in yet" : "Not approved yet"}. ${asked(pending.page, pending.code)}\nKeep waiting with: ${again}, as often as needed until ${until}.\n`,
1301
+ );
1302
+ return EXIT.waiting;
805
1303
  }
806
1304
  };
807
1305
 
@@ -815,7 +1313,14 @@ const logout: Command = async (args, io) => {
815
1313
  }
816
1314
  };
817
1315
  if (credentials === undefined || credentials.logins.length === 0) {
818
- io.stdout("Not signed in here: nothing to forget.\n");
1316
+ // Nobody is signed in; a connection that waited for a person is forgotten all the same
1317
+ // (ADR-0129), with its secret.
1318
+ if (credentials !== undefined && (credentials.pending ?? []).length > 0) {
1319
+ await io.store.clear();
1320
+ io.stdout("Not signed in here; the connection that waited for a person is forgotten.\n");
1321
+ } else {
1322
+ io.stdout("Not signed in here: nothing to forget.\n");
1323
+ }
819
1324
  envNote();
820
1325
  return EXIT.ok;
821
1326
  }
@@ -839,8 +1344,19 @@ const logout: Command = async (args, io) => {
839
1344
  const chosen = account === undefined ? at : at.filter((login) => login.account === account);
840
1345
  const [login] = chosen;
841
1346
  if (login === undefined) {
1347
+ const whom = account === undefined ? "" : ` as ${account}`;
1348
+ // Nobody to sign out there; a connection that waits for a person at that console is
1349
+ // forgotten all the same (ADR-0129): signing out of a console leaves no secret of it here.
1350
+ if (pendingAt(credentials, url) !== undefined) {
1351
+ await io.store.save(withoutPending(credentials, url, io.now()));
1352
+ io.stdout(
1353
+ `Nobody is signed in here at ${url}${whom}; the connection that waited for a person there is forgotten.\n`,
1354
+ );
1355
+ envNote();
1356
+ return EXIT.ok;
1357
+ }
842
1358
  throw failed(
843
- `Nobody is signed in here at ${url}${account === undefined ? "" : ` as ${account}`}: nothing to forget. console logins lists the consoles signed in.`,
1359
+ `Nobody is signed in here at ${url}${whom}: nothing to forget. console logins lists the consoles signed in.`,
844
1360
  );
845
1361
  }
846
1362
  if (chosen.length > 1) {
@@ -865,8 +1381,14 @@ const logout: Command = async (args, io) => {
865
1381
  outcome = "left";
866
1382
  }
867
1383
  }
868
- const next = withoutLogin(credentials, url, login.account);
869
- if (next.logins.length === 0) {
1384
+ // A connection that waited at this console goes with its login (ADR-0129), as does any
1385
+ // whose code ran out: signing out leaves no secret of the console here.
1386
+ const next = withoutPending(
1387
+ withoutLogin(credentials, url, io.now(), login.account),
1388
+ url,
1389
+ io.now(),
1390
+ );
1391
+ if (keepsNothing(next)) {
870
1392
  await io.store.clear();
871
1393
  } else {
872
1394
  await io.store.save(next);
@@ -891,27 +1413,54 @@ const logins: Command = async (args, io) => {
891
1413
  url: login.url,
892
1414
  account: login.account ?? null,
893
1415
  agent: login.agent ?? null,
1416
+ // The command's own session, signed in as the account itself (ADR-0084), where so.
1417
+ self: login.self === true,
894
1418
  since: login.since ?? null,
895
1419
  default: credentials?.default === login.url,
896
1420
  }));
1421
+ // The connections that wait for a person while their codes last (ADR-0129): the console, the
1422
+ // code and its end, never the secret; one whose code ran out is not shown.
1423
+ const waiting = (credentials?.pending ?? [])
1424
+ .filter((pending) => lasts(pending, io.now()))
1425
+ .map((pending) => ({
1426
+ url: pending.url,
1427
+ code: pending.code,
1428
+ expiresAt: pending.expiresAt,
1429
+ self: pending.self === true,
1430
+ }));
897
1431
  if (on(values, "json")) {
898
1432
  io.stdout(
899
- `${JSON.stringify({ default: credentials?.default ?? null, logins: kept }, null, 2)}\n`,
1433
+ `${JSON.stringify(
1434
+ {
1435
+ default: credentials?.default ?? null,
1436
+ logins: kept,
1437
+ ...(waiting.length === 0 ? {} : { waiting }),
1438
+ },
1439
+ null,
1440
+ 2,
1441
+ )}\n`,
900
1442
  );
901
1443
  return EXIT.ok;
902
1444
  }
1445
+ const lines = [
1446
+ ...kept.map(
1447
+ (login) =>
1448
+ `${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)" : ""}`,
1449
+ ),
1450
+ ];
1451
+ for (const pending of waiting) {
1452
+ // The code's end as login printed it: in the zone a login at that console kept, else the machine's.
1453
+ setMomentZone(
1454
+ credentials?.logins.find((login) => login.url === pending.url)?.timeZone ?? io.timeZone,
1455
+ );
1456
+ lines.push(
1457
+ `${pending.url} waits for a person to approve the code ${pending.code}, until ${moment(pending.expiresAt)}: console login --url ${pending.url}${pending.self ? " --self" : ""}`,
1458
+ );
1459
+ }
903
1460
  if (kept.length === 0) {
904
- io.stdout("Not signed in anywhere here: console login --url <the console's origin>\n");
905
- return EXIT.ok;
1461
+ lines.unshift("Not signed in anywhere here: console login --url <the console's origin>");
906
1462
  }
907
- io.stdout(
908
- `${kept
909
- .map(
910
- (login) =>
911
- `${login.url} ${login.account ?? "(account unknown)"}${login.agent === null ? "" : ` ${login.agent}`}${login.since === null ? "" : ` since ${login.since.slice(0, 10)}`}${login.default ? " (default)" : ""}`,
912
- )
913
- .join("\n")}\n`,
914
- );
1463
+ io.stdout(`${lines.join("\n")}\n`);
915
1464
  return EXIT.ok;
916
1465
  };
917
1466
 
@@ -941,7 +1490,10 @@ async function rememberZone(io: CliIo, session: Session, zone: string | undefine
941
1490
  if (kept === undefined || kept.timeZone === zone) {
942
1491
  return;
943
1492
  }
944
- await io.store.save(withLogin(session.credentials, { ...kept, timeZone: zone }));
1493
+ // Kept anew, and so without a connection whose code ran out (ADR-0129).
1494
+ await io.store.save(
1495
+ fitting(withLogin(session.credentials, { ...kept, timeZone: zone }, io.now()), session.url),
1496
+ );
945
1497
  }
946
1498
 
947
1499
  const whoami: Command = async (args, io) => {
@@ -953,7 +1505,29 @@ const whoami: Command = async (args, io) => {
953
1505
  throw failed("The console does not know this token. Sign in again: console login");
954
1506
  }
955
1507
  await rememberZone(io, session, me.workspace.timeZone ?? undefined);
956
- const key = await session.projectKey();
1508
+ // The project the directory names is asked of the console (ADR-0112): a key repeated from a
1509
+ // file says nothing of whether this console has the project, or shows it to this member, and
1510
+ // an agreement has its agents check the binding with this command before the first one on
1511
+ // the board. Where the key came from is said either way, since that is where it is mended.
1512
+ const named = session.projectNamed();
1513
+ const key = named?.key;
1514
+ let projectName: string | undefined;
1515
+ if (named !== undefined) {
1516
+ try {
1517
+ projectName = (await session.client.project(named.key).get()).name;
1518
+ } catch (error) {
1519
+ if (!(error instanceof ApiError && error.code === "project.not_found")) {
1520
+ throw error;
1521
+ }
1522
+ }
1523
+ }
1524
+ const missing = named !== undefined && projectName === undefined;
1525
+ const projectWords =
1526
+ named === undefined
1527
+ ? "; no project named here"
1528
+ : projectName === undefined
1529
+ ? `; project ${named.key}, named by ${sourceWords(named.source)}, which this console does not have or does not show you`
1530
+ : `; project ${named.key} (${projectName}), named by ${sourceWords(named.source)}`;
957
1531
  const command = parseVersion(io.version);
958
1532
  const server = parseVersion(me.console?.version);
959
1533
  const verdict =
@@ -976,17 +1550,23 @@ const whoami: Command = async (args, io) => {
976
1550
  ...me,
977
1551
  console: me.console ?? null,
978
1552
  project: key ?? null,
1553
+ projectName: projectName ?? null,
1554
+ projectSource: named?.source ?? null,
979
1555
  command: { version: io.version ?? null, install: io.install ?? null },
980
1556
  },
981
1557
  () =>
982
1558
  [
983
- `${person.login} (${person.role}) at ${me.workspace.name}, ${session.url}${key === undefined ? "; no project named here" : `; project ${key}`}`,
984
- // The pack's rules send an agent here first; from here the rules and the skill are the next steps.
985
- ...(key === undefined
986
- ? []
987
- : [
988
- `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)}`}`,
989
- ]),
1559
+ `${whoOf(person)} at ${me.workspace.name}, ${session.url}${projectWords}${me.session?.kind === "command" ? "; signed in as the account itself" : ""}`,
1560
+ // The sentence of a checkout's agreement sends an agent here first and says that this
1561
+ // answer says how: so it says what is read before the first task, the rules and the
1562
+ // skill, and that one command's flags are read from that command's help, since an agent
1563
+ // that has the skill was reading the whole help beside it. In a directory that names
1564
+ // no project too: an agent account's desk names none, the command's help sends an
1565
+ // agent here for where the skill is, and the workspace has rules whatever the project.
1566
+ // The skill's path stands last, with nothing after it, to be copied as it is.
1567
+ io.skillsDir === undefined
1568
+ ? "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>."
1569
+ : `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)}`,
990
1570
  `This command is ${io.version ?? "of a version it does not know"}${io.install === undefined ? "" : `, ${describeInstall(io.install)}`}; ${consoleWords}.`,
991
1571
  ...(verdict === "behind"
992
1572
  ? [`A newer command exists. Update it: ${updateWords(io, me.console?.version)}`]
@@ -997,6 +1577,11 @@ const whoami: Command = async (args, io) => {
997
1577
  : []),
998
1578
  ].join("\n"),
999
1579
  );
1580
+ if (missing && named !== undefined) {
1581
+ // Who and where are said above, which is what mends it; the command still ends as refused,
1582
+ // so that a check of the binding never passes on a key alone.
1583
+ throw failed(unseenProjectWords(session.url, named, person.login));
1584
+ }
1000
1585
  return EXIT.ok;
1001
1586
  };
1002
1587
 
@@ -1020,26 +1605,23 @@ const use: Command = async (args, io) => {
1020
1605
  );
1021
1606
  const session = await open(io, values);
1022
1607
  const project = await session.client.project(key).get();
1023
- // The directory names the console where that is not the default login here, or when asked,
1024
- // and the account where the console has several, or when asked; never a token.
1025
- const credentials = session.credentials ?? EMPTY_CREDENTIALS;
1026
- const pinUrl =
1027
- text(values, "url") !== undefined ||
1028
- (session.via === "login" && credentials.default !== session.url);
1608
+ // The directory names the console every time (ADR-0112): what is the default login on this
1609
+ // machine is another console's on the next, and a file that said only the project would
1610
+ // follow it there. The account only when asked, or where the directory named it before, so
1611
+ // that a file to be committed never carries somebody's account unasked; never a token.
1612
+ const before = await io.directory.load();
1029
1613
  const pinAccount =
1030
- text(values, "account") !== undefined ||
1031
- (session.via === "login" && loginsAt(credentials, session.url).length > 1);
1614
+ session.account !== undefined &&
1615
+ (text(values, "account") !== undefined || before?.account === session.account);
1032
1616
  const kept = await io.directory.save({
1033
1617
  project: project.key,
1034
- ...(pinUrl ? { url: session.url } : {}),
1035
- ...(pinAccount && session.account !== undefined ? { account: session.account } : {}),
1618
+ url: session.url,
1619
+ ...(pinAccount ? { account: session.account } : {}),
1036
1620
  });
1037
- const bound = pinUrl
1038
- ? ` at ${session.url}${pinAccount && session.account !== undefined ? ` as ${session.account}` : ""}`
1039
- : "";
1621
+ const bound = ` at ${session.url}${pinAccount ? ` as ${session.account}` : ""}`;
1040
1622
  answer(io, session, project, () =>
1041
1623
  [
1042
- `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.`,
1624
+ `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.`,
1043
1625
  // Nothing sends an agent to the console until the checkout says so; the sentence is the
1044
1626
  // skill's (references/the-sentence.md), printed here as `skillcdn use` prints its own.
1045
1627
  "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:",
@@ -1113,7 +1695,7 @@ const tasks: Command = async (args, io) => {
1113
1695
  if (search === "") {
1114
1696
  throw misuse("Say what to search for: console tasks --search <words>");
1115
1697
  }
1116
- const found = await project.tasks({
1698
+ const filter = {
1117
1699
  ...(state === undefined ? {} : { state }),
1118
1700
  ...(on(values, "open") || due === "overdue" ? { open: true } : {}),
1119
1701
  ...(worker === undefined ? {} : { worker }),
@@ -1124,10 +1706,22 @@ const tasks: Command = async (args, io) => {
1124
1706
  ...(search === undefined ? {} : { q: search }),
1125
1707
  ...(on(values, "archived") ? { archived: true } : {}),
1126
1708
  ...page,
1127
- });
1709
+ };
1710
+ // A line a task and no body: the listing is asked for in the brief form, without the bodies,
1711
+ // which weigh more than the rest of a page together. --json is the console's own answer, whole.
1712
+ const found = session.json ? await project.tasks(filter) : await project.taskBriefs(filter);
1713
+ // A search that finds nothing says how it looked: every word must be in a title, so three
1714
+ // words find nothing where one of them finds the task, and an agent that read "No tasks."
1715
+ // wrote the same work a second time.
1716
+ const none =
1717
+ search === undefined
1718
+ ? "No tasks."
1719
+ : /\s/.test(search.trim())
1720
+ ? `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.`
1721
+ : `No tasks: no title holds "${search.trim()}".`;
1128
1722
  answer(io, session, found, () =>
1129
1723
  found.items.length === 0
1130
- ? "No tasks."
1724
+ ? none
1131
1725
  : found.items.map(formatTaskLine).join("\n") +
1132
1726
  formatMore(found.more, page.limit, page.offset),
1133
1727
  );
@@ -1160,138 +1754,42 @@ const categories: Command = async (args, io) => {
1160
1754
  return EXIT.ok;
1161
1755
  };
1162
1756
 
1163
- /** How many pages of a skill, of a file or of a folder the command follows before it stops: far above what one holds. */
1164
- const MAX_SKILL_PAGES = 64;
1165
- /** How many results a search answers at most: what the deployment allows on one page. */
1166
- const MAX_FIND_LIMIT = 25;
1167
-
1168
- /** The pack of the project as the console lists it, and what its reads are rendered at; none when the pack did not answer. */
1169
- async function packOf(
1170
- reader: PackReader,
1171
- ): Promise<{ readonly listing: RestSkills; readonly summary: PackSummary | undefined }> {
1172
- const listing = await reader.skills();
1173
- return { listing, summary: summaryOf(listing) };
1174
- }
1175
-
1176
- /** What reads a pack: a project's client, or a plugin's, whose skills are a pack of their own. */
1177
- type PackReader = Pick<
1178
- ProjectClient,
1179
- "skills" | "skill" | "skillFile" | "skillBrowse" | "skillFind"
1180
- >;
1757
+ /** What reads a pack: a project's client, a plugin's, whose skills are a pack of their own, or the console's for the organization's. */
1758
+ type PackReader = PackClient;
1181
1759
 
1182
1760
  const SKILLS_OPTIONS: OptionSpec = {
1183
1761
  search: { type: "string" },
1762
+ path: { type: "string" },
1184
1763
  limit: { type: "string" },
1185
1764
  cursor: { type: "string" },
1765
+ rows: { type: "boolean" },
1766
+ code: { type: "boolean" },
1767
+ heading: { type: "string" },
1768
+ format: { type: "string" },
1769
+ grep: { type: "string" },
1770
+ out: { type: "string" },
1186
1771
  };
1187
1772
 
1188
- const SKILL_OPTIONS: OptionSpec = {
1189
- file: { type: "string" },
1190
- offset: { type: "string" },
1191
- limit: { type: "string" },
1192
- };
1193
-
1194
- /** The line `console skills` ends with: where the plugins' own skills are. */
1195
- const PLUGIN_SKILLS_LINE =
1196
- "The plugins of this console have skills of their own: console plugins lists the plugins, console plugin <key> skills the skills of one.";
1197
-
1198
1773
  /**
1199
- * The pack as the words say: whole, a folder of it, a file's outline, or what words find; for
1200
- * the project's pack as `console skills`, and for a plugin's as `console plugin <key> skills`.
1774
+ * A read the pack refused, as the command ends on it (ADR-0118): the words on standard error
1775
+ * and the exit of a refusal, as the skillcdn command ends one, where the pack's answer was once
1776
+ * printed as if it were the read. `--json` still prints what the console answered, which says
1777
+ * the status. Thrown by the caller, so that nothing follows it.
1201
1778
  */
1202
- async function readSkills(
1779
+ function refusedRead(
1203
1780
  io: CliIo,
1204
1781
  session: Session,
1205
- reader: PackReader,
1206
- values: Values,
1207
- positionals: readonly string[],
1208
- extras: {
1209
- /** The command these words came after, for what is said when they are not understood. */
1210
- readonly command: string;
1211
- /** Where the console's own skills are on this machine, said with the project's pack. */
1212
- readonly own?: string | undefined;
1213
- /** A line after the listing whole. */
1214
- readonly afterwards?: string | undefined;
1215
- },
1216
- ): Promise<number> {
1217
- if (positionals.length > 1) {
1218
- throw misuse(`Say one folder: ${extras.command} [<folder>] [--search <words>]`);
1219
- }
1220
- // The root of the pack is the mounted folder, which the deployment reads as no path at all.
1221
- const given = positionals[0];
1222
- const folder = given === undefined || given === "/" || given === "." ? undefined : given;
1223
- const words = text(values, "search");
1224
- const limit = text(values, "limit");
1225
- const cursor = text(values, "cursor");
1226
- if (words === undefined && (limit !== undefined || cursor !== undefined)) {
1227
- throw misuse(
1228
- `--limit and --cursor go with --search: ${extras.command} --search <words> [--limit <n>] [--cursor <cursor>]`,
1229
- );
1230
- }
1231
- const atMost = limit === undefined ? undefined : Number(limit);
1232
- if (
1233
- atMost !== undefined &&
1234
- (!Number.isInteger(atMost) || atMost < 1 || atMost > MAX_FIND_LIMIT)
1235
- ) {
1236
- throw misuse(`Not a number of results, 1 to ${MAX_FIND_LIMIT}: ${limit}`);
1237
- }
1238
- const { listing, summary } = await packOf(reader);
1239
- // The pack as it stands; or why it does not answer, which a folder or a search would meet too.
1240
- if (summary === undefined || (words === undefined && given === undefined)) {
1241
- answer(io, session, listing, () =>
1242
- [formatSkills(listing, extras.own), extras.afterwards]
1243
- .filter((part): part is string => part !== undefined)
1244
- .join("\n"),
1245
- );
1246
- return EXIT.ok;
1247
- }
1248
- if (words !== undefined) {
1249
- // One page of what the words find; more is said, and asked for with --cursor.
1250
- const found = await reader.skillFind(words, { path: folder, limit: atMost, cursor });
1251
- answer(io, session, found, () => formatSkillFind(found, summary));
1252
- return EXIT.ok;
1253
- }
1254
- // The folder whole: its pages until the end, as the pack lists them.
1255
- const pages: RestSkillBrowse[] = [];
1256
- let next: string | undefined;
1257
- let last: RestSkillBrowse | undefined;
1258
- for (let n = 0; n < MAX_SKILL_PAGES; n += 1) {
1259
- last = await reader.skillBrowse({ path: folder, cursor: next });
1260
- if (last.read?.status !== "ready") {
1261
- break;
1262
- }
1263
- pages.push(last);
1264
- next = last.read.nextCursor ?? undefined;
1265
- if (next === undefined) {
1266
- break;
1267
- }
1268
- }
1269
- if (last === undefined) {
1270
- throw failed("The folder could not be read.");
1782
+ owner: PackOwner,
1783
+ answered: unknown,
1784
+ words: string,
1785
+ ): CliExit {
1786
+ if (session.json) {
1787
+ io.stdout(`${JSON.stringify(answered, null, 2)}\n`);
1271
1788
  }
1272
- const browsed = last;
1273
- const whole = joinFolder(pages, summary);
1274
- answer(io, session, { ...browsed, read: whole === undefined ? null : bodyOfFolder(whole) }, () =>
1275
- formatSkillBrowse(browsed, whole),
1276
- );
1277
- return EXIT.ok;
1789
+ return failed(owner === "organization" ? `${ORGANIZATION_PACK_LINE}\n${words}` : words);
1278
1790
  }
1279
1791
 
1280
- const skills: Command = async (args, io) => {
1281
- const { values, positionals } = parse(args, SKILLS_OPTIONS);
1282
- const session = await open(io, values);
1283
- const project = await session.project();
1284
- return readSkills(io, session, project, values, positionals, {
1285
- command: "console skills",
1286
- own: io.skillsDir,
1287
- afterwards: PLUGIN_SKILLS_LINE,
1288
- });
1289
- };
1290
-
1291
- /** The most characters one read of a file asks for: what the console's API allows on one page. */
1292
- const MAX_FILE_LIMIT = 100_000;
1293
-
1294
- /** A count given as a flag, within its bounds, or nothing; anything else is not understood. */
1792
+ /** A whole number a flag carries, within its bounds; nothing when it is not given. */
1295
1793
  function countOf(
1296
1794
  given: string | undefined,
1297
1795
  name: string,
@@ -1300,32 +1798,403 @@ function countOf(
1300
1798
  if (given === undefined) {
1301
1799
  return undefined;
1302
1800
  }
1303
- const count = Number(given);
1801
+ const count = /^\d{1,9}$/.test(given) ? Number(given) : Number.NaN;
1304
1802
  if (
1305
- !Number.isInteger(count) ||
1803
+ Number.isNaN(count) ||
1306
1804
  count < bounds.least ||
1307
1805
  (bounds.most !== undefined && count > bounds.most)
1308
1806
  ) {
1309
- const range =
1310
- bounds.most === undefined ? `${bounds.least} or more` : `${bounds.least} to ${bounds.most}`;
1311
- throw misuse(`Not a number for --${name}, ${range}: ${given}`);
1807
+ throw misuse(
1808
+ `--${name} takes an integer ${bounds.most === undefined ? `from ${bounds.least}` : `between ${bounds.least} and ${bounds.most}`}: ${given}`,
1809
+ );
1312
1810
  }
1313
1811
  return count;
1314
1812
  }
1315
1813
 
1316
1814
  /**
1317
- * One skill of the pack whole, a file of it, or one page of a file; for the project's pack as
1318
- * `console skill`, and for a plugin's as `console plugin <key> skill`.
1815
+ * A number a read of a pack takes, checked as the skillcdn command checks it and said in its
1816
+ * words, before anything is asked of the console.
1319
1817
  */
1320
- async function readSkill(
1321
- io: CliIo,
1322
- session: Session,
1323
- reader: PackReader,
1324
- values: Values,
1325
- positionals: readonly string[],
1818
+ function checkedNumber(given: string | undefined, name: string, most: number): void {
1819
+ try {
1820
+ readNumber(given, name, most);
1821
+ } catch (error) {
1822
+ throw error instanceof ReadMisuse ? misuse(error.message) : error;
1823
+ }
1824
+ }
1825
+
1826
+ /**
1827
+ * The flags that say where a pack is read, as they were given, for the command that reads the
1828
+ * next part of a skill (ADR-0124): it is asked as this part was.
1829
+ */
1830
+ function whereGiven(values: Readonly<Record<string, unknown>>): readonly string[] {
1831
+ return ["project", "url", "account"].flatMap((name) => {
1832
+ const value = values[name];
1833
+ return typeof value === "string" ? [`--${name}`, value] : [];
1834
+ });
1835
+ }
1836
+
1837
+ /**
1838
+ * One read of a pack as the skillcdn command makes it (ADR-0124): `readPack` of @skillcdn/cli
1839
+ * over the pack made of the console's answers, in the words of the command the pack is read
1840
+ * with. What the pack refused ends the command as refused (ADR-0118): of one read, in the
1841
+ * pack's own code and words, as that command prints them; of the pack as a whole, in the
1842
+ * console's. A read not asked right is a command not understood. With `data`, nothing is
1843
+ * printed for a refusal even with `--json`: what a program takes is never one.
1844
+ */
1845
+ async function readThrough(
1846
+ io: CliIo,
1847
+ session: Session,
1848
+ owner: PackOwner,
1849
+ pack: ConsolePack,
1850
+ read: PackRead,
1851
+ options: {
1852
+ readonly words: ToolWords;
1853
+ readonly nextPart?: ((cursor: string) => string) | undefined;
1854
+ readonly data?: boolean | undefined;
1855
+ },
1856
+ ): Promise<ReadOutput> {
1857
+ try {
1858
+ return await readPack(pack, read, {
1859
+ words: options.words,
1860
+ json: session.json,
1861
+ nextPart: options.nextPart,
1862
+ });
1863
+ } catch (error) {
1864
+ if (error instanceof ReadMisuse) {
1865
+ throw misuse(error.message);
1866
+ }
1867
+ const refusal =
1868
+ error instanceof PackRefusal
1869
+ ? { answer: error.answer, words: refusalWords(error.what, error.answer, owner) }
1870
+ : error instanceof PackError
1871
+ ? { answer: pack.answered(), words: `${error.code}: ${error.message}` }
1872
+ : undefined;
1873
+ if (refusal === undefined) {
1874
+ throw error;
1875
+ }
1876
+ throw options.data === true || refusal.answer === undefined
1877
+ ? failed(refusal.words)
1878
+ : refusedRead(io, session, owner, refusal.answer, refusal.words);
1879
+ }
1880
+ }
1881
+
1882
+ /**
1883
+ * What `--json` prints for a read: the console's answer, with the pack's own in it as the
1884
+ * skillcdn command's `--json` prints it, the pages of a skill or of a read of data joined.
1885
+ */
1886
+ function jsonOfRead(session: Session, pack: ConsolePack, output: ReadOutput): unknown {
1887
+ return session.json ? { ...pack.answered(), read: JSON.parse(output.text) } : undefined;
1888
+ }
1889
+
1890
+ /**
1891
+ * The tables, or the code blocks, of a document or of every document under a folder, as data
1892
+ * (ADR-0100): read and printed as the skillcdn command prints them, one CSV or an array of rows,
1893
+ * the blocks as written, or written to a file with `--out`. What a program takes is never a
1894
+ * refusal: a read the pack refused fails with why.
1895
+ */
1896
+ async function readData(
1897
+ io: CliIo,
1898
+ session: Session,
1899
+ pack: ConsolePack,
1900
+ asked: {
1901
+ readonly read: Extract<PackRead, { readonly read: "rows" | "code" }>;
1902
+ readonly out: string | undefined;
1903
+ readonly owner: PackOwner;
1904
+ readonly words: ToolWords;
1905
+ },
1906
+ ): Promise<number> {
1907
+ const { read } = asked;
1908
+ const output = await readThrough(io, session, asked.owner, pack, read, {
1909
+ words: asked.words,
1910
+ data: true,
1911
+ });
1912
+ // Nothing is printed for nothing, which a program takes as it is; a line beside it says so.
1913
+ if (holdsNothing(output.holds) && asked.out === undefined && !session.json) {
1914
+ io.stderr(
1915
+ `No ${read.read === "rows" ? "tables" : "code blocks"} in ${read.path ?? "the pack"}${read.heading === undefined ? "" : " under that heading"}.\n`,
1916
+ );
1917
+ }
1918
+ const made = session.json
1919
+ ? JSON.stringify(jsonOfRead(session, pack, output), null, 2)
1920
+ : output.text;
1921
+ const whole = made.endsWith("\n") || made.length === 0 ? made : `${made}\n`;
1922
+ if (asked.out === undefined) {
1923
+ io.stdout(whole);
1924
+ return EXIT.ok;
1925
+ }
1926
+ const name =
1927
+ read.read === "code" ? "code.txt" : read.format === "json" ? "rows.json" : "rows.csv";
1928
+ let saved: string;
1929
+ try {
1930
+ saved = await io.writeBytes(asked.out, new TextEncoder().encode(whole), name);
1931
+ } catch {
1932
+ throw failed(`The file could not be written at ${asked.out}.`);
1933
+ }
1934
+ io.stdout(`${wroteLine(output.holds ?? "", saved)}\n`);
1935
+ return EXIT.ok;
1936
+ }
1937
+
1938
+ const SKILL_OPTIONS: OptionSpec = {
1939
+ file: { type: "string" },
1940
+ offset: { type: "string" },
1941
+ limit: { type: "string" },
1942
+ cursor: { type: "string" },
1943
+ };
1944
+
1945
+ /** The line `console skills` ends with: where the plugins' own skills are. */
1946
+ const PLUGIN_SKILLS_LINE =
1947
+ "The plugins of this console have skills of their own: console plugins lists the plugins, console plugin <key> skills the skills of one.";
1948
+
1949
+ /**
1950
+ * The pack as the words say: whole, a page of a folder or of a file's outline, or what words
1951
+ * find; for the project's pack as `console skills`, and for a plugin's as
1952
+ * `console plugin <key> skills`. Each as the skillcdn command reads it, through its own reads
1953
+ * (ADR-0124).
1954
+ */
1955
+ async function readSkills(
1956
+ io: CliIo,
1957
+ session: Session,
1958
+ reader: PackReader,
1959
+ values: Values,
1960
+ positionals: readonly string[],
1961
+ extras: {
1962
+ /** The command these words came after, for what is said when they are not understood. */
1963
+ readonly command: string;
1964
+ /** Where the console's own skills are on this machine, said with the project's pack. */
1965
+ readonly own?: string | undefined;
1966
+ /** A line after the listing whole. */
1967
+ readonly afterwards?: string | undefined;
1968
+ /** Whose pack it is: the organization's where no project is named (ADR-0113), else a project's. */
1969
+ readonly owner?: PackOwner | undefined;
1970
+ },
1971
+ ): Promise<number> {
1972
+ const owner = extras.owner ?? "project";
1973
+ const say = (value: unknown, words: () => string): void =>
1974
+ answerPack(io, session, owner, value, words);
1975
+ // The reads by the names of this pack's own commands: a plugin's are not the project's.
1976
+ const skillCommand = extras.command.replace(/skills$/, "skill");
1977
+ const toolWords = packWords(extras.command, skillCommand);
1978
+ // How a skill is loaded, said after a listing and after what a search found: the pack's own
1979
+ // words there name how a section is read, and a skill read as a file comes without its rules.
1980
+ 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.`;
1981
+ if (positionals.length > 1) {
1982
+ throw misuse(`Say one folder: ${extras.command} [<folder>] [--search <words>]`);
1983
+ }
1984
+ // The root of the pack is the mounted folder, which the deployment reads as no path at all.
1985
+ const given = positionals[0];
1986
+ const words = text(values, "search");
1987
+ const within = text(values, "path");
1988
+ const limit = text(values, "limit");
1989
+ const cursor = text(values, "cursor");
1990
+ const rows = on(values, "rows");
1991
+ const code = on(values, "code");
1992
+ const heading = text(values, "heading");
1993
+ const out = text(values, "out");
1994
+ const format = text(values, "format");
1995
+ const grep = text(values, "grep");
1996
+ const dataUsage = `${extras.command} --rows|--code [<folder|file>] [--heading <words>] [--out <path>]`;
1997
+ if (rows && code) {
1998
+ throw misuse(`Say one: --rows for the tables, or --code for the code blocks: ${dataUsage}`);
1999
+ }
2000
+ if (
2001
+ (rows || code) &&
2002
+ (words !== undefined || within !== undefined || limit !== undefined || cursor !== undefined)
2003
+ ) {
2004
+ throw misuse(
2005
+ `--rows and --code read a folder or a file whole, and go without --search: ${dataUsage}`,
2006
+ );
2007
+ }
2008
+ if (!rows && !code && (heading !== undefined || out !== undefined)) {
2009
+ throw misuse(`--heading and --out go with --rows or --code: ${dataUsage}`);
2010
+ }
2011
+ if (format !== undefined && !rows) {
2012
+ throw misuse(
2013
+ `--format goes with --rows: ${extras.command} --rows [<folder|file>] [--format csv|json]`,
2014
+ );
2015
+ }
2016
+ if (grep !== undefined && !code) {
2017
+ throw misuse(
2018
+ `--grep goes with --code: ${extras.command} --code [<folder|file>] [--grep <pattern>]`,
2019
+ );
2020
+ }
2021
+ // The folder a search keeps to is said once: after the words, or with --path as the
2022
+ // skillcdn command takes it.
2023
+ if (within !== undefined && words === undefined) {
2024
+ throw misuse(
2025
+ `--path goes with --search; a folder is read with ${extras.command} <folder>: ${extras.command} --search <words> [--path <folder>]`,
2026
+ );
2027
+ }
2028
+ if (within !== undefined && given !== undefined) {
2029
+ throw misuse(
2030
+ `Say the folder once: after the words, or with --path: ${extras.command} --search <words> [<folder>]`,
2031
+ );
2032
+ }
2033
+ const named = given ?? within;
2034
+ const folder = named === undefined || named === "/" || named === "." ? undefined : named;
2035
+ if (words === undefined && given === undefined && (limit !== undefined || cursor !== undefined)) {
2036
+ throw misuse(
2037
+ `--limit and --cursor go with a folder or with --search: ${extras.command} <folder> [--limit <n>] [--cursor <cursor>]`,
2038
+ );
2039
+ }
2040
+ // A page of what words find, or of what a folder holds: the bounds of each, as the pack has them.
2041
+ checkedNumber(limit, "limit", words === undefined ? BROWSE_MAX_LIMIT : FIND_MAX_LIMIT);
2042
+ const listing = await reader.skills();
2043
+ // With --json the console's own addresses stay in a document's outline; in words, the
2044
+ // commands that read its tables and its code blocks.
2045
+ const pack = consolePack(reader, listing, {
2046
+ url: session.url,
2047
+ dataCommand: session.json ? undefined : extras.command,
2048
+ });
2049
+ // As data: a read the pack refused fails with why, and nothing is printed.
2050
+ if (rows || code) {
2051
+ if (pack === undefined) {
2052
+ throw failed(refusalWords(rows ? "tables" : "code blocks", listing, owner));
2053
+ }
2054
+ return readData(io, session, pack, {
2055
+ read: rows
2056
+ ? { read: "rows", path: folder, heading, format }
2057
+ : { read: "code", path: folder, heading, grep },
2058
+ out,
2059
+ owner,
2060
+ words: toolWords,
2061
+ });
2062
+ }
2063
+ // A pack that does not answer: said as that, which a folder or a search would meet too.
2064
+ if (pack === undefined) {
2065
+ throw refusedRead(
2066
+ io,
2067
+ session,
2068
+ owner,
2069
+ listing,
2070
+ [formatSkills(listing, undefined, extras.own, owner, toolWords), extras.afterwards]
2071
+ .filter((part): part is string => part !== undefined)
2072
+ .join("\n"),
2073
+ );
2074
+ }
2075
+ if (words === undefined && given === undefined) {
2076
+ // --json is the console's listing as it answered it; the words are the pack's own, read once more from that answer.
2077
+ const told = session.json
2078
+ ? undefined
2079
+ : await readThrough(io, session, owner, pack, { read: "skills" }, { words: toolWords });
2080
+ say(listing, () =>
2081
+ [formatSkills(listing, told?.text, extras.own, owner, toolWords), loading, extras.afterwards]
2082
+ .filter((part): part is string => part !== undefined)
2083
+ .join("\n"),
2084
+ );
2085
+ return EXIT.ok;
2086
+ }
2087
+ if (words !== undefined) {
2088
+ // One page of what the words find; more is said, and asked for with --cursor.
2089
+ const found = await readThrough(
2090
+ io,
2091
+ session,
2092
+ owner,
2093
+ pack,
2094
+ { read: "find", words, path: folder, cursor, limit },
2095
+ { words: toolWords },
2096
+ );
2097
+ say(jsonOfRead(session, pack, found), () => `${found.text}\n${loading}`);
2098
+ return EXIT.ok;
2099
+ }
2100
+ // One page of the folder, or of a file's outline, as the skillcdn command browses: a page
2101
+ // that ends before the folder does names the cursor that continues it.
2102
+ const browsed = await readThrough(
2103
+ io,
2104
+ session,
2105
+ owner,
2106
+ pack,
2107
+ { read: "browse", path: folder, cursor, limit },
2108
+ { words: toolWords },
2109
+ );
2110
+ say(jsonOfRead(session, pack, browsed), () => browsed.text);
2111
+ return EXIT.ok;
2112
+ }
2113
+
2114
+ /**
2115
+ * The pack a command reads (ADR-0113): the project's where one is named; else the
2116
+ * organization's, which a desk and a folder a repository is about to be made in read, since
2117
+ * neither names a project and the skill that sets one up is in that pack.
2118
+ */
2119
+ async function packNamed(
2120
+ session: Session,
2121
+ ): Promise<{ readonly reader: PackReader; readonly owner: PackOwner }> {
2122
+ return (await session.projectKey()) === undefined
2123
+ ? { reader: session.client.organizationPack(), owner: "organization" }
2124
+ : { reader: await session.project(), owner: "project" };
2125
+ }
2126
+
2127
+ /**
2128
+ * A read of the organization's pack at a console from before ADR-0113, which has no such
2129
+ * routes and answers that nothing is at the path: said as what it is, with what still reads a
2130
+ * pack there, where the console's own words would read as a missing skill.
2131
+ */
2132
+ async function readingPack(owner: PackOwner, read: () => Promise<number>): Promise<number> {
2133
+ try {
2134
+ return await read();
2135
+ } catch (error) {
2136
+ if (owner === "organization" && error instanceof ApiError && error.code === "not_found") {
2137
+ throw failed(
2138
+ `This console does not read the organization's pack where no project is named: it is older than the command. ${NO_PROJECT}`,
2139
+ );
2140
+ }
2141
+ throw error;
2142
+ }
2143
+ }
2144
+
2145
+ /**
2146
+ * Prints a read of a pack: as `answer` does, and, where the pack is the organization's, under
2147
+ * the line that says so. `--json` stays what the console answered.
2148
+ */
2149
+ function answerPack(
2150
+ io: CliIo,
2151
+ session: Session,
2152
+ owner: PackOwner,
2153
+ value: unknown,
2154
+ words: () => string,
2155
+ ): void {
2156
+ answer(io, session, value, () =>
2157
+ owner === "organization" ? `${ORGANIZATION_PACK_LINE}\n${words()}` : words(),
2158
+ );
2159
+ }
2160
+
2161
+ const skills: Command = async (args, io) => {
2162
+ const { values, positionals } = parse(args, SKILLS_OPTIONS);
2163
+ const session = await open(io, values);
2164
+ const { reader, owner } = await packNamed(session);
2165
+ return readingPack(owner, () =>
2166
+ readSkills(io, session, reader, values, positionals, {
2167
+ command: "console skills",
2168
+ own: io.skillsDir,
2169
+ afterwards: PLUGIN_SKILLS_LINE,
2170
+ owner,
2171
+ }),
2172
+ );
2173
+ };
2174
+
2175
+ /**
2176
+ * One skill of the pack, or a page of a file of it; for the project's pack as `console skill`,
2177
+ * and for a plugin's as `console plugin <key> skill`. Each as the skillcdn command reads it,
2178
+ * through its own reads (ADR-0124): a skill whole where a host shows it whole, else in parts,
2179
+ * each ending with the command that reads the next; a file a page at a time. `again` is what
2180
+ * that command says after the cursor, its words: where the pack is read, as it was said for this
2181
+ * part.
2182
+ */
2183
+ async function readSkill(
2184
+ io: CliIo,
2185
+ session: Session,
2186
+ reader: PackReader,
2187
+ values: Values,
2188
+ positionals: readonly string[],
1326
2189
  command: string,
2190
+ owner: PackOwner = "project",
2191
+ again: readonly string[] = [],
1327
2192
  ): Promise<number> {
2193
+ const say = (value: unknown, words: () => string): void =>
2194
+ answerPack(io, session, owner, value, words);
2195
+ const toolWords = packWords(`${command}s`, command);
1328
2196
  const file = text(values, "file");
2197
+ const cursor = text(values, "cursor");
1329
2198
  // A file is read by its own path from the repository's root; a skill's path beside it would be
1330
2199
  // ignored, which reads as if it mattered, so the two together are not understood.
1331
2200
  if (file !== undefined && positionals.length > 0) {
@@ -1333,7 +2202,7 @@ async function readSkill(
1333
2202
  `Say one: ${command} <path of its SKILL.md> for a skill, or ${command} --file <path> for a file of the pack.`,
1334
2203
  );
1335
2204
  }
1336
- // A section is a page of a file read as asked (SkillCDN 0.4): the flags mean nothing without one.
2205
+ // A page of a file is asked for by where it begins and how long it is: the flags mean nothing without one.
1337
2206
  if (
1338
2207
  file === undefined &&
1339
2208
  (text(values, "offset") !== undefined || text(values, "limit") !== undefined)
@@ -1342,90 +2211,92 @@ async function readSkill(
1342
2211
  `--offset and --limit go with --file: ${command} --file <path> [--offset <n>] [--limit <n>]`,
1343
2212
  );
1344
2213
  }
1345
- const offset = countOf(text(values, "offset"), "offset", { least: 0 });
1346
- const limit = countOf(text(values, "limit"), "limit", { least: 1, most: MAX_FILE_LIMIT });
1347
- const { listing, summary } = await packOf(reader);
1348
- if (summary === undefined) {
1349
- answer(io, session, listing, () => formatSkills(listing, io.skillsDir));
1350
- return EXIT.ok;
2214
+ // The next part of a skill is asked for by the cursor its part ended with; a file reads on from an offset.
2215
+ if (file !== undefined && cursor !== undefined) {
2216
+ throw misuse(
2217
+ `--cursor reads the next part of a skill; a file reads on from --offset: ${command} --file <path> [--offset <n>] [--limit <n>]`,
2218
+ );
1351
2219
  }
1352
- if (file !== undefined && (offset !== undefined || limit !== undefined)) {
1353
- // One page as asked, the section a search or an outline named; the result says where the
1354
- // file continues, and asks for nothing.
1355
- const page = await reader.skillFile(file, { offset, limit });
1356
- const section = page.read === null ? undefined : joinFile([page], summary, limit);
1357
- answer(io, session, { ...page, read: section === undefined ? null : bodyOfFile(section) }, () =>
1358
- formatSkillFile(page, section),
2220
+ checkedNumber(text(values, "offset"), "offset", Number.MAX_SAFE_INTEGER);
2221
+ checkedNumber(text(values, "limit"), "limit", READ_FILE_MAX_LIMIT);
2222
+ const listing = await reader.skills();
2223
+ const pack = consolePack(reader, listing, { url: session.url });
2224
+ if (pack === undefined) {
2225
+ throw refusedRead(
2226
+ io,
2227
+ session,
2228
+ owner,
2229
+ listing,
2230
+ formatSkills(listing, undefined, io.skillsDir, owner, toolWords),
1359
2231
  );
1360
- return EXIT.ok;
1361
2232
  }
1362
2233
  if (file !== undefined) {
1363
- // The file whole, page after page, as the console reads it from the pack.
1364
- const pages: RestSkillFile[] = [];
1365
- let offset: number | undefined;
1366
- let last: RestSkillFile | undefined;
1367
- for (let n = 0; n < MAX_SKILL_PAGES; n += 1) {
1368
- last = await reader.skillFile(file, offset === undefined ? {} : { offset });
1369
- if (last.read === null) {
1370
- break;
1371
- }
1372
- pages.push(last);
1373
- if (last.read.kind !== "file" || last.read.nextOffset === null) {
1374
- break;
1375
- }
1376
- offset = last.read.nextOffset;
1377
- }
1378
- if (last === undefined) {
1379
- throw failed("The file could not be read.");
1380
- }
1381
- const fileRead = last;
1382
- const whole = joinFile(pages, summary);
1383
- answer(io, session, { ...fileRead, read: whole === undefined ? null : bodyOfFile(whole) }, () =>
1384
- formatSkillFile(fileRead, whole),
2234
+ // A page of the file, as the skillcdn command reads one: from --offset, as long as a host
2235
+ // shows whole where --limit says nothing, and where the next begins when the file goes on.
2236
+ const page = await readThrough(
2237
+ io,
2238
+ session,
2239
+ owner,
2240
+ pack,
2241
+ { read: "file", path: file, offset: text(values, "offset"), limit: text(values, "limit") },
2242
+ { words: toolWords },
1385
2243
  );
2244
+ say(jsonOfRead(session, pack, page), () => page.text);
1386
2245
  return EXIT.ok;
1387
2246
  }
1388
- const wanted = skillPathIn(
1389
- theOne(
1390
- positionals,
1391
- `Say which skill: ${command} <path of its SKILL.md>, or ${command} --file <path> for a file of the pack`,
1392
- ),
1393
- listing.address,
2247
+ const given = theOne(
2248
+ positionals,
2249
+ `Say which skill: ${command} <path of its SKILL.md>, or ${command} --file <path> for a file of the pack`,
1394
2250
  );
2251
+ const wanted = skillPathIn(given, listing.address);
1395
2252
  if ("error" in wanted) {
1396
2253
  throw misuse(wanted.error);
1397
2254
  }
1398
- // The skill whole: its pages until complete, the rules first, as load_skill lays them out.
1399
- const pages: RestSkillLoad[] = [];
1400
- let cursor: string | undefined;
1401
- let last: RestSkillLoad | undefined;
1402
- for (let n = 0; n < MAX_SKILL_PAGES; n += 1) {
1403
- last = await reader.skill(wanted.path, cursor);
1404
- if (last.read?.status !== "ready") {
1405
- break;
1406
- }
1407
- pages.push(last);
1408
- cursor = last.read.skill.nextCursor ?? undefined;
1409
- if (last.read.skill.complete === true || cursor === undefined) {
1410
- break;
1411
- }
1412
- }
1413
- if (last === undefined) {
1414
- throw failed("The skill could not be read.");
1415
- }
1416
- const loaded = last;
1417
- const whole = joinSkill(pages, summary);
1418
- answer(io, session, { ...loaded, read: whole === undefined ? null : bodyOfSkill(whole) }, () =>
1419
- formatSkillLoad(loaded, whole),
2255
+ // The skill, its rules first, as load_skill lays them out: whole, or the part that begins at
2256
+ // the cursor, ending with the command that reads the next, asked as this one was.
2257
+ let continues = false;
2258
+ const loaded = await readThrough(
2259
+ io,
2260
+ session,
2261
+ owner,
2262
+ pack,
2263
+ { read: "skill", path: wanted.path, cursor },
2264
+ {
2265
+ words: toolWords,
2266
+ // Spelled so that bash and PowerShell run it as it is; where a word has no such spelling,
2267
+ // the command that was run is run again, with the cursor, and the line says why.
2268
+ nextPart: (next) => {
2269
+ continues = true;
2270
+ return (
2271
+ commandLine(command, [given, "--cursor", next, ...again]) ??
2272
+ `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}`
2273
+ );
2274
+ },
2275
+ },
2276
+ );
2277
+ // A part that is not the last ends with the console's own words after the library's line: a
2278
+ // fresh agent read one part of four, saw that the skill continued, and planned from that part,
2279
+ // since "before using it" did not read as now to a session that meant only to plan.
2280
+ say(jsonOfRead(session, pack, loaded), () =>
2281
+ continues ? `${loaded.text}\n${PART_ENDS_HERE}` : loaded.text,
1420
2282
  );
1421
2283
  return EXIT.ok;
1422
2284
  }
1423
2285
 
2286
+ /**
2287
+ * What a part of a skill ends with where another follows: that the instructions stop here,
2288
+ * what the rest holds, and that the command above is run now.
2289
+ */
2290
+ const PART_ENDS_HERE =
2291
+ "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.";
2292
+
1424
2293
  const skill: Command = async (args, io) => {
1425
2294
  const { values, positionals } = parse(args, SKILL_OPTIONS);
1426
2295
  const session = await open(io, values);
1427
- const project = await session.project();
1428
- return readSkill(io, session, project, values, positionals, "console skill");
2296
+ const { reader, owner } = await packNamed(session);
2297
+ return readingPack(owner, () =>
2298
+ readSkill(io, session, reader, values, positionals, "console skill", owner, whereGiven(values)),
2299
+ );
1429
2300
  };
1430
2301
 
1431
2302
  // ---- The plugins (docs/specs/plugins.md, "The command") ----
@@ -1501,7 +2372,7 @@ function splitWords(
1501
2372
  }
1502
2373
 
1503
2374
  const PLUGIN_USAGE =
1504
- "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.";
2375
+ "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.";
1505
2376
 
1506
2377
  const plugin: Command = async (args, io) => {
1507
2378
  const { values, words } = splitWords(args, PLUGIN_GLOBAL_FLAGS);
@@ -1537,6 +2408,8 @@ const plugin: Command = async (args, io) => {
1537
2408
  }
1538
2409
  case "records":
1539
2410
  return pluginRecords(io, session, client, rest, text(values, "project"));
2411
+ case "events":
2412
+ return pluginEvents(io, session, client, rest);
1540
2413
  case "skills": {
1541
2414
  const parsed = parse(rest, SKILLS_OPTIONS);
1542
2415
  return readSkills(io, session, client, parsed.values, parsed.positionals, {
@@ -1552,6 +2425,8 @@ const plugin: Command = async (args, io) => {
1552
2425
  parsed.values,
1553
2426
  parsed.positionals,
1554
2427
  `console plugin ${key} skill`,
2428
+ "project",
2429
+ whereGiven(values),
1555
2430
  );
1556
2431
  }
1557
2432
  case "enable":
@@ -1704,6 +2579,53 @@ function whereValueOf(word: string): unknown {
1704
2579
  }
1705
2580
 
1706
2581
  /** The records of a collection one may read, a page of them; or one record, or its versions. */
2582
+ /**
2583
+ * A plugin's events, newest first (ADR-0128): what it did and what went wrong in it, as far as
2584
+ * the caller may read it, which the console decides (every event for an administrator; for
2585
+ * anyone else those of the projects they may see, their own commands and the console's word of
2586
+ * the plugin); the failures alone with `--kind plugin.failed`, whether or not it has a board
2587
+ * project. A console before 0.5.1 takes no kind and answers every one: the page is narrowed
2588
+ * here, and that is said, since a page narrowed after it was read may hold fewer than were
2589
+ * asked for.
2590
+ */
2591
+ async function pluginEvents(
2592
+ io: CliIo,
2593
+ session: Session,
2594
+ client: PluginClient,
2595
+ rest: readonly string[],
2596
+ ): Promise<number> {
2597
+ const usage = `console plugin ${client.key} events [--kind <kind>] [--limit <n>] [--offset <n>]`;
2598
+ const { values, positionals } = parse(rest, { kind: { type: "string" }, ...PAGE_OPTIONS });
2599
+ if (positionals.length > 0) {
2600
+ throw misuse(`Events take no word but their flags: ${usage}`);
2601
+ }
2602
+ const kind = text(values, "kind");
2603
+ if (kind !== undefined && !/^[a-z_]{1,40}\.[a-z_]{1,40}$/.test(kind)) {
2604
+ throw misuse(
2605
+ `Not a kind of event: ${kind}. A kind is two words with a dot between, as plugin.failed or plugin.command: ${usage}`,
2606
+ );
2607
+ }
2608
+ const limit = countOf(text(values, "limit"), "limit", { least: 1, most: EVENTS_PAGE_LIMIT });
2609
+ const offset = countOf(text(values, "offset"), "offset", { least: 0, most: 1_000_000 });
2610
+ const asked = { kind, limit: limit ?? DEFAULT_PAGE_LIMIT, offset: offset ?? 0 };
2611
+ const read = await client.events(asked);
2612
+ const items = kind === undefined ? read.items : read.items.filter((one) => one.kind === kind);
2613
+ const narrowedHere = items.length !== read.items.length;
2614
+ const page = { items, more: read.more };
2615
+ answer(
2616
+ io,
2617
+ session,
2618
+ page,
2619
+ () =>
2620
+ `${formatPluginEvents(client.key, page, asked)}${
2621
+ narrowedHere
2622
+ ? `\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.`
2623
+ : ""
2624
+ }`,
2625
+ );
2626
+ return EXIT.ok;
2627
+ }
2628
+
1707
2629
  async function pluginRecords(
1708
2630
  io: CliIo,
1709
2631
  session: Session,
@@ -2021,31 +2943,38 @@ async function pluginSecret(
2021
2943
  client: PluginClient,
2022
2944
  rest: readonly string[],
2023
2945
  ): Promise<number> {
2024
- const { values, positionals } = parse(rest, { remove: { type: "boolean" } });
2946
+ const { values, positionals } = parse(rest, {
2947
+ remove: { type: "boolean" },
2948
+ key: { type: "string" },
2949
+ });
2025
2950
  const name = theOne(
2026
2951
  positionals,
2027
- `Say which secret: console plugin ${client.key} secret <name> [--remove]; the value is typed at the prompt, unseen, or piped in.`,
2952
+ `Say which secret: console plugin ${client.key} secret <name> [--key <key>] [--remove]; the value is typed at the prompt, unseen, or piped in.`,
2028
2953
  );
2954
+ // A secret kept per key (ADR-0111) is set and removed one key at a time.
2955
+ const key = text(values, "key");
2956
+ const which = key === undefined ? `the secret ${name}` : `the secret ${name} under ${key}`;
2957
+ const data = key === undefined ? { name } : { name, key };
2029
2958
  if (on(values, "remove")) {
2030
- await client.removeSecret(name);
2031
- answer(io, session, { name, set: false }, () => `Removed the secret ${name} of ${client.key}.`);
2959
+ await client.removeSecret(name, key);
2960
+ answer(io, session, { ...data, set: false }, () => `Removed ${which} of ${client.key}.`);
2032
2961
  return EXIT.ok;
2033
2962
  }
2034
2963
  const value = await secretGiven(
2035
2964
  io,
2036
- `Secret ${name} of ${client.key} (typed unseen; Enter ends it): `,
2965
+ `Secret ${name}${key === undefined ? "" : ` under ${key}`} of ${client.key} (typed unseen; Enter ends it): `,
2037
2966
  );
2038
2967
  if (value.length === 0) {
2039
2968
  throw misuse(
2040
- `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.`,
2969
+ `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.`,
2041
2970
  );
2042
2971
  }
2043
- await client.setSecret(name, value);
2972
+ await client.setSecret(name, value, key);
2044
2973
  answer(
2045
2974
  io,
2046
2975
  session,
2047
- { name, set: true },
2048
- () => `Set the secret ${name} of ${client.key}: sealed, and shown by nothing from now on.`,
2976
+ { ...data, set: true },
2977
+ () => `Set ${which} of ${client.key}: sealed, and shown by nothing from now on.`,
2049
2978
  );
2050
2979
  return EXIT.ok;
2051
2980
  }
@@ -2117,8 +3046,9 @@ function versionOf(given: string | undefined): number | undefined {
2117
3046
  return version;
2118
3047
  }
2119
3048
 
2120
- // The rules of the board (ADR-0023): read before a task is taken, written by an owner for the
2121
- // project and by an administrator for the workspace, through the same page the console keeps.
3049
+ // The rules of the board (ADR-0023, ADR-0120): the console's, which always hold, with what the
3050
+ // organization and the project add to them; read before a task is taken, and added to by an
3051
+ // owner for the project and by an administrator for the organization, on the page each keeps.
2122
3052
  const rules: Command = async (args, io) => {
2123
3053
  const [verb, ...rest] = args;
2124
3054
  if (verb === "write") {
@@ -2136,7 +3066,7 @@ const rules: Command = async (args, io) => {
2136
3066
  const body = none ? undefined : await bodyOf(io, values, given);
2137
3067
  if (!none && body === undefined) {
2138
3068
  throw misuse(
2139
- "Say what the rules are to say: --body <markdown>, --file <path>, - to read standard input, or none to put the written rules away.",
3069
+ "Say what is added to the rules: --body <markdown>, --file <path>, - to read standard input, or none to put what was added away.",
2140
3070
  );
2141
3071
  }
2142
3072
  const baseVersion = versionOf(text(values, "base"));
@@ -2148,18 +3078,28 @@ const rules: Command = async (args, io) => {
2148
3078
  io,
2149
3079
  session,
2150
3080
  put,
2151
- () => "The organization's rules are put away: the console's own hold.",
3081
+ () => "What this organization adds to the rules is put away: the console's stand alone.",
2152
3082
  );
2153
3083
  return EXIT.ok;
2154
3084
  }
3085
+ // A console of before 0.5.1 keeps what is written here as the organization's whole rules,
3086
+ // in the place of its own (ADR-0120): what is added would be all that holds there. Its
3087
+ // answer tells, since it says the workspace's rules whole and no parts, and it is asked
3088
+ // before anything is written.
3089
+ const held = await session.client.rules();
3090
+ if (held.own === undefined) {
3091
+ throw failed(
3092
+ "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.",
3093
+ );
3094
+ }
2155
3095
  const written = await session.client.writeRules({
2156
3096
  body: body ?? "",
2157
3097
  ...(baseVersion === undefined ? {} : { baseVersion }),
2158
3098
  });
2159
3099
  answer(io, session, written, () =>
2160
3100
  written.page === null
2161
- ? "Nothing written: these are the console's own rules as they stand, and they hold already."
2162
- : `Wrote the workspace's rules, version ${written.page.version}.`,
3101
+ ? "Nothing written: that adds nothing to the console's rules, which hold as they stand."
3102
+ : `Wrote what this organization adds to the rules, version ${written.page.version}.`,
2163
3103
  );
2164
3104
  return EXIT.ok;
2165
3105
  }
@@ -2167,12 +3107,22 @@ const rules: Command = async (args, io) => {
2167
3107
  if (none) {
2168
3108
  try {
2169
3109
  const put = await project.archiveDocument(RULES_PATH);
2170
- answer(io, session, put, () => "This project's rules are put away: it adds none now.");
3110
+ answer(
3111
+ io,
3112
+ session,
3113
+ put,
3114
+ () => "What this project adds to the rules is put away: it adds nothing now.",
3115
+ );
2171
3116
  } catch (error) {
2172
3117
  if (!(error instanceof ApiError) || error.code !== "document.not_found") {
2173
3118
  throw error;
2174
3119
  }
2175
- answer(io, session, null, () => "This project has no rules of its own to put away.");
3120
+ answer(
3121
+ io,
3122
+ session,
3123
+ null,
3124
+ () => "This project adds nothing to the rules: nothing to put away.",
3125
+ );
2176
3126
  }
2177
3127
  return EXIT.ok;
2178
3128
  }
@@ -2181,14 +3131,19 @@ const rules: Command = async (args, io) => {
2181
3131
  body: body ?? "",
2182
3132
  ...(baseVersion === undefined ? {} : { baseVersion }),
2183
3133
  });
2184
- answer(io, session, written, () => `Wrote this project's rules, version ${written.version}.`);
3134
+ answer(
3135
+ io,
3136
+ session,
3137
+ written,
3138
+ () => `Wrote what this project adds to the rules, version ${written.version}.`,
3139
+ );
2185
3140
  return EXIT.ok;
2186
3141
  }
2187
3142
  const { values } = parse(args, {}, false);
2188
3143
  const session = await open(io, values);
2189
3144
  const key = await session.projectKey();
2190
3145
  const [found, me] = await Promise.all([
2191
- key === undefined ? session.client.rules() : session.client.project(key).rules(),
3146
+ key === undefined ? session.client.rules() : (await session.project()).rules(),
2192
3147
  session.client.me(),
2193
3148
  ]);
2194
3149
  const read =
@@ -2199,19 +3154,27 @@ const rules: Command = async (args, io) => {
2199
3154
  ...(found.plugins === undefined ? {} : { plugins: found.plugins }),
2200
3155
  }
2201
3156
  : forPerson(found, readingLanguage(me));
2202
- answer(io, session, read, () => formatRules(read, readingLanguage(me)));
3157
+ // The mark of what is printed goes with --json too, for a program that takes a task next.
3158
+ answer(io, session, { ...read, mark: rulesMark(read, readingLanguage(me)) }, () =>
3159
+ formatRules(read, readingLanguage(me)),
3160
+ );
2203
3161
  return EXIT.ok;
2204
3162
  };
2205
3163
 
2206
3164
  /**
2207
3165
  * The rules as they read for the person whose token the command holds: `{language}` filled
2208
- * with the language they read in, or with the task's while they have none.
3166
+ * with the language they read in, or with the task's while they have none; in the whole and,
3167
+ * where the console says them apart (ADR-0120), in the console's own and in what is added.
2209
3168
  */
2210
- function forPerson<T extends { readonly body: string | null }>(
2211
- half: T,
2212
- language: string | null,
2213
- ): T {
2214
- return half.body === null ? half : { ...half, body: fillRules(half.body, language) };
3169
+ function forPerson(half: RestRules, language: string | null): RestRules {
3170
+ return {
3171
+ ...half,
3172
+ ...(half.body === null ? {} : { body: fillRules(half.body, language) }),
3173
+ ...(half.own === undefined ? {} : { own: fillRules(half.own, language) }),
3174
+ ...(half.added == null
3175
+ ? {}
3176
+ : { added: { ...half.added, body: fillRules(half.added.body, language) } }),
3177
+ };
2215
3178
  }
2216
3179
 
2217
3180
  /** The flags that set a task's fields, shared by writing one and changing one. */
@@ -2292,8 +3255,28 @@ const newTask: Command = async (args, io) => {
2292
3255
  ...TASK_FIELDS,
2293
3256
  body: { type: "string" },
2294
3257
  file: { type: "string" },
3258
+ take: { type: "boolean" },
3259
+ agent: { type: "string" },
3260
+ rules: { type: "string" },
2295
3261
  });
2296
3262
  const title = theOne(positionals, 'Say the title: console task new "<title>"');
3263
+ // Written and taken in one command (--take): work given in chat is both at once, and a
3264
+ // session that sends its commands together cannot read the number between two of them,
3265
+ // on a board where another agent may have written a task in the meantime.
3266
+ const taken = on(values, "take");
3267
+ if (!taken && (text(values, "rules") !== undefined || text(values, "agent") !== undefined)) {
3268
+ throw misuse(
3269
+ '--rules and --agent go with --take, which takes the task as it is written: console task new "<title>" --take [--rules <mark>] [--agent <name>]',
3270
+ );
3271
+ }
3272
+ // Refused before anything is written: a task that is done or dropped is not taken, and
3273
+ // written first it would stand on the board as the half of a command that failed.
3274
+ const said = stateOf(text(values, "state"));
3275
+ if (taken && (said === "done" || said === "dropped")) {
3276
+ throw misuse(
3277
+ `A task written as ${said} is not taken. Leave --state out, for ready; or leave --take out.`,
3278
+ );
3279
+ }
2297
3280
  const body = await bodyOf(io, values, text(values, "body"));
2298
3281
  const session = await open(io, values);
2299
3282
  const project = await session.project();
@@ -2301,14 +3284,46 @@ const newTask: Command = async (args, io) => {
2301
3284
  const made = await project.createTask({
2302
3285
  title,
2303
3286
  ...(body === undefined ? {} : { body }),
3287
+ // An idea is not taken: what is written to be taken is ready, where no state is said.
3288
+ ...(taken && said === undefined ? { state: "ready" as const } : {}),
2304
3289
  ...fields,
2305
3290
  });
2306
- answer(
2307
- io,
2308
- session,
2309
- made,
2310
- () => `Task #${made.number} written: ${made.title}\ntask id: ${made.id}`,
2311
- );
3291
+ const written = `Task #${made.number} written: ${made.title}\ntask id: ${made.id}`;
3292
+ if (!taken) {
3293
+ // With the address of its page, for a person told of the task; a task taken at once says
3294
+ // it in the task's own lines below, once.
3295
+ const page = await taskPage(session, made.number);
3296
+ answer(io, session, made, () =>
3297
+ page === undefined ? written : `${written}\n${pageLine(page)}`,
3298
+ );
3299
+ return EXIT.ok;
3300
+ }
3301
+ // The number first, before the take is asked for: whatever becomes of the take, the task is
3302
+ // on the board, and the session must know it by its number so as not to write it twice.
3303
+ if (!session.json) {
3304
+ io.stdout(`${written}\n`);
3305
+ }
3306
+ let run: RestRun | undefined;
3307
+ let took: Taking;
3308
+ try {
3309
+ run = await runOn(project, made, values);
3310
+ took = await taking(session, project, made, made.id, run, values);
3311
+ } catch (error) {
3312
+ // Said before the console's own words for what failed, which follow as on any command:
3313
+ // which half stands, by the task's number, so that nothing is written or taken twice.
3314
+ if (session.json) {
3315
+ io.stdout(
3316
+ `${JSON.stringify({ written: made, ...(run === undefined ? {} : { run }) }, null, 2)}\n`,
3317
+ );
3318
+ }
3319
+ io.stderr(
3320
+ run === undefined
3321
+ ? `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`
3322
+ : `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`,
3323
+ );
3324
+ throw error;
3325
+ }
3326
+ answer(io, session, { written: made, ...took.value }, took.words);
2312
3327
  return EXIT.ok;
2313
3328
  };
2314
3329
 
@@ -2339,7 +3354,8 @@ const editTask: Command = async (args, io) => {
2339
3354
  }
2340
3355
  const found = await project.task(ref);
2341
3356
  const changed = await project.updateTask(found.id, patch);
2342
- answer(io, session, changed, () => formatTask(changed));
3357
+ const page = await taskPage(session, changed.number);
3358
+ answer(io, session, changed, () => formatTask(changed, undefined, undefined, undefined, page));
2343
3359
  return EXIT.ok;
2344
3360
  };
2345
3361
 
@@ -2402,14 +3418,17 @@ const task: Command = async (args, io) => {
2402
3418
  const found = await project.task(ref);
2403
3419
  const [decisions, runs, comments] = await Promise.all([
2404
3420
  project.decisions({ task: found.id }),
2405
- project.runs({ task: found.id }),
3421
+ // The runs are a line each, with their reports counted: the brief form, unless --json asks
3422
+ // for the console's own answer.
3423
+ session.json ? project.runs({ task: found.id }) : project.runBriefs({ task: found.id }),
2406
3424
  project.comments(found.id),
2407
3425
  ]);
3426
+ const page = await taskPage(session, found.number);
2408
3427
  answer(
2409
3428
  io,
2410
3429
  session,
2411
3430
  { task: found, decisions: decisions.items, runs: runs.items, comments: comments.items },
2412
- () => formatTask(found, decisions.items, runs.items, comments.items),
3431
+ () => formatTask(found, decisions.items, runs.items, comments.items, page),
2413
3432
  );
2414
3433
  return EXIT.ok;
2415
3434
  };
@@ -2512,17 +3531,40 @@ const file: Command = async (args, io) => {
2512
3531
  return EXIT.ok;
2513
3532
  };
2514
3533
 
2515
- const take: Command = async (args, io) => {
2516
- const { values, positionals } = parse(args, { agent: { type: "string" } });
2517
- const ref = theOne(positionals, "Say which task: console take <number|id>");
2518
- const session = await open(io, values);
2519
- const project = await session.project();
2520
- const found = await project.task(ref);
3534
+ /** What a take answers: the value `--json` prints, and the words otherwise. */
3535
+ interface Taking {
3536
+ value: {
3537
+ run: RestRun;
3538
+ task: RestTask;
3539
+ comments: readonly unknown[];
3540
+ rules: Record<string, unknown>;
3541
+ };
3542
+ words: () => string;
3543
+ }
3544
+
3545
+ /** Begins a run on a task, as the agent `--agent` names where it is said: the take itself. */
3546
+ function runOn(project: ProjectClient, found: RestTask, values: Values): Promise<RestRun> {
2521
3547
  const agent = text(values, "agent");
2522
- const run = await project.startRun({
3548
+ return project.startRun({
2523
3549
  taskId: found.id,
2524
3550
  ...(agent === undefined ? {} : { agent }),
2525
3551
  });
3552
+ }
3553
+
3554
+ /**
3555
+ * What a take answers, once its run began: the task as it stands taken, its comments and the
3556
+ * rules under their mark, or left out by it (`--rules`, ADR-0119). `take` takes a task that
3557
+ * was read by what the person said, `task new --take` the one it has just written; `ref` is
3558
+ * what the task is read again by, now that it is taken.
3559
+ */
3560
+ async function taking(
3561
+ session: Session,
3562
+ project: ProjectClient,
3563
+ found: RestTask,
3564
+ ref: string,
3565
+ run: RestRun,
3566
+ values: Values,
3567
+ ): Promise<Taking> {
2526
3568
  // The rules come with the run, as they read for the person: everything from here acts
2527
3569
  // within them (ADR-0023); the task is read again, as it stands now that it is taken.
2528
3570
  const [ruling, me, taken, comments, openRuns] = await Promise.all([
@@ -2530,7 +3572,7 @@ const take: Command = async (args, io) => {
2530
3572
  session.client.me(),
2531
3573
  project.task(ref),
2532
3574
  project.comments(found.id),
2533
- project.runs({ open: true, mine: true }),
3575
+ project.runBriefs({ open: true, mine: true }),
2534
3576
  ]);
2535
3577
  // Taking a task with a run open on it ends that run (ADR-0020): said when it happened.
2536
3578
  const tookOver =
@@ -2549,21 +3591,51 @@ const take: Command = async (args, io) => {
2549
3591
  project: forPerson(ruling.project, readingLanguage(me)),
2550
3592
  ...(ruling.plugins === undefined ? {} : { plugins: ruling.plugins }),
2551
3593
  };
2552
- answer(io, session, { run, task: taken, comments: comments.items, rules }, () =>
2553
- [
2554
- `Run ${run.id} began on #${found.number} ${found.title}, as "${run.agent}" for ${run.person.login}. The task is in progress and theirs.${tookOver}${elsewhere}`,
2555
- // The ids on a line of their own, each named: a run's and a task's begin alike, and a
2556
- // task has a number for people as well.
2557
- `run id: ${run.id} task id: ${found.id} (task #${found.number})`,
2558
- "",
2559
- formatTask(taken, undefined, undefined, comments.items),
2560
- "",
2561
- formatRules(rules, readingLanguage(me)),
2562
- "",
2563
- 'Say how it goes: console report "<what you found or did>". Hand in what you make: console hand-in <https url | file path>.',
2564
- '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>".',
2565
- ].join("\n"),
2566
- );
3594
+ // A take gives the rules, whole, unless the session says the mark they have (ADR-0119): a
3595
+ // mark is known only from having been shown them, so a session that never was, a fresh one
3596
+ // or a subagent, gets them whatever it does. A mark that is not theirs, since they changed
3597
+ // or it is of another project's, gets them whole again, and is told so first. The line that
3598
+ // answers a mark stands directly after the run's ids, before the task: a take is cut at its
3599
+ // head by a session that holds the rules, and a rule that changed is what such a cut must
3600
+ // not lose. Without a mark nothing is said there, and the rules follow the task as before.
3601
+ const language = readingLanguage(me);
3602
+ const mark = rulesMark(rules, language);
3603
+ const held = text(values, "rules")?.trim().toLowerCase();
3604
+ const answered =
3605
+ held === undefined ? [] : [held === mark ? formatRulesLeftOut(mark) : formatRulesChanged(held)];
3606
+ const ruled = held === mark ? [] : [formatRules(rules, language), ""];
3607
+ const page = await taskPage(session, taken.number);
3608
+ return {
3609
+ value: { run, task: taken, comments: comments.items, rules: { ...rules, mark } },
3610
+ words: () =>
3611
+ [
3612
+ `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}`,
3613
+ // The ids on a line of their own, each named: a run's and a task's begin alike, and a
3614
+ // task has a number for people as well.
3615
+ `run id: ${run.id} task id: ${found.id} (task #${found.number})`,
3616
+ ...answered,
3617
+ "",
3618
+ formatTask(taken, undefined, undefined, comments.items, page),
3619
+ "",
3620
+ ...ruled,
3621
+ 'Say how it goes: console report "<what you found or did>". Hand in what you make: console hand-in <https url | file path>.',
3622
+ '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>".',
3623
+ ].join("\n"),
3624
+ };
3625
+ }
3626
+
3627
+ const take: Command = async (args, io) => {
3628
+ const { values, positionals } = parse(args, {
3629
+ agent: { type: "string" },
3630
+ rules: { type: "string" },
3631
+ });
3632
+ const ref = theOne(positionals, "Say which task: console take <number|id> [--rules <mark>]");
3633
+ const session = await open(io, values);
3634
+ const project = await session.project();
3635
+ const found = await project.task(ref);
3636
+ const run = await runOn(project, found, values);
3637
+ const took = await taking(session, project, found, ref, run, values);
3638
+ answer(io, session, took.value, took.words);
2567
3639
  return EXIT.ok;
2568
3640
  };
2569
3641
 
@@ -2583,7 +3655,7 @@ const report: Command = async (args, io) => {
2583
3655
  }
2584
3656
  const session = await open(io, values);
2585
3657
  const project = await session.project();
2586
- const runId = await currentRun(project, values);
3658
+ const runId = await currentRun(session, project, values);
2587
3659
  const run = await project.report(runId, { body });
2588
3660
  answer(
2589
3661
  io,
@@ -2629,7 +3701,7 @@ const handIn: Command = async (args, io) => {
2629
3701
  const label = text(values, "label");
2630
3702
  const session = await open(io, values);
2631
3703
  const project = await session.project();
2632
- const runId = await currentRun(project, values);
3704
+ const runId = await currentRun(session, project, values);
2633
3705
  // A URL is handed in as a link, and the console says whether it takes it; anything else
2634
3706
  // names a file on this machine.
2635
3707
  if (/^[a-z][a-z0-9+.-]*:\/\//i.test(what)) {
@@ -2700,7 +3772,7 @@ const ask: Command = async (args, io) => {
2700
3772
  const files = await attachmentsOf(io, texts(values, "attach"));
2701
3773
  const session = await open(io, values);
2702
3774
  const project = await session.project();
2703
- const runId = await currentRun(project, values);
3775
+ const runId = await currentRun(session, project, values);
2704
3776
  // Whom the decision is for (ADR-0042, ADR-0057): the person the agent works for, unless --to
2705
3777
  // names others of the project, each once; several, and any of them may answer.
2706
3778
  const deciderIds: string[] = [];
@@ -2726,13 +3798,28 @@ const ask: Command = async (args, io) => {
2726
3798
  );
2727
3799
  const withFiles =
2728
3800
  files.length === 0 ? "" : `, with ${files.length} file${files.length === 1 ? "" : "s"}`;
2729
- // The id is printed before any waiting, so that a wait cut short loses nothing.
3801
+ // The id is printed before any waiting, so that a wait cut short loses nothing; and the
3802
+ // address of its page, which is what a person told of the decision is given to open.
2730
3803
  io.stdout(
2731
3804
  session.json
2732
3805
  ? `${JSON.stringify(raised, null, 2)}\n`
2733
- : `Decision ${raised.id} raised on run ${runId}${withFiles}; the run waits for ${deciderLogins(raised)}.\ndecision id: ${raised.id}\n${formatOptions(raised)}\n`,
3806
+ : `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`,
2734
3807
  );
2735
- return settle(io, session, project, raised, seconds, true);
3808
+ // An agent account is attended by nobody, and the answer wakes it (ADR-0085): it waits at no
3809
+ // terminal unless it asked to, and is told to go on with other work, where an attended
3810
+ // agent is told how to keep waiting. A wait it asked for that runs out ends in the same
3811
+ // words: waiting on is not what it is told to do then either.
3812
+ const wakes =
3813
+ raised.raisedBy.kind === "agent"
3814
+ ? `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.`
3815
+ : undefined;
3816
+ if (wakes !== undefined && text(values, "wait") === undefined) {
3817
+ if (!session.json) {
3818
+ io.stdout(`${wakes}\n`);
3819
+ }
3820
+ return EXIT.waiting;
3821
+ }
3822
+ return settle(io, session, project, raised, seconds, true, wakes);
2736
3823
  };
2737
3824
 
2738
3825
  /**
@@ -2764,7 +3851,8 @@ const answering: Command = async (args, io) => {
2764
3851
  ...(own === undefined ? { option } : { own }),
2765
3852
  ...(note === undefined ? {} : { note }),
2766
3853
  });
2767
- answer(io, session, answered, () => formatDecision(answered, { atItsAddress }));
3854
+ const page = await decisionPage(session, answered.id, atItsAddress);
3855
+ answer(io, session, answered, () => formatDecision(answered, { atItsAddress, page }));
2768
3856
  return EXIT.ok;
2769
3857
  };
2770
3858
 
@@ -2818,6 +3906,27 @@ async function reachDecision(
2818
3906
  }
2819
3907
  }
2820
3908
 
3909
+ /**
3910
+ * The project a write on a decision goes to: the one the command works in; where none is named,
3911
+ * the decision's own, as the console says it of the decision wherever it is (ADR-0068). A desk
3912
+ * names no project, and the wake that brings an answer names the decision alone: what followed
3913
+ * is written from there as the decision was read from there. With a project named nothing is
3914
+ * looked up, and the console answers for that project as before.
3915
+ */
3916
+ async function projectOfDecision(session: Session, id: string): Promise<ProjectClient> {
3917
+ if ((await session.projectKey()) !== undefined) {
3918
+ return session.project();
3919
+ }
3920
+ try {
3921
+ return session.client.project((await session.client.decision(id)).project.key);
3922
+ } catch (error) {
3923
+ if (error instanceof ApiError && error.status === 404) {
3924
+ throw new ApiError(404, "decision.not_found", "The decision was not found.");
3925
+ }
3926
+ throw error;
3927
+ }
3928
+ }
3929
+
2821
3930
  /** Writes an answer on a decision as the command reaches it (ADR-0068): in the project, else wherever it is. */
2822
3931
  async function answerReached(
2823
3932
  session: Session,
@@ -2851,27 +3960,65 @@ const decision: Command = async (args, io) => {
2851
3960
  wait: { type: "string" },
2852
3961
  outcome: { type: "string" },
2853
3962
  file: { type: "string" },
3963
+ to: { type: "string", multiple: true },
2854
3964
  });
2855
3965
  const id = theOne(
2856
3966
  positionals,
2857
- "Say which decision: console decision <id> [--wait <seconds>] [--outcome <markdown>|--file <path>]",
3967
+ "Say which decision: console decision <id> [--wait <seconds>] [--outcome <markdown>|--file <path>] [--to <login|me>]...",
2858
3968
  );
2859
3969
  const seconds = secondsOf(text(values, "wait"), 0);
3970
+ const tos = texts(values, "to");
3971
+ if (tos.includes("none")) {
3972
+ throw misuse("Say whom the decision is for: --to <login|me>, given again for several.");
3973
+ }
3974
+ if (tos.length > MAX_DECIDERS) {
3975
+ throw misuse(`Name up to ${MAX_DECIDERS} people with --to.`);
3976
+ }
2860
3977
  const outcome = await bodyOf(io, values, text(values, "outcome"));
3978
+ if (tos.length > 0 && outcome !== undefined) {
3979
+ throw misuse("Say one thing at a time: whom the decision is for (--to), or what followed it.");
3980
+ }
2861
3981
  const session = await open(io, values);
3982
+ if (tos.length > 0) {
3983
+ // Whom a decision that waits is for, said anew (ADR-0096): the people named take the place
3984
+ // of those it was for, each once in the order named.
3985
+ const project = await projectOfDecision(session, id);
3986
+ const deciderIds: string[] = [];
3987
+ for (const to of tos) {
3988
+ const named = await personIdOf(session, to);
3989
+ if (typeof named === "string" && !deciderIds.includes(named)) {
3990
+ deciderIds.push(named);
3991
+ }
3992
+ }
3993
+ const addressed = await project.addressDecision(id, deciderIds);
3994
+ const page = await decisionPage(session, addressed.id);
3995
+ answer(io, session, addressed, () => formatDecision(addressed, { page }));
3996
+ return EXIT.ok;
3997
+ }
2862
3998
  if (outcome !== undefined) {
2863
3999
  // What followed the decision: the record grows, and is printed as it stands.
2864
- const project = await session.project();
4000
+ const project = await projectOfDecision(session, id);
2865
4001
  const grown = await project.updateDecision(id, { outcome });
2866
- answer(io, session, grown, () => formatDecision(grown));
4002
+ const page = await decisionPage(session, grown.id);
4003
+ answer(io, session, grown, () => formatDecision(grown, { page }));
2867
4004
  return EXIT.ok;
2868
4005
  }
2869
4006
  const { decision: found, waiter, atItsAddress } = await reachDecision(session, id);
2870
4007
  if (seconds === 0) {
2871
- answer(io, session, found, () => formatDecision(found, { atItsAddress }));
4008
+ const page = await decisionPage(session, found.id, atItsAddress);
4009
+ answer(io, session, found, () => formatDecision(found, { atItsAddress, page }));
2872
4010
  return EXIT.ok;
2873
4011
  }
2874
- return settle(io, session, waiter, found, seconds);
4012
+ // An agent account is attended by nobody, and the answer to a decision it raised wakes it
4013
+ // (ADR-0085): a wait of its own that runs out ends in the account's words, as ask's does, and
4014
+ // not in how an attended agent waits on. Whether the command is the account is what the
4015
+ // login kept says (`login --self`), since the decision alone does not: a person's agent may
4016
+ // wait for a decision an account raised, and is told how to keep waiting.
4017
+ const wakes =
4018
+ signedInAsItself(session) && found.raisedBy.login === session.account
4019
+ ? `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.`
4020
+ : undefined;
4021
+ return settle(io, session, waiter, found, seconds, false, wakes);
2875
4022
  };
2876
4023
 
2877
4024
  const docs: Command = async (args, io) => {
@@ -2885,8 +4032,10 @@ const docs: Command = async (args, io) => {
2885
4032
  const search = text(values, "search");
2886
4033
  const session = await open(io, values);
2887
4034
  const project = await session.project();
4035
+ // A folder is taken as the listing prints it, `guides/`, and as it is named, `guides`.
4036
+ const folder = positionals[0]?.replace(/\/+$/, "");
2888
4037
  const found = await project.documents({
2889
- ...(positionals[0] === undefined ? {} : { folder: positionals[0] }),
4038
+ ...(folder === undefined || folder === "" ? {} : { folder }),
2890
4039
  ...(search === undefined ? {} : { q: search }),
2891
4040
  ...(on(values, "archived") ? { archived: true } : {}),
2892
4041
  });
@@ -2965,12 +4114,15 @@ const write: Command = async (args, io) => {
2965
4114
  body,
2966
4115
  ...(baseVersion === undefined ? {} : { baseVersion }),
2967
4116
  });
4117
+ // The page's address, as a task's and a decision's: what an agent tells a person and hands in.
4118
+ const key = await session.projectKey();
4119
+ const page = key === undefined ? undefined : `${session.url}${docHref(key, written.path)}`;
2968
4120
  answer(
2969
4121
  io,
2970
4122
  session,
2971
4123
  written,
2972
4124
  () =>
2973
- `Wrote ${written.path} (${written.title}), version ${written.version}${written.links.length === 0 ? "" : `; refers to ${written.links.map((link) => link.path).join(", ")}`}`,
4125
+ `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)}`}`,
2974
4126
  );
2975
4127
  return EXIT.ok;
2976
4128
  };
@@ -3148,7 +4300,9 @@ const goal: Command = async (args, io) => {
3148
4300
  const session = await open(io, values);
3149
4301
  const project = await session.project();
3150
4302
  const found = await project.goal(id);
3151
- const towards = await project.tasks({ goal: found.id });
4303
+ const towards = session.json
4304
+ ? await project.tasks({ goal: found.id })
4305
+ : await project.taskBriefs({ goal: found.id });
3152
4306
  answer(io, session, { goal: found, tasks: towards.items }, () =>
3153
4307
  formatGoal(found, towards.items),
3154
4308
  );
@@ -3196,6 +4350,37 @@ const decisions: Command = async (args, io) => {
3196
4350
  return EXIT.ok;
3197
4351
  };
3198
4352
 
4353
+ /**
4354
+ * Says how a run ended, and where that left its task (ADR-0114). The console places the task,
4355
+ * and where is not the command's to know: a finished run leaves it at work where another run is
4356
+ * open on it, and a run that failed or was given up does that too, and on a console of before
4357
+ * 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
4358
+ * `--json` the answer is the run as the console gave it, and nothing more is asked.
4359
+ */
4360
+ async function sayEnded(
4361
+ io: CliIo,
4362
+ session: Session,
4363
+ project: ProjectClient,
4364
+ run: RestRun,
4365
+ status: "finished" | "failed" | "abandoned",
4366
+ ): Promise<void> {
4367
+ let words = "";
4368
+ if (!session.json) {
4369
+ try {
4370
+ const task = await project.task(run.taskId);
4371
+ words = `Run ${run.id} ${status}; task #${task.number} is ${task.state} now.`;
4372
+ } catch (error) {
4373
+ // Said before the console's own words for what failed, which follow as on any command:
4374
+ // the run is over whatever became of the reading, and is not to be ended again.
4375
+ io.stderr(
4376
+ `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`,
4377
+ );
4378
+ throw error;
4379
+ }
4380
+ }
4381
+ answer(io, session, run, () => words);
4382
+ }
4383
+
3199
4384
  const ending =
3200
4385
  (status: "finished" | "failed"): Command =>
3201
4386
  async (args, io) => {
@@ -3207,106 +4392,1397 @@ const ending =
3207
4392
  const summary = await bodyOf(io, values, text(values, "summary"));
3208
4393
  const session = await open(io, values);
3209
4394
  const project = await session.project();
3210
- const runId = await currentRun(project, values);
4395
+ const runId = await currentRun(session, project, values);
3211
4396
  const run = await project.endRun(runId, {
3212
4397
  status,
3213
4398
  ...(summary === undefined ? {} : { summary }),
3214
4399
  });
3215
- answer(io, session, run, () =>
3216
- status === "finished"
3217
- ? `Run ${run.id} finished; the task is up for review.`
3218
- : `Run ${run.id} failed; the task stays as it is.`,
4400
+ await sayEnded(io, session, project, run, status);
4401
+ return EXIT.ok;
4402
+ };
4403
+
4404
+ const abandon: Command = async (args, io) => {
4405
+ const { values, positionals } = parse(args, {
4406
+ summary: { type: "string" },
4407
+ file: { type: "string" },
4408
+ run: { type: "string" },
4409
+ });
4410
+ if (positionals.length > 1) {
4411
+ throw misuse("Say which run: console abandon [<run id>]");
4412
+ }
4413
+ const summary = await bodyOf(io, values, text(values, "summary"));
4414
+ const session = await open(io, values);
4415
+ const project = await session.project();
4416
+ const runId = positionals[0] ?? (await currentRun(session, project, values));
4417
+ const run = await project.endRun(runId, {
4418
+ status: "abandoned",
4419
+ ...(summary === undefined ? {} : { summary }),
4420
+ });
4421
+ await sayEnded(io, session, project, run, "abandoned");
4422
+ return EXIT.ok;
4423
+ };
4424
+
4425
+ const runs: Command = async (args, io) => {
4426
+ const { values } = parse(
4427
+ args,
4428
+ {
4429
+ task: { type: "string" },
4430
+ open: { type: "boolean" },
4431
+ mine: { type: "boolean" },
4432
+ ...PAGE_OPTIONS,
4433
+ },
4434
+ false,
4435
+ );
4436
+ const page = pageOf(values);
4437
+ const session = await open(io, values);
4438
+ const project = await session.project();
4439
+ const ref = text(values, "task");
4440
+ const taskId = ref === undefined ? undefined : (await project.task(ref)).id;
4441
+ const mine = on(values, "mine");
4442
+ const filter = {
4443
+ ...(taskId === undefined ? {} : { task: taskId }),
4444
+ ...(on(values, "open") ? { open: true } : {}),
4445
+ ...(mine ? { mine: true } : {}),
4446
+ ...page,
4447
+ };
4448
+ const [found, agent] = await Promise.all([
4449
+ // A line a run, its reports counted: the brief form, unless --json asks for the console's own.
4450
+ session.json ? project.runs(filter) : project.runBriefs(filter),
4451
+ // With a token, --mine is the runs begun with that token, one agent's, and a person may
4452
+ // have more: an empty listing would read as if they had none, so whose these are is said.
4453
+ mine && !session.json ? tokenNameOf(session) : undefined,
4454
+ ]);
4455
+ const others =
4456
+ "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.";
4457
+ answer(io, session, found, () => {
4458
+ if (found.items.length === 0) {
4459
+ return agent === undefined
4460
+ ? "No runs."
4461
+ : `No runs begun through this agent (${agent}). ${others}`;
4462
+ }
4463
+ const listed =
4464
+ found.items.map(formatRunLine).join("\n") + formatMore(found.more, page.limit, page.offset);
4465
+ return agent === undefined
4466
+ ? listed
4467
+ : `${listed}\nThese are the runs begun through this agent (${agent}). ${others}`;
4468
+ });
4469
+ return EXIT.ok;
4470
+ };
4471
+
4472
+ /** What the token the command acts with is called, or nothing where it acts on a session or cannot be asked. */
4473
+ async function tokenNameOf(session: Session): Promise<string | undefined> {
4474
+ try {
4475
+ return (await session.client.me()).agent ?? undefined;
4476
+ } catch (error) {
4477
+ if (error instanceof ApiError) {
4478
+ return undefined;
4479
+ }
4480
+ throw error;
4481
+ }
4482
+ }
4483
+
4484
+ const run: Command = async (args, io) => {
4485
+ const { values, positionals } = parse(args, {});
4486
+ const id = theOne(positionals, "Say which run: console run <id>");
4487
+ const session = await open(io, values);
4488
+ const project = await session.project();
4489
+ const found = await project.run(id);
4490
+ answer(io, session, found, () => formatRun(found, (artifactId) => project.fileUrl(artifactId)));
4491
+ return EXIT.ok;
4492
+ };
4493
+
4494
+ /** A port for `serve`: the default, or what was said; 0 for one the system picks. */
4495
+ function portOf(value: string | undefined): number {
4496
+ if (value === undefined) {
4497
+ return DEFAULT_SERVE_PORT;
4498
+ }
4499
+ const port = Number(value);
4500
+ if (!Number.isInteger(port) || port < 0 || port > 65535) {
4501
+ throw misuse(`Not a port: ${value}`);
4502
+ }
4503
+ return port;
4504
+ }
4505
+
4506
+ /**
4507
+ * A console of the person's own, served from this machine (ADR-0014): the build's pages here,
4508
+ * and everything under /api/ carried to the console with the token, which the pages never see;
4509
+ * and, with --records, what a desk keeps under /records/ (ADR-0117), for the desk's pages.
4510
+ */
4511
+ const serve: Command = async (args, io) => {
4512
+ const { values, positionals } = parse(args, {
4513
+ port: { type: "string" },
4514
+ records: { type: "string" },
4515
+ });
4516
+ if (positionals.length > 1) {
4517
+ throw misuse("Say at most one directory: console serve [<dir>] [--port <n>] [--records <dir>]");
4518
+ }
4519
+ const [dir] = positionals;
4520
+ const port = portOf(text(values, "port"));
4521
+ const listen = io.listen;
4522
+ if (listen === undefined) {
4523
+ throw failed("Serving is not possible here.");
4524
+ }
4525
+ const session = await open(io, values);
4526
+ const me = await session.client.me();
4527
+ const person = me.person;
4528
+ if (person === null) {
4529
+ throw failed("The console does not know this token. Sign in again: console login");
4530
+ }
4531
+ let web: WebRoot | undefined;
4532
+ if (dir !== undefined) {
4533
+ try {
4534
+ web = await loadWebRoot(dir);
4535
+ } catch (error) {
4536
+ if (error instanceof WebRootError) {
4537
+ throw failed(
4538
+ `Not a build to serve: ${error.message}. Build your console first, and name the directory that holds its index.html: console serve <dir>`,
4539
+ );
4540
+ }
4541
+ throw error;
4542
+ }
4543
+ }
4544
+ const kept = text(values, "records");
4545
+ let records: RecordsRoot | undefined;
4546
+ if (kept !== undefined) {
4547
+ try {
4548
+ records = await loadRecordsRoot(kept);
4549
+ } catch (error) {
4550
+ if (error instanceof RecordsRootError) {
4551
+ throw failed(
4552
+ `No records to serve: ${error.message}. Name the records/ of a desk: console serve <dir> --records <desk>/records`,
4553
+ );
4554
+ }
4555
+ throw error;
4556
+ }
4557
+ }
4558
+ const listening = await listen(
4559
+ (bound) =>
4560
+ createServeHandler({
4561
+ upstream: session.url,
4562
+ token: session.token,
4563
+ fetch: io.fetch,
4564
+ port: bound,
4565
+ web,
4566
+ records,
4567
+ }),
4568
+ port,
4569
+ );
4570
+ // A desk has its records/ once it keeps something (ADR-0122): until then the line says that
4571
+ // nothing is kept there, and that what comes to be is served with no restart.
4572
+ const served =
4573
+ kept === undefined || records === undefined
4574
+ ? ""
4575
+ : (await records.there())
4576
+ ? ` The records in ${kept} are at ${listening.url}records/, read as they are when they are asked for.`
4577
+ : ` Nothing is kept in ${kept} yet: what comes to be kept there is at ${listening.url}records/ from then on, with no restart.`;
4578
+ io.stdout(
4579
+ web === undefined
4580
+ ? `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`
4581
+ : `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`,
4582
+ );
4583
+ await listening.closed;
4584
+ return EXIT.ok;
4585
+ };
4586
+
4587
+ /** What the runner keeps between its own restarts, as its file says it; nothing for a file that does not read. */
4588
+ function runnerStateOf(text: string | undefined): RunnerState | undefined {
4589
+ if (text === undefined) {
4590
+ return undefined;
4591
+ }
4592
+ let json: unknown;
4593
+ try {
4594
+ json = JSON.parse(text);
4595
+ } catch {
4596
+ return undefined;
4597
+ }
4598
+ if (typeof json !== "object" || json === null) {
4599
+ return undefined;
4600
+ }
4601
+ const delivered = "delivered" in json ? json.delivered : undefined;
4602
+ const conversation = "conversation" in json ? json.conversation : undefined;
4603
+ const driver = "driver" in json ? json.driver : undefined;
4604
+ if (typeof delivered !== "number" || !Number.isSafeInteger(delivered) || delivered < 0) {
4605
+ return undefined;
4606
+ }
4607
+ return {
4608
+ delivered,
4609
+ conversation:
4610
+ typeof conversation === "string" && conversation.length > 0 && conversation.length <= 200
4611
+ ? conversation
4612
+ : undefined,
4613
+ // The driver the conversation was begun under, as a registry spells one.
4614
+ driver:
4615
+ typeof driver === "string" && /^[a-z][a-z0-9-]{0,39}$/.test(driver) ? driver : undefined,
4616
+ };
4617
+ }
4618
+
4619
+ /** A line a runner says of its machine, within what the console takes one in. */
4620
+ const machineLine = (text: string): string => {
4621
+ const line = [...text]
4622
+ .map((character) => {
4623
+ const code = character.codePointAt(0) ?? 0;
4624
+ return code < 0x20 || code === 0x7f ? " " : character;
4625
+ })
4626
+ .join("")
4627
+ .trim()
4628
+ .slice(0, MAX_RUNNER_LINE_LENGTH);
4629
+ return line.length === 0 ? "unknown" : line;
4630
+ };
4631
+
4632
+ // The runner of an agent account (ADR-0085, docs/specs/runner.md): started in the account's
4633
+ // desk, on the command signed in as the account itself. It keeps the agent's session going,
4634
+ // feeds it what the console sends and reports what it does, until it is stopped.
4635
+ const runner: Command = async (args, io) => {
4636
+ const { values, positionals } = parse(args, {});
4637
+ if (positionals.length > 0) {
4638
+ throw misuse("console runner takes nothing: it is started in the agent's desk.");
4639
+ }
4640
+ const host = io.runner;
4641
+ if (host === undefined) {
4642
+ throw failed("A runner cannot be started here.");
4643
+ }
4644
+ const session = await open(io, values);
4645
+ const me = await session.client.me();
4646
+ if (me.person === null) {
4647
+ throw failed("The console does not know this sign-in. Sign in again: console login --self");
4648
+ }
4649
+ if (me.person.kind !== "agent" || me.session?.kind !== "command") {
4650
+ throw failed(
4651
+ "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.",
4652
+ );
4653
+ }
4654
+ const written = await host.readText("runner.json");
4655
+ const read =
4656
+ written === undefined
4657
+ ? { ok: true as const, config: DEFAULT_RUNNER_CONFIG }
4658
+ : parseRunnerConfig(written);
4659
+ if (!read.ok) {
4660
+ throw failed(
4661
+ `${read.problem}. Nothing of it is used: put it right, or remove it to run with the defaults.`,
4662
+ );
4663
+ }
4664
+ const modules = ownRunnerModules({ user: host.user });
4665
+ const driverOf = modules.drivers.get(read.config.driver);
4666
+ if (driverOf === undefined) {
4667
+ throw failed(
4668
+ `runner.json names the driver ${read.config.driver}, which this command does not have. It has: ${modules.drivers.names().join(", ")}.`,
4669
+ );
4670
+ }
4671
+ const unknown = read.config.wake.find((name) => modules.wakeSources.get(name) === undefined);
4672
+ if (unknown !== undefined) {
4673
+ throw failed(
4674
+ `runner.json names the wake source ${unknown}, which this command does not have. It has: ${modules.wakeSources.names().join(", ")}.`,
4675
+ );
4676
+ }
4677
+ // A header says the hour and the minute in the workspace's zone, or the machine's where it has none.
4678
+ const zone = me.workspace.timeZone ?? undefined;
4679
+ let clock: Intl.DateTimeFormat;
4680
+ try {
4681
+ clock = new Intl.DateTimeFormat("en-GB", {
4682
+ hour: "2-digit",
4683
+ minute: "2-digit",
4684
+ hourCycle: "h23",
4685
+ ...(zone === undefined ? {} : { timeZone: zone }),
4686
+ });
4687
+ } catch {
4688
+ clock = new Intl.DateTimeFormat("en-GB", {
4689
+ hour: "2-digit",
4690
+ minute: "2-digit",
4691
+ hourCycle: "h23",
4692
+ });
4693
+ }
4694
+ const statePath = workPath("runner-state.json");
4695
+ const running = createRunner({
4696
+ client: session.client,
4697
+ driver: driverOf({
4698
+ spawn: host.spawn,
4699
+ cwd: host.cwd,
4700
+ command: read.config.product?.command,
4701
+ args: read.config.product?.args,
4702
+ version: io.version,
4703
+ }),
4704
+ config: read.config,
4705
+ cwd: host.cwd,
4706
+ machine: {
4707
+ name: machineLine(io.hostname ?? ""),
4708
+ os: machineLine(host.os),
4709
+ user: machineLine(modules.boundaries.get("os-user")?.user() ?? host.user),
4710
+ },
4711
+ version: io.version ?? "0.0.0",
4712
+ // A runner whose own version is not known has nothing to hold the package's against.
4713
+ installed: io.version === undefined ? undefined : io.installedVersion,
4714
+ // What installs the console's version here, the way this command was installed.
4715
+ updateCommand: () => updateWords(io, io.consoleVersion?.()),
4716
+ now: io.now,
4717
+ random: host.random,
4718
+ time: (iso) => clock.format(new Date(iso)),
4719
+ files: {
4720
+ write: (path, text) => host.writePrivate(workPath(path), text),
4721
+ remove: (path) => host.remove(workPath(path)),
4722
+ },
4723
+ state: {
4724
+ load: async () => runnerStateOf(await host.readText(statePath)),
4725
+ save: (state) => host.writePrivate(statePath, `${JSON.stringify(state)}\n`),
4726
+ },
4727
+ log: (line) => io.stdout(`${new Date(io.now()).toISOString()} ${line}\n`),
4728
+ // The autosave's git: in the desk, asking nobody at a terminal, its words read and let go.
4729
+ // A step that reaches the git host is handed the account's token for it, as the clone of
4730
+ // the desk was: answered from the environment of that one command, and only to the host
4731
+ // the workspace keeps its desks at.
4732
+ git: async (args, handed) => {
4733
+ const origin = gitOriginOf(deskRemoteOf(me.workspace, me.person?.handle ?? ""));
4734
+ const child = host.spawn("git", args, {
4735
+ cwd: host.cwd,
4736
+ env:
4737
+ handed?.token === undefined || origin === undefined
4738
+ ? { GIT_TERMINAL_PROMPT: "0" }
4739
+ : gitTokenEnv(handed.token, origin),
4740
+ });
4741
+ child.end();
4742
+ for await (const _ of child.lines) {
4743
+ // Nothing of what git prints is kept.
4744
+ }
4745
+ return (await child.exited).code;
4746
+ },
4747
+ // The wake sources the desk names beside the console's own stream, which the runner listens to itself.
4748
+ wakes: {
4749
+ sources: read.config.wake.flatMap((name) => {
4750
+ const source = modules.wakeSources.get(name);
4751
+ return source === undefined || source.run === undefined ? [] : [source];
4752
+ }),
4753
+ fetch: (url, init) => io.fetch(url, { ...init, headers: { ...init.headers } }),
4754
+ socket: (url) => host.socket(url),
4755
+ },
4756
+ });
4757
+ io.stdout(
4758
+ `The runner of @${me.person.handle ?? me.person.login} at ${me.workspace.name} (${session.url}) starts in ${host.cwd}. Stop with Ctrl+C.\n`,
4759
+ );
4760
+ void host.untilStopped().then(() => running.stop());
4761
+ if ((await running.run()) === "updated") {
4762
+ // The service that keeps a runner starts it again whenever it ends; one started by hand is
4763
+ // started again by hand.
4764
+ io.stdout(
4765
+ "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",
4766
+ );
4767
+ }
4768
+ return EXIT.ok;
4769
+ };
4770
+
4771
+ // Configuring, as the person (ADR-0021): what an administrator or an owner does on the pages,
4772
+ // their agent does here, attributed to them as the agent. The console decides on every request
4773
+ // with the same roles; what the person may not, the agent may not (auth.forbidden). The tokens
4774
+ // themselves have no command, by design.
4775
+
4776
+ const people: Command = async (args, io) => {
4777
+ const { values } = parse(args, {}, false);
4778
+ const session = await open(io, values);
4779
+ const found = await session.client.people();
4780
+ const loginOf = new Map(found.items.map((person) => [person.id, calledOf(person)]));
4781
+ answer(io, session, found, () =>
4782
+ [
4783
+ ...found.items.map((person) =>
4784
+ formatPersonLine(
4785
+ person,
4786
+ person.managerId === null || person.managerId === undefined
4787
+ ? undefined
4788
+ : (loginOf.get(person.managerId) ?? person.managerId),
4789
+ ),
4790
+ ),
4791
+ ...found.listed.map(formatListingLine),
4792
+ ].join("\n"),
4793
+ );
4794
+ return EXIT.ok;
4795
+ };
4796
+
4797
+ // Whom whoever asks reports to (ADR-0084), for a person as for an agent account: whom to turn to
4798
+ // first where one does not know whom to ask, and the administrators where there is nobody.
4799
+ const manager: Command = async (args, io) => {
4800
+ const { values } = parse(args, {}, false);
4801
+ const session = await open(io, values);
4802
+ const found = await session.client.manager();
4803
+ answer(io, session, found, () => {
4804
+ const lines: string[] = [];
4805
+ if (found.manager === null) {
4806
+ lines.push("You report to nobody.");
4807
+ } else {
4808
+ lines.push(`You report to: ${formatPersonLine(found.manager)}`);
4809
+ }
4810
+ // The administrators stand in where there is no manager, or the manager is out.
4811
+ if (found.manager === null || found.manager.status !== "active") {
4812
+ lines.push(
4813
+ found.administrators.length === 0
4814
+ ? "No administrator is in."
4815
+ : "The administrators, who stand in:",
4816
+ ...found.administrators.map((person) => ` ${formatPersonLine(person)}`),
4817
+ );
4818
+ }
4819
+ return lines.join("\n");
4820
+ });
4821
+ return EXIT.ok;
4822
+ };
4823
+
4824
+ /** A handle as the command takes one: with the `@` people call it by, or without. */
4825
+ const handleOf = (word: string): string => (word.startsWith("@") ? word.slice(1) : word);
4826
+
4827
+ /** The agent accounts of the workspace (ADR-0084), by handle. */
4828
+ const agents: Command = async (args, io) => {
4829
+ const { values } = parse(args, {}, false);
4830
+ const session = await open(io, values);
4831
+ const found = await session.client.agents();
4832
+ answer(io, session, found, () =>
4833
+ found.items.length === 0
4834
+ ? "No agent accounts that you see. An administrator makes one on the Agents page."
4835
+ : found.items.map(formatAgentLine).join("\n"),
4836
+ );
4837
+ return EXIT.ok;
4838
+ };
4839
+
4840
+ const AGENT_USAGE =
4841
+ 'Say what to do: console agent <handle> [--avatar <file>] | console agent new <handle> [--login <login>] [--project <key>] [--name "<name>"] [--title "<title>"] [--manager <login|me>] [--host gh|google] [--seed <seed>] [--convert]';
4842
+
4843
+ // An administrator makes an agent account with flags, where the pages make one from a form
4844
+ // (ADR-0084): the member's row at once, its login let in. What is left out is proposed: the
4845
+ // name is the handle's, capitalized, and the console rolls the avatar from the seed, or from one
4846
+ // of its own.
4847
+ const agentNew = async (args: readonly string[], io: CliIo): Promise<number> => {
4848
+ const { values, positionals } = parse(args, {
4849
+ login: { type: "string" },
4850
+ name: { type: "string" },
4851
+ title: { type: "string" },
4852
+ manager: { type: "string" },
4853
+ host: { type: "string" },
4854
+ seed: { type: "string" },
4855
+ convert: { type: "boolean" },
4856
+ });
4857
+ const handle = handleOf(theOne(positionals, AGENT_USAGE));
4858
+ const session = await open(io, values);
4859
+ // The account it signs in with: said, or what the workspace's identity service makes of the
4860
+ // two handles and the domain (ADR-0089).
4861
+ // A console that does not say its workspace's services names no login: one is asked for.
4862
+ const asked =
4863
+ text(values, "login") === undefined
4864
+ ? await session.client.me().catch(() => undefined)
4865
+ : undefined;
4866
+ const derived = asked === undefined ? undefined : agentLoginOf(asked.workspace, handle);
4867
+ const login = text(values, "login") ?? derived?.login;
4868
+ if (login === undefined) {
4869
+ throw misuse(
4870
+ `Say the account it will sign in with: console agent new ${handle} --login <login> --project <key>`,
4871
+ );
4872
+ }
4873
+ const chosen = text(values, "host");
4874
+ const host = chosen === undefined ? (derived?.host ?? hostOfLogin(login)) : providerOf(chosen);
4875
+ const project = await session.projectKey();
4876
+ if (project === undefined) {
4877
+ throw misuse(
4878
+ `Say the project it starts in: console agent new ${handle} --login ${login} --project <key>`,
4879
+ );
4880
+ }
4881
+ const manager = text(values, "manager");
4882
+ const seed = text(values, "seed");
4883
+ const title = text(values, "title");
4884
+ const made = await session.client.createAgent({
4885
+ host,
4886
+ login,
4887
+ handle,
4888
+ name: text(values, "name") ?? `${handle.slice(0, 1).toUpperCase()}${handle.slice(1)}`,
4889
+ ...(title === undefined ? {} : { title }),
4890
+ ...(seed === undefined ? {} : { avatarSeed: seed }),
4891
+ ...(manager === undefined || manager === "me"
4892
+ ? {}
4893
+ : { managerId: (await personOf(session, manager)).id }),
4894
+ project,
4895
+ // A member who carries the login becomes the account only where that is said (ADR-0104).
4896
+ ...(on(values, "convert") ? { convert: true } : {}),
4897
+ });
4898
+ answer(io, session, made, () =>
4899
+ [
4900
+ formatAgentLine(made),
4901
+ made.person.invited === true
4902
+ ? host === "gh"
4903
+ ? // A login at a git host goes to whoever registers it: what the first sign-in is held
4904
+ // to is said (ADR-0126), and by a console older than the answer, the login alone.
4905
+ made.firstSignIn === "account"
4906
+ ? `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.`
4907
+ : made.firstSignIn === "member"
4908
+ ? `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.`
4909
+ : `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.`
4910
+ : `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.`
4911
+ : `${made.person.login} is an agent account from now on, with everything it did.`,
4912
+ ...(made.onboarding === null || made.onboarding === undefined
4913
+ ? []
4914
+ : [
4915
+ `Its first task is #${made.onboarding.number} in ${made.onboarding.project}, with what setting it up takes; its runner is woken with it when it first starts.`,
4916
+ ]),
4917
+ `Next, a machine: console agent invite ${handle} makes the invitation that leads one to it.`,
4918
+ ].join("\n"),
4919
+ );
4920
+ return EXIT.ok;
4921
+ };
4922
+
4923
+ /** A day a secret's value ends on, as the flag gives one: a calendar day, or `none`. */
4924
+ function expiryOf(io: CliIo, values: Values): string | null | undefined {
4925
+ return dayOf(io, text(values, "expires"), true);
4926
+ }
4927
+
4928
+ /**
4929
+ * The value of a secret being set: typed unseen at the terminal, or all of standard input where
4930
+ * that is a pipe, or a file's whole text with --file; never an argument, which a shell would
4931
+ * keep and a process list show.
4932
+ */
4933
+ async function secretValue(io: CliIo, values: Values, prompt: string): Promise<string> {
4934
+ const file = text(values, "file");
4935
+ const value =
4936
+ file === undefined
4937
+ ? await secretGiven(io, prompt)
4938
+ : (await io.readFile(file)).replace(/\r?\n$/, "");
4939
+ if (value.length === 0) {
4940
+ throw failed("No value was given.");
4941
+ }
4942
+ return value;
4943
+ }
4944
+
4945
+ const SECRET_FLAGS: OptionSpec = {
4946
+ set: { type: "boolean" },
4947
+ remove: { type: "boolean" },
4948
+ file: { type: "string" },
4949
+ expires: { type: "string" },
4950
+ };
4951
+
4952
+ // An agent account's own secret store (ADR-0087): the names it keeps, for the account itself,
4953
+ // signed in as itself.
4954
+ const secrets: Command = async (args, io) => {
4955
+ const { values } = parse(args, {}, false);
4956
+ const session = await open(io, values);
4957
+ const found = await session.client.secrets();
4958
+ answer(io, session, found, () =>
4959
+ found.items.length === 0
4960
+ ? "No secret is kept yet: console secret <name> --set keeps one."
4961
+ : found.items.map((item) => formatSecretLine(item)).join("\n"),
4962
+ );
4963
+ return EXIT.ok;
4964
+ };
4965
+
4966
+ const SECRET_USAGE =
4967
+ "Say which secret: console secret <name> | secret <name> --set [--file <path>] [--expires <day|none>] | secret <name> --remove";
4968
+
4969
+ // One secret of the account's own: its value, read and noted; or set, typed unseen; or removed.
4970
+ const secret: Command = async (args, io) => {
4971
+ const { values, positionals } = parse(args, SECRET_FLAGS);
4972
+ const name = theOne(positionals, SECRET_USAGE);
4973
+ const session = await open(io, values);
4974
+ if (on(values, "remove")) {
4975
+ await session.client.removeSecret(name);
4976
+ answer(io, session, { removed: name }, () => `The secret ${name} is removed.`);
4977
+ return EXIT.ok;
4978
+ }
4979
+ if (on(values, "set")) {
4980
+ const expiresOn = expiryOf(io, values);
4981
+ const value = await secretValue(io, values, `Value of ${name} (typed unseen; Enter ends it): `);
4982
+ const kept = await session.client.setSecret(name, {
4983
+ value,
4984
+ ...(expiresOn === undefined ? {} : { expiresOn }),
4985
+ });
4986
+ answer(io, session, kept, () => `Kept: ${formatSecretLine(kept)}`);
4987
+ return EXIT.ok;
4988
+ }
4989
+ // The value alone, for whatever reads it next; the reading is on the account's record.
4990
+ const found = await session.client.secret(name);
4991
+ io.stdout(session.json ? `${JSON.stringify(found, null, 2)}\n` : `${found.value}\n`);
4992
+ return EXIT.ok;
4993
+ };
4994
+
4995
+ // A supervisor's part of an agent account's store (ADR-0087): the names; a secret seeded,
4996
+ // write-only, which only the account reads back; one removed. Never a value.
4997
+ const agentSecrets = async (args: readonly string[], io: CliIo): Promise<number> => {
4998
+ const { values, positionals } = parse(args, {});
4999
+ const handle = handleOf(theOne(positionals, "Say whose: console agent secrets <handle>"));
5000
+ const session = await open(io, values);
5001
+ let found: Awaited<ReturnType<ConsoleClient["agentSecrets"]>>;
5002
+ try {
5003
+ found = await session.client.agentSecrets(handle);
5004
+ } catch (error) {
5005
+ // An account that asks for its own secrets by the supervisor's command is told which
5006
+ // command is its own, where the console's refusal says only whose this one is.
5007
+ if (error instanceof ApiError && error.code === "auth.forbidden") {
5008
+ const me = await session.client.me().catch(() => undefined);
5009
+ if (me?.person?.kind === "agent" && me.person.handle === handle) {
5010
+ throw failed(
5011
+ `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>.`,
5012
+ );
5013
+ }
5014
+ }
5015
+ throw error;
5016
+ }
5017
+ answer(io, session, found, () =>
5018
+ found.items.length === 0
5019
+ ? `@${handle} keeps no secret yet.`
5020
+ : found.items.map((item) => formatSecretLine(item)).join("\n"),
5021
+ );
5022
+ return EXIT.ok;
5023
+ };
5024
+
5025
+ const agentSecret = async (args: readonly string[], io: CliIo): Promise<number> => {
5026
+ const { values, positionals } = parse(args, SECRET_FLAGS);
5027
+ const [given, name] = theTwo(
5028
+ positionals,
5029
+ "Say whose and which: console agent secret <handle> <name> [--file <path>] [--expires <day|none>] | agent secret <handle> <name> --remove",
5030
+ );
5031
+ const handle = handleOf(given);
5032
+ const session = await open(io, values);
5033
+ if (on(values, "remove")) {
5034
+ await session.client.removeAgentSecret(handle, name);
5035
+ answer(
5036
+ io,
5037
+ session,
5038
+ { handle, removed: name },
5039
+ () => `The secret ${name} of @${handle} is removed.`,
5040
+ );
5041
+ return EXIT.ok;
5042
+ }
5043
+ const expiresOn = expiryOf(io, values);
5044
+ const value = await secretValue(
5045
+ io,
5046
+ values,
5047
+ `Value of ${name} for @${handle} (typed unseen; Enter ends it): `,
5048
+ );
5049
+ const kept = await session.client.seedAgentSecret(handle, name, {
5050
+ value,
5051
+ ...(expiresOn === undefined ? {} : { expiresOn }),
5052
+ });
5053
+ answer(
5054
+ io,
5055
+ session,
5056
+ kept,
5057
+ () => `Seeded for @${handle}, which alone reads it back: ${formatSecretLine(kept)}`,
5058
+ );
5059
+ return EXIT.ok;
5060
+ };
5061
+
5062
+ /** The kinds of signal a supervisor sends with words: which need them, and which take them. */
5063
+ const WORDED_SIGNALS: Readonly<Record<string, { readonly needs: boolean }>> = {
5064
+ tell: { needs: true },
5065
+ // Without words it stops the turn so that what the agent was sent and has not taken is read now.
5066
+ interrupt: { needs: false },
5067
+ stop: { needs: false },
5068
+ restart: { needs: false },
5069
+ reset: { needs: false },
5070
+ wake: { needs: false },
5071
+ };
5072
+
5073
+ // A supervisor's signal to an agent account (ADR-0085): a tell, an interruption, a stop, a start
5074
+ // with the same conversation or with a new one, a wake; in their own name, on the account's
5075
+ // record. What it says is given as words, or with --file, or on standard input as `-`.
5076
+ const agentSignal = async (
5077
+ kind: "tell" | "interrupt" | "stop" | "restart" | "reset" | "wake",
5078
+ args: readonly string[],
5079
+ io: CliIo,
5080
+ ): Promise<number> => {
5081
+ const { values, positionals } = parse(args, { file: { type: "string" } });
5082
+ const [given, words, ...rest] = positionals;
5083
+ const needs = WORDED_SIGNALS[kind]?.needs === true;
5084
+ const usage = `Say whom${needs ? " and what" : ""}: console agent ${kind} <handle> ${needs ? '"<words>"' : '["<words>"]'} [--file <path>]`;
5085
+ if (given === undefined || rest.length > 0) {
5086
+ throw misuse(usage);
5087
+ }
5088
+ const said = ((await bodyOf(io, values, words)) ?? "").trim();
5089
+ if (needs && said.length === 0) {
5090
+ throw misuse(usage);
5091
+ }
5092
+ const handle = handleOf(given);
5093
+ const session = await open(io, values);
5094
+ const sent = await session.client.sendSignal(handle, {
5095
+ kind,
5096
+ ...(said.length === 0 ? {} : { text: said }),
5097
+ });
5098
+ answer(io, session, sent, () => `Sent to @${handle}: ${formatSignalLine(sent)}`);
5099
+ return EXIT.ok;
5100
+ };
5101
+
5102
+ // The model and the level of effort an agent account runs with (ADR-0085): a supervisor's
5103
+ // choice, kept with the account and applied by its runner.
5104
+ const agentSet = async (args: readonly string[], io: CliIo): Promise<number> => {
5105
+ const { values, positionals } = parse(args, {
5106
+ model: { type: "string" },
5107
+ effort: { type: "string" },
5108
+ });
5109
+ const usage =
5110
+ "Say whom and what: console agent set <handle> [--model <name|none>] [--effort <level|none>]";
5111
+ const handle = handleOf(theOne(positionals, usage));
5112
+ const model = orNone(text(values, "model"));
5113
+ const effort = orNone(text(values, "effort"));
5114
+ if (model === undefined && effort === undefined) {
5115
+ throw misuse(usage);
5116
+ }
5117
+ const session = await open(io, values);
5118
+ const sent = await session.client.sendSignal(handle, {
5119
+ kind: "set",
5120
+ set: {
5121
+ ...(model === undefined ? {} : { model }),
5122
+ ...(effort === undefined ? {} : { effort }),
5123
+ },
5124
+ });
5125
+ answer(io, session, sent, () => `Sent to @${handle}: ${formatSignalLine(sent)}`);
5126
+ return EXIT.ok;
5127
+ };
5128
+
5129
+ // The record of what an agent account was told (ADR-0085), the newest first: for its
5130
+ // supervisors, and for the account itself as `console agent signals me`.
5131
+ const agentSignals = async (args: readonly string[], io: CliIo): Promise<number> => {
5132
+ const { values, positionals } = parse(args, {
5133
+ limit: { type: "string" },
5134
+ before: { type: "string" },
5135
+ });
5136
+ const handle = handleOf(
5137
+ theOne(
5138
+ positionals,
5139
+ "Say whose: console agent signals <handle|me> [--limit <n>] [--before <number>]",
5140
+ ),
5141
+ );
5142
+ const limit = text(values, "limit");
5143
+ const before = text(values, "before");
5144
+ if (
5145
+ limit !== undefined &&
5146
+ !(
5147
+ Number.isInteger(Number(limit)) &&
5148
+ Number(limit) >= 1 &&
5149
+ Number(limit) <= MAX_SIGNALS_PAGE_LIMIT
5150
+ )
5151
+ ) {
5152
+ throw misuse(`Not a number of signals, 1 to ${MAX_SIGNALS_PAGE_LIMIT}: ${limit}`);
5153
+ }
5154
+ if (before !== undefined && !(Number.isSafeInteger(Number(before)) && Number(before) >= 1)) {
5155
+ throw misuse(`Not a signal's number: ${before}`);
5156
+ }
5157
+ const session = await open(io, values);
5158
+ const found = await session.client.signals(handle, {
5159
+ ...(limit === undefined ? {} : { limit: Number(limit) }),
5160
+ ...(before === undefined ? {} : { before: Number(before) }),
5161
+ });
5162
+ answer(io, session, found, () =>
5163
+ found.items.length === 0
5164
+ ? "No signal yet."
5165
+ : [
5166
+ ...found.items.map(formatSignalLine),
5167
+ ...(found.more
5168
+ ? [
5169
+ `More before: console agent signals ${handle} --before ${found.items.at(-1)?.number}`,
5170
+ ]
5171
+ : []),
5172
+ ].join("\n"),
5173
+ );
5174
+ return EXIT.ok;
5175
+ };
5176
+
5177
+ // The invitation that leads a machine to an agent account (ADR-0088): made, made again in place
5178
+ // of the one before, or taken away, by a supervisor. Its code is no credential: it says which
5179
+ // account a setup is for and opens the guide, and the account is entered through its own sign-in.
5180
+ const agentInvite = async (args: readonly string[], io: CliIo): Promise<number> => {
5181
+ const { values, positionals } = parse(args, { revoke: { type: "boolean" } });
5182
+ const handle = handleOf(
5183
+ theOne(positionals, "Say whose: console agent invite <handle> [--revoke]"),
5184
+ );
5185
+ const session = await open(io, values);
5186
+ if (on(values, "revoke")) {
5187
+ await session.client.revokeAgentInvitation(handle);
5188
+ answer(
5189
+ io,
5190
+ session,
5191
+ { handle, revoked: true },
5192
+ () => `The invitation of @${handle} is taken away: its code opens nothing now.`,
5193
+ );
5194
+ return EXIT.ok;
5195
+ }
5196
+ const made = await session.client.inviteAgent(handle);
5197
+ answer(io, session, made, () =>
5198
+ [
5199
+ `An invitation for @${handle}, good until ${moment(made.invitation.expiresAt)} or until its command has signed in. The code is shown this once. It is no credential: it says which account a setup is for, and gives nobody the account.`,
5200
+ "On the agent's machine, in its own OS account, say to its product:",
5201
+ ` ${setupSentenceOf(made.command)}`,
5202
+ `or run the command there yourself. A person reads the same guide at ${session.url}/setup/${made.code}`,
5203
+ ].join("\n"),
5204
+ );
5205
+ return EXIT.ok;
5206
+ };
5207
+
5208
+ const SETUP_USAGE =
5209
+ "Say which setup: console agent setup --console <origin> --code <code>, as the invitation's line has it. A supervisor of the account makes one: console agent invite <handle>";
5210
+
5211
+ /** The secret of an agent account's store that its git host is read with. */
5212
+ const DESK_TOKEN = GIT_TOKEN_SECRET;
5213
+ /** How often, and how many times, a setup looks whether the runner it started is heard from. */
5214
+ const RUNNER_HEARD_PAUSE_MS = 2000;
5215
+ const RUNNER_HEARD_TRIES = 15;
5216
+ /** How long a command of the service that is tried again waits between its tries. */
5217
+ const SERVICE_TRY_PAUSE_MS = 1000;
5218
+
5219
+ const SETUP_FLAGS: OptionSpec = {
5220
+ console: { type: "string" },
5221
+ code: { type: "string" },
5222
+ desk: { type: "string" },
5223
+ guide: { type: "boolean" },
5224
+ refresh: { type: "boolean" },
5225
+ "new-desk": { type: "boolean" },
5226
+ "no-service": { type: "boolean" },
5227
+ };
5228
+
5229
+ type Me = Awaited<ReturnType<ConsoleClient["me"]>>;
5230
+
5231
+ /** The end of what a program said, for a refusal to carry: one line, bounded. */
5232
+ function lastWords(ran: Ran): string {
5233
+ const line = ran.err.trim().split(/\r?\n/).at(-1) ?? "";
5234
+ return line.length === 0 ? "it said nothing" : line.slice(0, 300);
5235
+ }
5236
+
5237
+ /**
5238
+ * The origin of a remote that git reaches over the web, `https://host`, which is what a
5239
+ * credential is asked for; nothing for any other address, which takes no token this way.
5240
+ */
5241
+ function gitOriginOf(remote: string | undefined): string | undefined {
5242
+ if (remote === undefined) {
5243
+ return undefined;
5244
+ }
5245
+ try {
5246
+ const url = new URL(remote);
5247
+ return url.protocol === "https:" || url.protocol === "http:"
5248
+ ? `${url.protocol}//${url.host}`
5249
+ : undefined;
5250
+ } catch {
5251
+ return undefined;
5252
+ }
5253
+ }
5254
+
5255
+ /**
5256
+ * What git is handed a token by, for one command: a credential helper named in the environment,
5257
+ * which answers with the token from the environment. The token is on no command line, which a
5258
+ * process list shows, and in no file of the repository. The helper is named for one origin, the
5259
+ * remote's own: a redirect, or a repository inside the one cloned, at another host is answered
5260
+ * nothing of it.
5261
+ */
5262
+ function gitTokenEnv(token: string, origin: string): Record<string, string> {
5263
+ return {
5264
+ GIT_TERMINAL_PROMPT: "0",
5265
+ GIT_CONFIG_COUNT: "2",
5266
+ // An empty helper first: whatever the machine has configured for that origin is left out of this command.
5267
+ GIT_CONFIG_KEY_0: `credential.${origin}.helper`,
5268
+ GIT_CONFIG_VALUE_0: "",
5269
+ GIT_CONFIG_KEY_1: `credential.${origin}.helper`,
5270
+ GIT_CONFIG_VALUE_1:
5271
+ '!f() { test "$1" = get && printf "username=x-access-token\\npassword=%s\\n" "$CONSOLE_DESK_TOKEN"; }; f',
5272
+ CONSOLE_DESK_TOKEN: token,
5273
+ };
5274
+ }
5275
+
5276
+ /**
5277
+ * A word of a line a person runs in a shell, as that shell takes it whole: quoted where it holds
5278
+ * anything a shell reads as more than a word, in single quotes, which neither a POSIX shell nor
5279
+ * PowerShell reads into.
5280
+ */
5281
+ function shellWord(text: string, platform: string): string {
5282
+ const plain = platform === "win32" ? /^[A-Za-z0-9_@%+=:,./\\-]+$/ : /^[A-Za-z0-9_@%+=:,./-]+$/;
5283
+ if (plain.test(text)) {
5284
+ return text;
5285
+ }
5286
+ return platform === "win32"
5287
+ ? `'${text.replaceAll("'", "''")}'`
5288
+ : `'${text.replaceAll("'", "'\\''")}'`;
5289
+ }
5290
+
5291
+ /**
5292
+ * The line that starts the runner by hand, in the desk, for a person or an agent to run. On
5293
+ * Windows its two commands are joined by `;`: the PowerShell every Windows has takes no `&&`,
5294
+ * which came with PowerShell 7, and the words are quoted as PowerShell takes them.
5295
+ */
5296
+ function runnerByHand(desk: string, url: string, login: string, platform: string): string {
5297
+ const then = platform === "win32" ? ";" : " &&";
5298
+ return `cd ${shellWord(desk, platform)}${then} console runner --url ${shellWord(url, platform)} --account ${shellWord(login, platform)}`;
5299
+ }
5300
+
5301
+ /** The desk a setup is for: the place named, else this directory where it is a desk, else `desk` in the OS account's home. */
5302
+ async function deskOf(machine: SetupMachine, values: Values): Promise<string> {
5303
+ const named = text(values, "desk");
5304
+ if (named !== undefined) {
5305
+ return machine.path(named);
5306
+ }
5307
+ const here = machine.path(".");
5308
+ return (await machine.exists(machine.path(here, "runner.json")))
5309
+ ? here
5310
+ : machine.path(machine.home, "desk");
5311
+ }
5312
+
5313
+ /**
5314
+ * The desk on this machine (ADR-0088): left as it is where there is one; cloned from the git
5315
+ * host where the account keeps the token that reads it there, which is an account that pushed a
5316
+ * desk before; written from the template otherwise, and no file that is there is written over.
5317
+ */
5318
+ async function settleDesk(
5319
+ io: CliIo,
5320
+ machine: SetupMachine,
5321
+ client: ConsoleClient,
5322
+ person: NonNullable<Me["person"]>,
5323
+ workspace: Me["workspace"],
5324
+ url: string,
5325
+ values: Values,
5326
+ ): Promise<string> {
5327
+ const desk = await deskOf(machine, values);
5328
+ const handle = person.handle ?? "";
5329
+ if (
5330
+ (await machine.exists(machine.path(desk, "runner.json"))) ||
5331
+ (await machine.exists(machine.path(desk, "AGENTS.md")))
5332
+ ) {
5333
+ io.stdout(`The desk at ${desk} is there already, and is left as it is.\n`);
5334
+ return desk;
5335
+ }
5336
+ const remote = on(values, "new-desk") ? undefined : deskRemoteOf(workspace, handle);
5337
+ if (
5338
+ remote !== undefined &&
5339
+ (await client.secrets()).items.some((secret) => secret.name === DESK_TOKEN)
5340
+ ) {
5341
+ if (await machine.holds(desk)) {
5342
+ throw failed(
5343
+ `${desk} holds something that is no desk, and a desk is cloned into an empty place. Name another with --desk <dir>.`,
5344
+ );
5345
+ }
5346
+ const token = (await client.secret(DESK_TOKEN)).value;
5347
+ const origin = gitOriginOf(remote);
5348
+ const cloned = await machine.run("git", ["clone", "--quiet", remote, desk], {
5349
+ env: origin === undefined ? { GIT_TERMINAL_PROMPT: "0" } : gitTokenEnv(token, origin),
5350
+ });
5351
+ if (cloned.code !== 0) {
5352
+ throw failed(
5353
+ `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.`,
5354
+ );
5355
+ }
5356
+ io.stdout(`The desk is cloned from ${remote} into ${desk}.\n`);
5357
+ return desk;
5358
+ }
5359
+ const written: string[] = [];
5360
+ for (const [path, body] of deskFiles({
5361
+ agent: { name: person.name ?? handle, handle, title: person.title ?? null },
5362
+ console: { url, workspace: workspace.name },
5363
+ services: deskServicesOf(workspace, handle),
5364
+ })) {
5365
+ const file = machine.path(desk, path);
5366
+ if (!(await machine.exists(file))) {
5367
+ await machine.write(file, body, 0o644);
5368
+ written.push(path);
5369
+ }
5370
+ }
5371
+ io.stdout(
5372
+ `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`,
5373
+ );
5374
+ return desk;
5375
+ }
5376
+
5377
+ /**
5378
+ * The service that keeps the runner running (ADR-0085), by the module of this platform: its
5379
+ * files written and, for a first setup, its commands run; answers where the runner's own lines
5380
+ * are once it is loaded. A refresh runs none of them and never unloads a service, since it may
5381
+ * be running under it: what it wrote again is read when the service is next loaded.
5382
+ */
5383
+ async function settleService(
5384
+ io: CliIo,
5385
+ machine: SetupMachine,
5386
+ desk: string,
5387
+ url: string,
5388
+ login: string,
5389
+ how: "load" | "write",
5390
+ ): Promise<string | undefined> {
5391
+ const byHand = runnerByHand(desk, url, login, machine.platform);
5392
+ const modules = ownRunnerModules({ user: machine.user });
5393
+ const service = modules.services
5394
+ .names()
5395
+ .map((name) => modules.services.get(name))
5396
+ .find((one) => one?.platforms.includes(machine.platform) === true);
5397
+ if (service === undefined || machine.self === undefined) {
5398
+ io.stdout(
5399
+ `${service === undefined ? `No service keeps a runner running on ${machine.platform} yet` : "This command does not know how it was started, so it writes no service"}. Start the runner yourself and keep it running: ${byHand}\n`,
5400
+ );
5401
+ return undefined;
5402
+ }
5403
+ const plan = service.plan({
5404
+ desk,
5405
+ home: machine.home,
5406
+ uid: machine.uid,
5407
+ user: machine.user,
5408
+ program: [...machine.self, "runner", "--url", url, "--account", login],
5409
+ path: machine.searchPath,
5410
+ });
5411
+ if ("problem" in plan) {
5412
+ throw failed(
5413
+ `The ${service.name} service is not written: ${plan.problem}. Start the runner yourself and keep it running: ${byHand}`,
5414
+ );
5415
+ }
5416
+ let changed = false;
5417
+ for (const file of plan.files) {
5418
+ if ((await machine.read(file.path)) !== file.text) {
5419
+ await machine.write(file.path, file.text, file.mode);
5420
+ changed = true;
5421
+ }
5422
+ }
5423
+ const where = plan.files.map((file) => file.path).join(", ");
5424
+ const said = (step: ServiceCommand): string => `${step.command} ${step.args.join(" ")}`;
5425
+ // A command of the service's, tried as often as it says, a second apart.
5426
+ const run = async (step: ServiceCommand): Promise<Ran> => {
5427
+ let ran = await machine.run(step.command, step.args, { env: step.env });
5428
+ for (let tried = 1; ran.code !== 0 && tried < (step.tries ?? 1); tried += 1) {
5429
+ await io.sleep(SERVICE_TRY_PAUSE_MS);
5430
+ ran = await machine.run(step.command, step.args, { env: step.env });
5431
+ }
5432
+ return ran;
5433
+ };
5434
+ if (how === "write") {
5435
+ if (!changed) {
5436
+ io.stdout(`The ${service.name} service is as it was (${where}).\n`);
5437
+ return undefined;
5438
+ }
5439
+ // What has the system read the file anew ends nothing that runs: a refresh runs that much.
5440
+ const unread: string[] = [];
5441
+ for (const step of plan.reread ?? []) {
5442
+ if ((await run(step)).code !== 0) {
5443
+ unread.push(said(step));
5444
+ }
5445
+ }
5446
+ io.stdout(
5447
+ `The ${service.name} service is written again (${where}). It is read ${plan.reload}${unread.length === 0 ? "" : ` Run this first, which did not succeed here: ${unread.join("; ")}.`}\n`,
5448
+ );
5449
+ return undefined;
5450
+ }
5451
+ const left: string[] = [];
5452
+ for (const step of plan.commands) {
5453
+ const ran = await run(step);
5454
+ if (ran.code === 0) {
5455
+ continue;
5456
+ }
5457
+ if (step.mayFail !== true) {
5458
+ throw failed(
5459
+ `The ${service.name} service is written (${where}) and was not loaded: ${said(step)} said: ${lastWords(ran)}. ${plan.failing} Or start the runner yourself and keep it running: ${byHand}`,
5460
+ );
5461
+ }
5462
+ if (step.otherwise !== undefined) {
5463
+ left.push(step.otherwise);
5464
+ }
5465
+ }
5466
+ io.stdout(
5467
+ `The ${service.name} service is written (${where}) and loaded: the runner starts with the OS account ${machine.user}, and is started again when it ends. Its own lines are in ${plan.log}.\n${left.map((line) => `${line}\n`).join("")}`,
5468
+ );
5469
+ return plan.log;
5470
+ }
5471
+
5472
+ /**
5473
+ * Signs the command in as the account a setup is for (ADR-0088, point 5), unless it is already:
5474
+ * a connection that asks to be the account itself, opened in the machine's browser and approved
5475
+ * there by the account. A sign-in that turns out to be anybody else's is given up at once:
5476
+ * nobody answers for the account but the account.
5477
+ */
5478
+ async function signInAsAccount(
5479
+ io: CliIo,
5480
+ machine: SetupMachine,
5481
+ url: string,
5482
+ setup: RestAgentSetup,
5483
+ ): Promise<ConsoleClient> {
5484
+ const { handle, login } = setup.account;
5485
+ const isAccount = (me: Me): boolean =>
5486
+ me.person?.kind === "agent" && me.person.handle === handle && me.session?.kind === "command";
5487
+ const credentials = (await loadCredentials(io)) ?? EMPTY_CREDENTIALS;
5488
+ for (const kept of loginsAt(credentials, url)) {
5489
+ if (kept.self !== true) {
5490
+ continue;
5491
+ }
5492
+ const client = clientOf(io, url, kept.token);
5493
+ const me = await client.me().catch(() => undefined);
5494
+ if (me !== undefined && isAccount(me)) {
5495
+ io.stdout(`This command is signed in as @${handle} here already.\n`);
5496
+ return client;
5497
+ }
5498
+ }
5499
+ const anonymous = clientOf(io, url);
5500
+ // What the account's page shows beside the session: the OS account, and the machine.
5501
+ const label = `console as ${machine.user}`;
5502
+ const begun = await anonymous.connect({
5503
+ agent: io.hostname === undefined ? label : `${label} on ${io.hostname}`,
5504
+ as: "self",
5505
+ });
5506
+ // The address is the console's own, or it is not opened: what a console answers is not run.
5507
+ const opened =
5508
+ URL.canParse(begun.url) && new URL(begun.url).origin === url
5509
+ ? await machine.open(begun.url)
5510
+ : false;
5511
+ // The end of the wait is a moment as any other the command prints (ADR-0035), as a login's
5512
+ // is: in the workspace's time zone where a login at this console kept it, as the API gave it
5513
+ // where none has.
5514
+ setMomentZone(credentials.logins.find((kept) => kept.url === url)?.timeZone);
5515
+ io.stdout(
5516
+ `${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`,
5517
+ );
5518
+ let secret: string;
5519
+ for (;;) {
5520
+ await io.sleep(begun.interval * 1000);
5521
+ let claim: RestClaim;
5522
+ try {
5523
+ claim = await anonymous.claimConnection(begun.secret);
5524
+ } catch (error) {
5525
+ if (error instanceof ApiError && error.code === "connect.not_found") {
5526
+ throw failed(
5527
+ "Nobody said in time that this command is the account, or someone said it is not theirs. Nothing was set up. Run the line again for a new code.",
5528
+ );
5529
+ }
5530
+ throw error;
5531
+ }
5532
+ if (claim.status === "signed_in" || claim.status === "connected") {
5533
+ secret = claim.secret;
5534
+ break;
5535
+ }
5536
+ }
5537
+ const client = clientOf(io, url, secret);
5538
+ const me = await client.me();
5539
+ if (!isAccount(me)) {
5540
+ await client.giveUpToken().catch(() => undefined);
5541
+ throw failed(
5542
+ `The page said that this command is ${me.person?.login ?? "nobody"}, who is not @${handle}. That sign-in is given up, and nothing was set up. Sign out of the console in that browser, sign in as ${login}, and run the line again.`,
3219
5543
  );
3220
- return EXIT.ok;
3221
- };
3222
-
3223
- const abandon: Command = async (args, io) => {
3224
- const { values, positionals } = parse(args, {
3225
- summary: { type: "string" },
3226
- file: { type: "string" },
3227
- run: { type: "string" },
3228
- });
3229
- if (positionals.length > 1) {
3230
- throw misuse("Say which run: console abandon [<run id>]");
3231
5544
  }
3232
- const summary = await bodyOf(io, values, text(values, "summary"));
3233
- const session = await open(io, values);
3234
- const project = await session.project();
3235
- const runId = positionals[0] ?? (await currentRun(project, values));
3236
- const run = await project.endRun(runId, {
3237
- status: "abandoned",
3238
- ...(summary === undefined ? {} : { summary }),
3239
- });
3240
- answer(io, session, run, () => `Run ${run.id} abandoned; the task stays as it is.`);
3241
- return EXIT.ok;
3242
- };
5545
+ await keep(io, url, secret, undefined, true, true, () => undefined);
5546
+ io.stdout(
5547
+ `Signed in as @${handle}: what this command does from now on, the account does. The session is kept while it is used.\n`,
5548
+ );
5549
+ return client;
5550
+ }
3243
5551
 
3244
- const runs: Command = async (args, io) => {
3245
- const { values } = parse(
3246
- args,
3247
- {
3248
- task: { type: "string" },
3249
- open: { type: "boolean" },
3250
- mine: { type: "boolean" },
3251
- ...PAGE_OPTIONS,
3252
- },
3253
- false,
5552
+ /** Looks for a little while whether the runner that was started is heard from, and says how it stands. */
5553
+ async function awaitRunner(
5554
+ io: CliIo,
5555
+ client: ConsoleClient,
5556
+ handle: string,
5557
+ heardBefore: string | null,
5558
+ log: string,
5559
+ ): Promise<void> {
5560
+ for (let tries = 0; tries < RUNNER_HEARD_TRIES; tries += 1) {
5561
+ await io.sleep(RUNNER_HEARD_PAUSE_MS);
5562
+ const found = await client.agent(handle).catch(() => undefined);
5563
+ const heard = found?.state?.heardAt ?? null;
5564
+ const said = found?.runner?.machine ?? null;
5565
+ if (heard !== null && heard !== heardBefore && said !== null) {
5566
+ io.stdout(
5567
+ `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`,
5568
+ );
5569
+ return;
5570
+ }
5571
+ }
5572
+ io.stdout(
5573
+ `The runner is not heard from yet. Its own lines are in ${log}; the account's page says when it is.\n`,
3254
5574
  );
3255
- const page = pageOf(values);
5575
+ }
5576
+
5577
+ // Derives a machine again (ADR-0088): by the account's own command, in its desk, when the
5578
+ // services or the account changed. It writes what is missing of the desk and the service where
5579
+ // it changed, and says the services as they are now; what the agent wrote stays the agent's.
5580
+ const agentRefresh = async (values: Values, io: CliIo): Promise<number> => {
5581
+ const machine = io.machine;
5582
+ if (machine === undefined) {
5583
+ throw failed("A machine cannot be set up from here.");
5584
+ }
3256
5585
  const session = await open(io, values);
3257
- const project = await session.project();
3258
- const ref = text(values, "task");
3259
- const taskId = ref === undefined ? undefined : (await project.task(ref)).id;
3260
- const found = await project.runs({
3261
- ...(taskId === undefined ? {} : { task: taskId }),
3262
- ...(on(values, "open") ? { open: true } : {}),
3263
- ...(on(values, "mine") ? { mine: true } : {}),
3264
- ...page,
3265
- });
3266
- answer(io, session, found, () =>
3267
- found.items.length === 0
3268
- ? "No runs."
3269
- : found.items.map(formatRunLine).join("\n") + formatMore(found.more, page.limit, page.offset),
5586
+ const me = await session.client.me();
5587
+ const person = me.person;
5588
+ if (person === null || person.kind !== "agent" || me.session?.kind !== "command") {
5589
+ throw failed(
5590
+ "A machine is refreshed by the agent account's own command, signed in as the account. One is set up from an invitation a supervisor makes: console agent setup --console <origin> --code <code>.",
5591
+ );
5592
+ }
5593
+ const handle = person.handle ?? person.login;
5594
+ const desk = await settleDesk(
5595
+ io,
5596
+ machine,
5597
+ session.client,
5598
+ person,
5599
+ me.workspace,
5600
+ session.url,
5601
+ values,
5602
+ );
5603
+ if (!on(values, "no-service")) {
5604
+ await settleService(io, machine, desk, session.url, person.login, "write");
5605
+ }
5606
+ const services = deskServicesOf(me.workspace, handle);
5607
+ io.stdout(
5608
+ services.length === 0
5609
+ ? `${me.workspace.name} names no service for its agents.\n`
5610
+ : `The services ${me.workspace.name} names now, with what @${handle} is called at each:\n${services
5611
+ .map(
5612
+ (one) =>
5613
+ ` ${one.role}: ${one.name}${one.account === undefined ? "" : `, as ${one.account}`}`,
5614
+ )
5615
+ .join("\n")}\nWhere the desk says otherwise, put its AGENTS.md right: it is yours.\n`,
3270
5616
  );
3271
5617
  return EXIT.ok;
3272
5618
  };
3273
5619
 
3274
- const run: Command = async (args, io) => {
3275
- const { values, positionals } = parse(args, {});
3276
- const id = theOne(positionals, "Say which run: console run <id>");
3277
- const session = await open(io, values);
3278
- const project = await session.project();
3279
- const found = await project.run(id);
3280
- answer(io, session, found, () => formatRun(found, (artifactId) => project.fileUrl(artifactId)));
5620
+ // Sets a machine up for an agent account (ADR-0088), from the line of its invitation: prints the
5621
+ // guide the code opens, which is asked of the console the line names without a sign-in, since
5622
+ // the command is signed in nowhere there yet; then signs the command in as the account, settles
5623
+ // the desk and the service that keeps the runner running, and says how the runner stands.
5624
+ const agentSetup = async (args: readonly string[], io: CliIo): Promise<number> => {
5625
+ const { values } = parse(args, SETUP_FLAGS, false);
5626
+ if (on(values, "refresh")) {
5627
+ return agentRefresh(values, io);
5628
+ }
5629
+ const wanted = text(values, "console") ?? text(values, "url");
5630
+ const given = text(values, "code");
5631
+ if (wanted === undefined || given === undefined) {
5632
+ throw misuse(SETUP_USAGE);
5633
+ }
5634
+ const code = normalizeConnectCode(given);
5635
+ if (code === undefined) {
5636
+ throw misuse(
5637
+ "Not a code. An invitation's code is eight letters and digits, as ABCD-EFGH; copy it from the line you were given.",
5638
+ );
5639
+ }
5640
+ const url = originOf(wanted);
5641
+ let setup: RestAgentSetup;
5642
+ try {
5643
+ setup = await clientOf(io, url).agentSetup(code);
5644
+ } catch (error) {
5645
+ if (error instanceof ApiError && error.code === "setup.not_found") {
5646
+ throw failed(
5647
+ `No setup has that code at ${url}: it was never made, its day has passed, or the account's command has signed in already. A supervisor of the account makes a new one: console agent invite <handle>.`,
5648
+ );
5649
+ }
5650
+ throw error;
5651
+ }
5652
+ const guide = setupGuideOf(setup, code);
5653
+ if (on(values, "json")) {
5654
+ io.stdout(`${JSON.stringify({ setup, guide }, null, 2)}\n`);
5655
+ return EXIT.ok;
5656
+ }
5657
+ io.stdout(`${setupGuideText(guide, moment)}\n`);
5658
+ if (on(values, "guide")) {
5659
+ return EXIT.ok;
5660
+ }
5661
+ const machine = io.machine;
5662
+ if (machine === undefined) {
5663
+ throw failed("A machine cannot be set up from here. The guide above says what a setup takes.");
5664
+ }
5665
+ const { handle } = setup.account;
5666
+ io.stdout(
5667
+ `\nSetting this machine up for @${handle}, in the OS account ${machine.user}${io.hostname === undefined ? "" : ` on ${io.hostname}`}.\n`,
5668
+ );
5669
+ const client = await signInAsAccount(io, machine, url, setup);
5670
+ const me = await client.me();
5671
+ if (me.person === null) {
5672
+ throw failed("The console does not know this sign-in any more. Run the line again.");
5673
+ }
5674
+ const heardBefore = (await client.agent(handle).catch(() => undefined))?.state?.heardAt ?? null;
5675
+ const desk = await settleDesk(io, machine, client, me.person, me.workspace, url, values);
5676
+ if (on(values, "no-service")) {
5677
+ io.stdout(
5678
+ `No service is written, as asked. Start the runner yourself and keep it running: ${runnerByHand(desk, url, me.person.login, machine.platform)}\n`,
5679
+ );
5680
+ return EXIT.ok;
5681
+ }
5682
+ const log = await settleService(io, machine, desk, url, me.person.login, "load");
5683
+ if (log !== undefined) {
5684
+ await awaitRunner(io, client, handle, heardBefore, log);
5685
+ }
3281
5686
  return EXIT.ok;
3282
5687
  };
3283
5688
 
3284
- /** A port for `serve`: the default, or what was said; 0 for one the system picks. */
3285
- function portOf(value: string | undefined): number {
3286
- if (value === undefined) {
3287
- return DEFAULT_SERVE_PORT;
3288
- }
3289
- const port = Number(value);
3290
- if (!Number.isInteger(port) || port < 0 || port > 65535) {
3291
- throw misuse(`Not a port: ${value}`);
3292
- }
3293
- return port;
3294
- }
5689
+ const DESK_USAGE = "Say at most one directory: console desk [<directory>] [--web]";
3295
5690
 
3296
5691
  /**
3297
- * A console of the person's own, served from this machine (ADR-0014): the build's pages here,
3298
- * and everything under /api/ carried to the console with the token, which the pages never see.
5692
+ * What is next in a new desk, in order, as a person says it to their agent there (ADR-0115,
5693
+ * ADR-0122): first the desk is set up as a repository, by the skill for that in the
5694
+ * organization's pack; then the person is asked what they want to keep and to see, and the
5695
+ * desk is shaped to it, by the skill the command ships, named with its place.
3299
5696
  */
3300
- const serve: Command = async (args, io) => {
3301
- const { values, positionals } = parse(args, { port: { type: "string" } });
5697
+ function deskNext(web: boolean, skillsDir: string | undefined): [string, string] {
5698
+ return [
5699
+ `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`,
5700
+ `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")}`}`,
5701
+ ];
5702
+ }
5703
+
5704
+ /** The files of the shell of a desk's pages as they are written: the two words the template leaves filled in. */
5705
+ function deskWebFiles(
5706
+ template: ReadonlyMap<string, string>,
5707
+ version: string,
5708
+ title: string,
5709
+ ): [string, string][] {
5710
+ return [...template]
5711
+ .filter(([path]) => !path.split("/").some((part) => part === ".." || part.length === 0))
5712
+ .map(([path, body]) => [
5713
+ path,
5714
+ body.replaceAll("__VERSION__", version).replaceAll("__TITLE__", title),
5715
+ ]);
5716
+ }
5717
+
5718
+ /** A count with its word, the word in the plural where the count is not one. */
5719
+ const counted = (count: number, one: string, many = `${one}s`): string =>
5720
+ `${count} ${count === 1 ? one : many}`;
5721
+
5722
+ // The check of a desk's records (ADR-0117): every file under `records/` read as the format's
5723
+ // schemas read it, and each problem said with its file. It asks nothing of the console and
5724
+ // needs no sign-in: an agent that wrote a record runs it before it commits, and nobody needs
5725
+ // a page to know that the records are right.
5726
+ const deskCheck = async (args: readonly string[], io: CliIo): Promise<number> => {
5727
+ const { values, positionals } = parse(args, {});
3302
5728
  if (positionals.length > 1) {
3303
- throw misuse("Say at most one directory: console serve [<dir>] [--port <n>]");
5729
+ throw misuse("Say at most one directory: console desk check [<directory>]");
3304
5730
  }
3305
- const [dir] = positionals;
3306
- const port = portOf(text(values, "port"));
3307
- const listen = io.listen;
3308
- if (listen === undefined) {
3309
- throw failed("Serving is not possible here.");
5731
+ const at = io.recordsAt?.(positionals[0] ?? ".");
5732
+ if (at === undefined) {
5733
+ throw failed("A desk's records cannot be read from here.");
5734
+ }
5735
+ const found = await checkRecords(at.files);
5736
+ if (on(values, "json")) {
5737
+ io.stdout(`${JSON.stringify({ directory: at.directory, ...found }, null, 2)}\n`);
5738
+ } else if (!found.found) {
5739
+ io.stdout(
5740
+ `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`,
5741
+ );
5742
+ } else {
5743
+ const kept = found.collections.map(
5744
+ (one) =>
5745
+ ` ${one.key}: ${counted(one.items, "item")}, ${counted(one.uses, "use")}, ${counted(one.metricRows, "row of figures", "rows of figures")}`,
5746
+ );
5747
+ io.stdout(
5748
+ [
5749
+ ...found.problems.map((one) => `${one.file}: ${one.problem}`),
5750
+ ...found.notes.map((one) => `note: ${one.file}: ${one.problem}`),
5751
+ ...(found.problems.length === 0
5752
+ ? [
5753
+ `The records in ${at.directory} read right: ${counted(found.collections.length, "collection")}.`,
5754
+ ]
5755
+ : found.collections.length === 0
5756
+ ? []
5757
+ : ["What reads:"]),
5758
+ ...kept,
5759
+ "",
5760
+ ].join("\n"),
5761
+ );
5762
+ }
5763
+ if (found.problems.length > 0) {
5764
+ throw failed(
5765
+ `${counted(found.problems.length, "problem")} in the records of ${at.directory}. Mend the files and run this again.`,
5766
+ );
5767
+ }
5768
+ return EXIT.ok;
5769
+ };
5770
+
5771
+ // A person's desk (ADR-0115): its files, the least (ADR-0122), each only where no file of that
5772
+ // name is there, in `desk` here, as an agent account's is called, or the directory named; with
5773
+ // --web, the shell of the desk's pages in `web/`, where that holds nothing yet. The command
5774
+ // writes and stops, and its last lines say what is next, in order, for an agent to go on with:
5775
+ // making the desk a repository is a skill's, of the organization's pack, and shaping it to what
5776
+ // the person asks to keep and to see is the skill keeping-a-desk's, which the command ships.
5777
+ // An agent account's desk is setup's: for one, the command writes the shell alone, with --web,
5778
+ // into the desk it names.
5779
+ const desk: Command = async (args, io) => {
5780
+ if (args[0] === "check") {
5781
+ return deskCheck(args.slice(1), io);
5782
+ }
5783
+ const { values, positionals } = parse(args, { web: { type: "boolean" } });
5784
+ if (positionals.length > 1) {
5785
+ throw misuse(DESK_USAGE);
3310
5786
  }
3311
5787
  const session = await open(io, values);
3312
5788
  const me = await session.client.me();
@@ -3314,61 +5790,212 @@ const serve: Command = async (args, io) => {
3314
5790
  if (person === null) {
3315
5791
  throw failed("The console does not know this token. Sign in again: console login");
3316
5792
  }
3317
- let web: WebRoot | undefined;
3318
- if (dir !== undefined) {
3319
- try {
3320
- web = await loadWebRoot(dir);
3321
- } catch (error) {
3322
- if (error instanceof WebRootError) {
3323
- throw failed(
3324
- `Not a build to serve: ${error.message}. Build your console first, and name the directory that holds its index.html: console serve <dir>`,
3325
- );
3326
- }
3327
- throw error;
5793
+ // An agent account's desk is setup's, and none of its own files is written here (ADR-0115).
5794
+ // The shell of its pages is the one thing this command writes for it, into the desk it names
5795
+ // (ADR-0122): a desk's pages are its member's, whichever kind of member that is.
5796
+ const ofAgent = person.kind === "agent";
5797
+ if (ofAgent && !on(values, "web")) {
5798
+ throw failed(
5799
+ `${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.`,
5800
+ );
5801
+ }
5802
+ const machine = io.machine;
5803
+ if (machine === undefined) {
5804
+ throw failed("A desk cannot be written from here.");
5805
+ }
5806
+ const [named] = positionals;
5807
+ // A desk made under a directory that works in a project would work in it too, and every
5808
+ // checkout under its work/ with it: what the folder above says, a desk must not inherit.
5809
+ const above = named === undefined || !isAbsolute(named) ? await io.directory.load() : undefined;
5810
+ if (above !== undefined) {
5811
+ throw failed(
5812
+ `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>.`,
5813
+ );
5814
+ }
5815
+ const dir = machine.path(named ?? DESK_FOLDER);
5816
+ if (ofAgent && !(await machine.exists(machine.path(dir, "AGENTS.md")))) {
5817
+ throw failed(
5818
+ `${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`,
5819
+ );
5820
+ }
5821
+ const input = {
5822
+ person: { name: person.name ?? person.login, login: person.login },
5823
+ console: { url: session.url, workspace: me.workspace.name },
5824
+ // The language to write to them in (A-F6): theirs, else the workspace's, else none is said.
5825
+ language: readingLanguage(me) ?? undefined,
5826
+ };
5827
+ // The shell of the pages is settled before anything is written, so that a command that cannot
5828
+ // write it writes nothing.
5829
+ const webDir = machine.path(dir, "web");
5830
+ const webKept = on(values, "web") && (await machine.holds(webDir));
5831
+ let shell: [string, string][] | undefined;
5832
+ if (on(values, "web") && !webKept) {
5833
+ const template = await io.deskWebTemplate?.();
5834
+ if (template === undefined || template.size === 0) {
5835
+ throw failed(
5836
+ `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."}`,
5837
+ );
5838
+ }
5839
+ if (io.version === undefined) {
5840
+ throw failed(
5841
+ `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."}`,
5842
+ );
5843
+ }
5844
+ shell = deskWebFiles(template, io.version, deskWebTitleOf(input.person));
5845
+ }
5846
+ const written: string[] = [];
5847
+ const kept: string[] = [];
5848
+ for (const [path, body] of ofAgent ? [] : personDeskFiles(input)) {
5849
+ const file = machine.path(dir, path);
5850
+ if (await machine.exists(file)) {
5851
+ kept.push(path);
5852
+ } else {
5853
+ await machine.write(file, body, 0o644);
5854
+ written.push(path);
3328
5855
  }
3329
5856
  }
3330
- const listening = await listen(
3331
- (bound) =>
3332
- createServeHandler({
3333
- upstream: session.url,
3334
- token: session.token,
3335
- fetch: io.fetch,
3336
- port: bound,
3337
- web,
3338
- }),
3339
- port,
3340
- );
3341
- io.stdout(
3342
- web === undefined
3343
- ? `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`
3344
- : `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`,
5857
+ const lines = ofAgent
5858
+ ? []
5859
+ : [
5860
+ written.length === 0
5861
+ ? `The desk at ${dir} is there already, and is left as it is.`
5862
+ : kept.length === 0
5863
+ ? `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.`
5864
+ : `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"}.`,
5865
+ ];
5866
+ const shellNames = (shell ?? []).map(([path]) => path);
5867
+ for (const [path, body] of shell ?? []) {
5868
+ await machine.write(machine.path(webDir, ...path.split("/")), body, 0o644);
5869
+ }
5870
+ if (shell !== undefined) {
5871
+ lines.push(
5872
+ `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" : ""}.`,
5873
+ );
5874
+ } else if (webKept) {
5875
+ lines.push(`${webDir} holds something already, and is left as it is.`);
5876
+ }
5877
+ const web = on(values, "web")
5878
+ ? { directory: webDir, written: shellNames, version: shell === undefined ? null : io.version }
5879
+ : null;
5880
+ // An agent account that asked for the shell is shaping its desk already: nothing is next.
5881
+ // So is a person who asked for the shell in a desk that was there: the two lines printed
5882
+ // again sent a fresh agent back to the repository's setup in the middle of building a page.
5883
+ const shaping = ofAgent || (web !== null && written.length === 0);
5884
+ const next: string[] = shaping ? [] : deskNext(web !== null, io.skillsDir);
5885
+ answer(io, session, { directory: dir, written, kept, web, next }, () =>
5886
+ (next.length === 0
5887
+ ? lines
5888
+ : [
5889
+ ...lines,
5890
+ "Next, in that folder, say these to your agent in order; an agent that ran this command goes on with them there:",
5891
+ "",
5892
+ ...next.map((line, index) => `${index + 1}. ${line}`),
5893
+ ]
5894
+ ).join("\n"),
3345
5895
  );
3346
- await listening.closed;
3347
5896
  return EXIT.ok;
3348
5897
  };
3349
5898
 
3350
- // Configuring, as the person (ADR-0021): what an administrator or an owner does on the pages,
3351
- // their agent does here, attributed to them as the agent. The console decides on every request
3352
- // with the same roles; what the person may not, the agent may not (auth.forbidden). The tokens
3353
- // themselves have no command, by design.
3354
-
3355
- const people: Command = async (args, io) => {
3356
- const { values } = parse(args, {}, false);
5899
+ // One agent account by its handle; with --avatar, its picture written as a file (ADR-0084): the
5900
+ // parts are drawn here, by the package's own function, and the console sends no picture.
5901
+ const agent: Command = async (args, io) => {
5902
+ if (args[0] === "new") {
5903
+ return agentNew(args.slice(1), io);
5904
+ }
5905
+ if (
5906
+ args[0] === "tell" ||
5907
+ args[0] === "interrupt" ||
5908
+ args[0] === "stop" ||
5909
+ args[0] === "restart" ||
5910
+ args[0] === "reset" ||
5911
+ args[0] === "wake"
5912
+ ) {
5913
+ return agentSignal(args[0], args.slice(1), io);
5914
+ }
5915
+ if (args[0] === "set") {
5916
+ return agentSet(args.slice(1), io);
5917
+ }
5918
+ if (args[0] === "signals") {
5919
+ return agentSignals(args.slice(1), io);
5920
+ }
5921
+ if (args[0] === "invite") {
5922
+ return agentInvite(args.slice(1), io);
5923
+ }
5924
+ if (args[0] === "setup") {
5925
+ return agentSetup(args.slice(1), io);
5926
+ }
5927
+ if (args[0] === "secrets") {
5928
+ return agentSecrets(args.slice(1), io);
5929
+ }
5930
+ if (args[0] === "secret") {
5931
+ return agentSecret(args.slice(1), io);
5932
+ }
5933
+ const { values, positionals } = parse(args, {
5934
+ avatar: { type: "string" },
5935
+ account: { type: "string", multiple: true },
5936
+ "day-start": { type: "string" },
5937
+ "day-end": { type: "string" },
5938
+ });
5939
+ const handle = handleOf(theOne(positionals, AGENT_USAGE));
3357
5940
  const session = await open(io, values);
3358
- const found = await session.client.people();
3359
- const loginOf = new Map(found.items.map((person) => [person.id, person.login]));
3360
- answer(io, session, found, () =>
3361
- [
3362
- ...found.items.map((person) =>
3363
- formatPersonLine(
3364
- person,
3365
- person.managerId === null || person.managerId === undefined
3366
- ? undefined
3367
- : (loginOf.get(person.managerId) ?? person.managerId),
3368
- ),
3369
- ),
3370
- ...found.listed.map(formatListingLine),
3371
- ].join("\n"),
5941
+ const held = texts(values, "account");
5942
+ // The hours of its day (ADR-0085): an hour as 09:00, or none for the usual start and no end.
5943
+ const hourOf = (flag: string): string | null | undefined => {
5944
+ const word = text(values, flag);
5945
+ if (word === undefined) {
5946
+ return undefined;
5947
+ }
5948
+ if (word === "none") {
5949
+ return null;
5950
+ }
5951
+ if (!/^(?:[01][0-9]|2[0-3]):[0-5][0-9]$/.test(word)) {
5952
+ throw misuse(`Not an hour: ${word}. Say one as 09:00 or 18:30, or none.`);
5953
+ }
5954
+ return word;
5955
+ };
5956
+ const dayStart = hourOf("day-start");
5957
+ const dayEnd = hourOf("day-end");
5958
+ if (held.length > 0 || dayStart !== undefined || dayEnd !== undefined) {
5959
+ // The accounts it holds elsewhere (ADR-0089), each as <service>=<name>, or =none to take
5960
+ // one away: what it is called there, and never a secret.
5961
+ const accounts: Record<string, string | null> = {};
5962
+ for (const word of held) {
5963
+ const at = word.indexOf("=");
5964
+ const service = at === -1 ? "" : word.slice(0, at).trim();
5965
+ const name = at === -1 ? "" : word.slice(at + 1).trim();
5966
+ if (service.length === 0 || name.length === 0) {
5967
+ throw misuse(
5968
+ `Not an account: ${word}. Say the service and what the agent is called there, as --account github=acme-mira, or --account github=none to take one away.`,
5969
+ );
5970
+ }
5971
+ accounts[service] = name === "none" ? null : name;
5972
+ }
5973
+ const kept = await session.client.updateAgent(handle, {
5974
+ ...(held.length === 0 ? {} : { accounts }),
5975
+ ...(dayStart === undefined ? {} : { dayStart }),
5976
+ ...(dayEnd === undefined ? {} : { dayEnd }),
5977
+ });
5978
+ answer(io, session, kept, () => formatAgent(kept));
5979
+ return EXIT.ok;
5980
+ }
5981
+ const found = await session.client.agent(handle);
5982
+ const file = text(values, "avatar");
5983
+ if (file === undefined) {
5984
+ answer(io, session, found, () => formatAgent(found));
5985
+ return EXIT.ok;
5986
+ }
5987
+ const parts = found.person.avatarParts;
5988
+ if (parts === null || parts === undefined) {
5989
+ throw failed(`The console answered no avatar for @${handle}.`);
5990
+ }
5991
+ const png = pngFile(MAX_AVATAR_PIXELS, deflateSync(avatarScanlines(parts, MAX_AVATAR_PIXELS)));
5992
+ const written = await io.writeBytes(file, png, `${handle}.png`);
5993
+ answer(
5994
+ io,
5995
+ session,
5996
+ { handle, file: written, pixels: MAX_AVATAR_PIXELS, bytes: png.length },
5997
+ () =>
5998
+ `The avatar of @${handle} is written to ${written}: a PNG of ${MAX_AVATAR_PIXELS} pixels a side, for its profile elsewhere.`,
3372
5999
  );
3373
6000
  return EXIT.ok;
3374
6001
  };
@@ -3378,7 +6005,7 @@ const teams: Command = async (args, io) => {
3378
6005
  const { values } = parse(args, {}, false);
3379
6006
  const session = await open(io, values);
3380
6007
  const [found, everyone] = await Promise.all([session.client.teams(), session.client.people()]);
3381
- const loginOf = new Map(everyone.items.map((person) => [person.id, person.login]));
6008
+ const loginOf = new Map(everyone.items.map((person) => [person.id, calledOf(person)]));
3382
6009
  answer(io, session, found, () =>
3383
6010
  found.items.length === 0
3384
6011
  ? "No teams yet. console team new <key> <name> makes one."
@@ -3437,7 +6064,7 @@ const team: Command = async (args, io) => {
3437
6064
  : await session.client.removeTeamMember(key, person.id);
3438
6065
  const everyone = await session.client.people();
3439
6066
  answer(io, session, changed, () =>
3440
- formatTeamLine(changed, new Map(everyone.items.map((one) => [one.id, one.login]))),
6067
+ formatTeamLine(changed, new Map(everyone.items.map((one) => [one.id, calledOf(one)]))),
3441
6068
  );
3442
6069
  return EXIT.ok;
3443
6070
  }
@@ -3447,7 +6074,41 @@ const team: Command = async (args, io) => {
3447
6074
  // The workspace's settings (ADR-0035): read by everyone, changed by an administrator, themselves
3448
6075
  // on the Settings page or through their agent here (ADR-0021).
3449
6076
  const WORKSPACE_FLAGS =
3450
- "--people-visibility <everyone|shared-projects>, --week-start <auto|monday|sunday>, --time-zone <zone|none>, --language <en|ko|none>";
6077
+ "--people-visibility <everyone|shared-projects>, --week-start <auto|monday|sunday>, --time-zone <zone|none>, --language <en|ko|none>, --handle <name|none>, --domain <domain|none>, --service <role>=<kind|none>[,<parameter>=<value>]...";
6078
+
6079
+ /**
6080
+ * A service as `--service` names one (ADR-0089): `git=github,organization=acme`, or `git=none`
6081
+ * to take it away. The role is one of the three; the kind and its parameters are the console's
6082
+ * to judge.
6083
+ */
6084
+ function serviceOf(word: string): {
6085
+ readonly role: ServiceRole;
6086
+ readonly service: Record<string, string> | null;
6087
+ } {
6088
+ const [first = "", ...rest] = word.split(",");
6089
+ const equals = first.indexOf("=");
6090
+ const role = equals === -1 ? "" : first.slice(0, equals).trim();
6091
+ const kind = equals === -1 ? "" : first.slice(equals + 1).trim();
6092
+ if (!SERVICE_ROLES.some((known) => known === role) || kind.length === 0) {
6093
+ throw misuse(
6094
+ `Not a service: ${word}. Say --service <${SERVICE_ROLES.join("|")}>=<kind|none>[,<parameter>=<value>]...`,
6095
+ );
6096
+ }
6097
+ if (kind === "none") {
6098
+ return { role: role as ServiceRole, service: null };
6099
+ }
6100
+ const service: Record<string, string> = { kind };
6101
+ for (const pair of rest) {
6102
+ const at = pair.indexOf("=");
6103
+ const name = at === -1 ? "" : pair.slice(0, at).trim();
6104
+ const value = at === -1 ? "" : pair.slice(at + 1).trim();
6105
+ if (name.length === 0 || value.length === 0 || name === "kind") {
6106
+ throw misuse(`Not a parameter of a service: ${pair}. Say <parameter>=<value>.`);
6107
+ }
6108
+ service[name] = value;
6109
+ }
6110
+ return { role: role as ServiceRole, service };
6111
+ }
3451
6112
  const WORKSPACE_USAGE = `Say what to do: console workspace | console workspace edit [${WORKSPACE_FLAGS.replaceAll(", ", "] [")}] | console workspace pack-token --connect|--stdin|--remove`;
3452
6113
 
3453
6114
  const workspace: Command = async (args, io) => {
@@ -3468,6 +6129,9 @@ const workspace: Command = async (args, io) => {
3468
6129
  "week-start": { type: "string" },
3469
6130
  "time-zone": { type: "string" },
3470
6131
  language: { type: "string" },
6132
+ handle: { type: "string" },
6133
+ domain: { type: "string" },
6134
+ service: { type: "string", multiple: true },
3471
6135
  },
3472
6136
  false,
3473
6137
  );
@@ -3475,11 +6139,18 @@ const workspace: Command = async (args, io) => {
3475
6139
  const weekStart = text(values, "week-start");
3476
6140
  const zone = text(values, "time-zone");
3477
6141
  const language = text(values, "language");
6142
+ const handle = text(values, "handle");
6143
+ const domain = text(values, "domain");
6144
+ const named = values.service;
6145
+ const services = (Array.isArray(named) ? named : []).map((word) => serviceOf(String(word)));
3478
6146
  if (
3479
6147
  visibility === undefined &&
3480
6148
  weekStart === undefined &&
3481
6149
  zone === undefined &&
3482
- language === undefined
6150
+ language === undefined &&
6151
+ handle === undefined &&
6152
+ domain === undefined &&
6153
+ services.length === 0
3483
6154
  ) {
3484
6155
  throw misuse(`Say what to change: ${WORKSPACE_FLAGS}`);
3485
6156
  }
@@ -3498,6 +6169,13 @@ const workspace: Command = async (args, io) => {
3498
6169
  ? null
3499
6170
  : wordOf(language, CONSOLE_LANGUAGES, "a language the console speaks, or none"),
3500
6171
  }),
6172
+ ...(handle === undefined ? {} : { handle: handle === "none" ? null : handleOf(handle) }),
6173
+ ...(domain === undefined ? {} : { domain: domain === "none" ? null : domain.toLowerCase() }),
6174
+ ...(services.length === 0
6175
+ ? {}
6176
+ : {
6177
+ services: Object.fromEntries(services.map((one) => [one.role, one.service])),
6178
+ }),
3501
6179
  });
3502
6180
  await rememberZone(io, session, changed.timeZone ?? undefined);
3503
6181
  answer(io, session, changed, () => formatWorkspace(changed));
@@ -3535,7 +6213,7 @@ const workspace: Command = async (args, io) => {
3535
6213
  };
3536
6214
 
3537
6215
  const PERSON_USAGE =
3538
- "Say what to do: console person role <login> <admin|member> | person manager <login> <manager login|none> | person email <login> <address|none> | person add <login> [--host gh|google] | person remove <login> | person deactivate <login> | person reactivate <login>";
6216
+ 'Say what to do: console person role <login> <admin|member> | person manager <login> <manager login|none> | person email <login> <address|none> | person title <login> "<title>"|none | person add <login> [--host gh|google] | person remove <login> | person deactivate <login> | person reactivate <login>';
3539
6217
 
3540
6218
  const person: Command = async (args, io) => {
3541
6219
  const what = args[0];
@@ -3566,6 +6244,20 @@ const person: Command = async (args, io) => {
3566
6244
  answer(io, session, changed, () => formatPersonLine(changed));
3567
6245
  return EXIT.ok;
3568
6246
  }
6247
+ if (what === "title") {
6248
+ const { values, positionals } = parse(args.slice(1), {});
6249
+ const [login, title] = theTwo(
6250
+ positionals,
6251
+ 'Say whom and what they do: console person title <login> "<title>"|none',
6252
+ );
6253
+ const session = await open(io, values);
6254
+ const found = await personOf(session, login);
6255
+ const changed = await session.client.updatePerson(found.id, {
6256
+ title: title === "none" ? null : title,
6257
+ });
6258
+ answer(io, session, changed, () => formatPersonLine(changed));
6259
+ return EXIT.ok;
6260
+ }
3569
6261
  if (what === "manager") {
3570
6262
  const { values, positionals } = parse(args.slice(1), {});
3571
6263
  const [login, manager] = theTwo(
@@ -4012,6 +6704,8 @@ const COMMANDS: Readonly<Record<string, Command>> = {
4012
6704
  logout,
4013
6705
  whoami,
4014
6706
  serve,
6707
+ runner,
6708
+ desk,
4015
6709
  projects,
4016
6710
  use,
4017
6711
  work,
@@ -4027,6 +6721,11 @@ const COMMANDS: Readonly<Record<string, Command>> = {
4027
6721
  plugin,
4028
6722
  people,
4029
6723
  person,
6724
+ manager,
6725
+ agents,
6726
+ agent,
6727
+ secrets,
6728
+ secret,
4030
6729
  teams,
4031
6730
  team,
4032
6731
  workspace,
@@ -4061,7 +6760,7 @@ function help(io: CliIo, name: string | undefined): number {
4061
6760
  io.stdout(usage(io.version, io.skillsDir));
4062
6761
  return EXIT.ok;
4063
6762
  }
4064
- const found = helpFor(name);
6763
+ const found = helpFor(name, io.skillsDir);
4065
6764
  if (found === undefined) {
4066
6765
  throw misuse(`Not a command: ${name}. The commands: ${Object.keys(COMMAND_HELP).join(", ")}`);
4067
6766
  }
@@ -4090,7 +6789,8 @@ interface ConsoleSeen {
4090
6789
 
4091
6790
  /** The command that puts the console's version where this command is installed. */
4092
6791
  function updateWords(io: CliIo, version: string | undefined): string {
4093
- const wanted = version ?? "latest";
6792
+ // What a console says its version is goes into a line someone runs: a version, or `latest`.
6793
+ const wanted = version !== undefined && parseVersion(version) !== undefined ? version : "latest";
4094
6794
  if (io.install === undefined) {
4095
6795
  return `npm install -g @skillcdn/console@${wanted}`;
4096
6796
  }
@@ -4240,6 +6940,8 @@ function hintFor(error: ApiError, io: CliIo, seen: ConsoleSeen): string {
4240
6940
  return "The board keeps at least one administrator in. Make another one first.\n";
4241
6941
  case "person.of_organization":
4242
6942
  return "The organization says who is in: a person it let in comes and goes with it, and is listed by login to stay.\n";
6943
+ case "agent.login_is_member":
6944
+ return "A member carries that login already, and nothing was changed. Name the login of the agent's own account with --login; or, to make that member the agent account for good, with everything they did, say so with --convert.\n";
4243
6945
  case "listing.exists":
4244
6946
  return "The login is let in already, or is a person's who is in. console people lists both.\n";
4245
6947
  case "listing.not_found":
@@ -4263,6 +6965,7 @@ export async function runCli(argv: readonly string[], io: CliIo): Promise<number
4263
6965
  const seen: ConsoleSeen = {};
4264
6966
  const watched: CliIo = {
4265
6967
  ...io,
6968
+ consoleVersion: () => seen.version,
4266
6969
  fetch: async (input, init) => {
4267
6970
  const response = await io.fetch(input, init);
4268
6971
  seen.version = response.headers.get(VERSION_HEADER) ?? seen.version;
@@ -4303,6 +7006,10 @@ export async function runCli(argv: readonly string[], io: CliIo): Promise<number
4303
7006
  io.stderr(`${error.message}\n`);
4304
7007
  return error.exit;
4305
7008
  }
7009
+ if (error instanceof UnseenProject) {
7010
+ io.stderr(`${error.words}\n`);
7011
+ return EXIT.failed;
7012
+ }
4306
7013
  if (error instanceof ApiError) {
4307
7014
  io.stderr(`${error.code}: ${error.message}\n${hintFor(error, io, seen)}`);
4308
7015
  return error.code === "client.outdated" ||