@skillcdn/console 0.5.0 → 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 (345) hide show
  1. package/README.md +68 -11
  2. package/SKILLCDN.md +3 -3
  3. package/dist/agent-page.d.ts.map +1 -1
  4. package/dist/agent-page.js +3 -2
  5. package/dist/agent-page.js.map +1 -1
  6. package/dist/api.d.ts +7 -6
  7. package/dist/api.d.ts.map +1 -1
  8. package/dist/api.js +6 -5
  9. package/dist/api.js.map +1 -1
  10. package/dist/charts.d.ts +103 -0
  11. package/dist/charts.d.ts.map +1 -0
  12. package/dist/charts.js +182 -0
  13. package/dist/charts.js.map +1 -0
  14. package/dist/cli/cli.d.ts +26 -2
  15. package/dist/cli/cli.d.ts.map +1 -1
  16. package/dist/cli/cli.js +1304 -383
  17. package/dist/cli/cli.js.map +1 -1
  18. package/dist/cli/command-words.d.ts +20 -0
  19. package/dist/cli/command-words.d.ts.map +1 -0
  20. package/dist/cli/command-words.js +51 -0
  21. package/dist/cli/command-words.js.map +1 -0
  22. package/dist/cli/credentials.d.ts +54 -5
  23. package/dist/cli/credentials.d.ts.map +1 -1
  24. package/dist/cli/credentials.js +126 -20
  25. package/dist/cli/credentials.js.map +1 -1
  26. package/dist/cli/directory.d.ts +19 -4
  27. package/dist/cli/directory.d.ts.map +1 -1
  28. package/dist/cli/directory.js +16 -8
  29. package/dist/cli/directory.js.map +1 -1
  30. package/dist/cli/format.d.ts +65 -8
  31. package/dist/cli/format.d.ts.map +1 -1
  32. package/dist/cli/format.js +242 -37
  33. package/dist/cli/format.js.map +1 -1
  34. package/dist/cli/help.d.ts +13 -4
  35. package/dist/cli/help.d.ts.map +1 -1
  36. package/dist/cli/help.js +92 -54
  37. package/dist/cli/help.js.map +1 -1
  38. package/dist/cli/main.js +76 -2
  39. package/dist/cli/main.js.map +1 -1
  40. package/dist/cli/pack.d.ts +69 -60
  41. package/dist/cli/pack.d.ts.map +1 -1
  42. package/dist/cli/pack.js +241 -270
  43. package/dist/cli/pack.js.map +1 -1
  44. package/dist/cli/plugin-check.d.ts +42 -0
  45. package/dist/cli/plugin-check.d.ts.map +1 -1
  46. package/dist/cli/plugin-check.js +221 -36
  47. package/dist/cli/plugin-check.js.map +1 -1
  48. package/dist/cli/plugin-cli.d.ts +6 -1
  49. package/dist/cli/plugin-cli.d.ts.map +1 -1
  50. package/dist/cli/plugin-cli.js +21 -4
  51. package/dist/cli/plugin-cli.js.map +1 -1
  52. package/dist/cli/plugin-main.js +1 -0
  53. package/dist/cli/plugin-main.js.map +1 -1
  54. package/dist/cli/serve.d.ts +33 -1
  55. package/dist/cli/serve.d.ts.map +1 -1
  56. package/dist/cli/serve.js +252 -3
  57. package/dist/cli/serve.js.map +1 -1
  58. package/dist/client.d.ts +48 -9
  59. package/dist/client.d.ts.map +1 -1
  60. package/dist/client.js +72 -80
  61. package/dist/client.js.map +1 -1
  62. package/dist/components/agent-page.d.ts +64 -1
  63. package/dist/components/agent-page.d.ts.map +1 -1
  64. package/dist/components/agent-page.js +244 -96
  65. package/dist/components/agent-page.js.map +1 -1
  66. package/dist/components/charts.d.ts +157 -0
  67. package/dist/components/charts.d.ts.map +1 -0
  68. package/dist/components/charts.js +182 -0
  69. package/dist/components/charts.js.map +1 -0
  70. package/dist/components/desk-records.d.ts +102 -0
  71. package/dist/components/desk-records.d.ts.map +1 -0
  72. package/dist/components/desk-records.js +221 -0
  73. package/dist/components/desk-records.js.map +1 -0
  74. package/dist/components/desk.d.ts +85 -0
  75. package/dist/components/desk.d.ts.map +1 -0
  76. package/dist/components/desk.js +135 -0
  77. package/dist/components/desk.js.map +1 -0
  78. package/dist/components/event-feed.d.ts.map +1 -1
  79. package/dist/components/event-feed.js +4 -1
  80. package/dist/components/event-feed.js.map +1 -1
  81. package/dist/components/home.d.ts.map +1 -1
  82. package/dist/components/home.js +4 -2
  83. package/dist/components/home.js.map +1 -1
  84. package/dist/components/plugin-settings.d.ts.map +1 -1
  85. package/dist/components/plugin-settings.js +54 -3
  86. package/dist/components/plugin-settings.js.map +1 -1
  87. package/dist/components/projects.d.ts.map +1 -1
  88. package/dist/components/projects.js +27 -7
  89. package/dist/components/projects.js.map +1 -1
  90. package/dist/components/rules.d.ts +8 -10
  91. package/dist/components/rules.d.ts.map +1 -1
  92. package/dist/components/rules.js +35 -13
  93. package/dist/components/rules.js.map +1 -1
  94. package/dist/components/setup.d.ts +9 -3
  95. package/dist/components/setup.d.ts.map +1 -1
  96. package/dist/components/setup.js +10 -4
  97. package/dist/components/setup.js.map +1 -1
  98. package/dist/console.css +677 -7
  99. package/dist/console.d.ts +5 -0
  100. package/dist/console.d.ts.map +1 -1
  101. package/dist/console.js +14 -8
  102. package/dist/console.js.map +1 -1
  103. package/dist/data.d.ts.map +1 -1
  104. package/dist/data.js +32 -33
  105. package/dist/data.js.map +1 -1
  106. package/dist/desk-page.d.ts +38 -0
  107. package/dist/desk-page.d.ts.map +1 -0
  108. package/dist/desk-page.js +184 -0
  109. package/dist/desk-page.js.map +1 -0
  110. package/dist/desk-records-page.d.ts +18 -0
  111. package/dist/desk-records-page.d.ts.map +1 -0
  112. package/dist/desk-records-page.js +130 -0
  113. package/dist/desk-records-page.js.map +1 -0
  114. package/dist/desk-records.d.ts +247 -0
  115. package/dist/desk-records.d.ts.map +1 -0
  116. package/dist/desk-records.js +543 -0
  117. package/dist/desk-records.js.map +1 -0
  118. package/dist/desk.d.ts +122 -0
  119. package/dist/desk.d.ts.map +1 -0
  120. package/dist/desk.js +211 -0
  121. package/dist/desk.js.map +1 -0
  122. package/dist/feed-stream.d.ts +39 -0
  123. package/dist/feed-stream.d.ts.map +1 -0
  124. package/dist/feed-stream.js +117 -0
  125. package/dist/feed-stream.js.map +1 -0
  126. package/dist/home-tiles.d.ts +10 -3
  127. package/dist/home-tiles.d.ts.map +1 -1
  128. package/dist/home-tiles.js +54 -31
  129. package/dist/home-tiles.js.map +1 -1
  130. package/dist/i18n/en.d.ts +180 -5
  131. package/dist/i18n/en.d.ts.map +1 -1
  132. package/dist/i18n/en.js +184 -7
  133. package/dist/i18n/en.js.map +1 -1
  134. package/dist/i18n/ko.d.ts.map +1 -1
  135. package/dist/i18n/ko.js +169 -6
  136. package/dist/i18n/ko.js.map +1 -1
  137. package/dist/index.d.ts +8 -0
  138. package/dist/index.d.ts.map +1 -1
  139. package/dist/index.js +8 -0
  140. package/dist/index.js.map +1 -1
  141. package/dist/limits.d.ts +11 -0
  142. package/dist/limits.d.ts.map +1 -1
  143. package/dist/limits.js +11 -0
  144. package/dist/limits.js.map +1 -1
  145. package/dist/onboarding.d.ts +6 -0
  146. package/dist/onboarding.d.ts.map +1 -1
  147. package/dist/onboarding.js +3 -3
  148. package/dist/onboarding.js.map +1 -1
  149. package/dist/plugin/context.d.ts +42 -11
  150. package/dist/plugin/context.d.ts.map +1 -1
  151. package/dist/plugin/limits.d.ts +2 -0
  152. package/dist/plugin/limits.d.ts.map +1 -1
  153. package/dist/plugin/limits.js +2 -0
  154. package/dist/plugin/limits.js.map +1 -1
  155. package/dist/plugin/manifest.d.ts +13 -0
  156. package/dist/plugin/manifest.d.ts.map +1 -1
  157. package/dist/plugin/manifest.js +30 -3
  158. package/dist/plugin/manifest.js.map +1 -1
  159. package/dist/plugin/rest-schemas.d.ts +55 -0
  160. package/dist/plugin/rest-schemas.d.ts.map +1 -1
  161. package/dist/plugin/rest-schemas.js +37 -0
  162. package/dist/plugin/rest-schemas.js.map +1 -1
  163. package/dist/plugin/sandbox.d.ts.map +1 -1
  164. package/dist/plugin/sandbox.js +4 -1
  165. package/dist/plugin/sandbox.js.map +1 -1
  166. package/dist/plugin/testing.d.ts +6 -2
  167. package/dist/plugin/testing.d.ts.map +1 -1
  168. package/dist/plugin/testing.js +52 -10
  169. package/dist/plugin/testing.js.map +1 -1
  170. package/dist/plugin.d.ts +1 -1
  171. package/dist/plugin.d.ts.map +1 -1
  172. package/dist/plugin.js +1 -1
  173. package/dist/plugin.js.map +1 -1
  174. package/dist/records.d.ts +283 -0
  175. package/dist/records.d.ts.map +1 -0
  176. package/dist/records.js +543 -0
  177. package/dist/records.js.map +1 -0
  178. package/dist/routes.d.ts +3 -1
  179. package/dist/routes.d.ts.map +1 -1
  180. package/dist/routes.js +3 -1
  181. package/dist/routes.js.map +1 -1
  182. package/dist/rules.d.ts +30 -11
  183. package/dist/rules.d.ts.map +1 -1
  184. package/dist/rules.js +98 -45
  185. package/dist/rules.js.map +1 -1
  186. package/dist/runner/acp.d.ts +1 -1
  187. package/dist/runner/acp.d.ts.map +1 -1
  188. package/dist/runner/acp.js +31 -20
  189. package/dist/runner/acp.js.map +1 -1
  190. package/dist/runner/claude.d.ts +1 -1
  191. package/dist/runner/claude.d.ts.map +1 -1
  192. package/dist/runner/claude.js +85 -15
  193. package/dist/runner/claude.js.map +1 -1
  194. package/dist/runner/codex.d.ts +1 -1
  195. package/dist/runner/codex.d.ts.map +1 -1
  196. package/dist/runner/codex.js +19 -16
  197. package/dist/runner/codex.js.map +1 -1
  198. package/dist/runner/desk.d.ts +43 -2
  199. package/dist/runner/desk.d.ts.map +1 -1
  200. package/dist/runner/desk.js +166 -10
  201. package/dist/runner/desk.js.map +1 -1
  202. package/dist/runner/process.d.ts.map +1 -1
  203. package/dist/runner/process.js +11 -4
  204. package/dist/runner/process.js.map +1 -1
  205. package/dist/runner/redact.d.ts +39 -4
  206. package/dist/runner/redact.d.ts.map +1 -1
  207. package/dist/runner/redact.js +81 -5
  208. package/dist/runner/redact.js.map +1 -1
  209. package/dist/runner/runner.d.ts +15 -1
  210. package/dist/runner/runner.d.ts.map +1 -1
  211. package/dist/runner/runner.js +231 -33
  212. package/dist/runner/runner.js.map +1 -1
  213. package/dist/runner/task-scheduler.d.ts +20 -0
  214. package/dist/runner/task-scheduler.d.ts.map +1 -1
  215. package/dist/runner/task-scheduler.js +34 -4
  216. package/dist/runner/task-scheduler.js.map +1 -1
  217. package/dist/runner/types.d.ts +36 -1
  218. package/dist/runner/types.d.ts.map +1 -1
  219. package/dist/runner/types.js +17 -0
  220. package/dist/runner/types.js.map +1 -1
  221. package/dist/runner.d.ts +6 -6
  222. package/dist/runner.d.ts.map +1 -1
  223. package/dist/runner.js +5 -5
  224. package/dist/runner.js.map +1 -1
  225. package/dist/schemas.d.ts +509 -5
  226. package/dist/schemas.d.ts.map +1 -1
  227. package/dist/schemas.js +76 -16
  228. package/dist/schemas.js.map +1 -1
  229. package/dist/services.d.ts +22 -5
  230. package/dist/services.d.ts.map +1 -1
  231. package/dist/services.js +35 -15
  232. package/dist/services.js.map +1 -1
  233. package/dist/setup-guide.d.ts +3 -1
  234. package/dist/setup-guide.d.ts.map +1 -1
  235. package/dist/setup-guide.js +7 -4
  236. package/dist/setup-guide.js.map +1 -1
  237. package/dist/vocabulary.d.ts +14 -3
  238. package/dist/vocabulary.d.ts.map +1 -1
  239. package/dist/vocabulary.js +13 -3
  240. package/dist/vocabulary.js.map +1 -1
  241. package/docs/specs/cli.md +64 -38
  242. package/docs/specs/plugins.md +27 -20
  243. package/docs/specs/records.md +113 -0
  244. package/docs/specs/rest.md +20 -13
  245. package/docs/specs/runner.md +23 -17
  246. package/package.json +7 -2
  247. package/skills/building-a-console/SKILL.md +4 -4
  248. package/skills/building-a-plugin/SKILL.md +6 -6
  249. package/skills/deploying-a-console/SKILL.md +4 -4
  250. package/skills/deploying-a-console/references/resources.md +41 -4
  251. package/skills/deploying-a-console/references/running-it-again.md +3 -2
  252. package/skills/keeping-a-desk/SKILL.md +133 -0
  253. package/skills/keeping-a-desk/collections.md +96 -0
  254. package/skills/planning-the-board/SKILL.md +14 -18
  255. package/skills/planning-the-board/references/a-task.md +2 -2
  256. package/skills/planning-the-board/references/project-rules.md +13 -14
  257. package/skills/planning-the-board/references/setting-up.md +15 -13
  258. package/skills/running-an-agent/SKILL.md +10 -9
  259. package/skills/working-the-board/SKILL.md +62 -44
  260. package/skills/working-the-board/references/terms.md +9 -5
  261. package/skills/working-the-board/references/the-pack.md +12 -10
  262. package/skills/working-the-board/references/the-sentence.md +2 -2
  263. package/src/agent-page.tsx +3 -1
  264. package/src/api.ts +77 -2
  265. package/src/charts.ts +250 -0
  266. package/src/cli/cli.ts +1698 -476
  267. package/src/cli/command-words.ts +56 -0
  268. package/src/cli/credentials.ts +181 -20
  269. package/src/cli/directory.ts +28 -10
  270. package/src/cli/format.ts +301 -46
  271. package/src/cli/help.ts +102 -54
  272. package/src/cli/main.ts +72 -2
  273. package/src/cli/pack.ts +333 -372
  274. package/src/cli/plugin-check.ts +275 -34
  275. package/src/cli/plugin-cli.ts +28 -4
  276. package/src/cli/plugin-main.ts +1 -0
  277. package/src/cli/serve.ts +295 -2
  278. package/src/client.ts +192 -177
  279. package/src/components/agent-page.tsx +489 -243
  280. package/src/components/charts.tsx +680 -0
  281. package/src/components/desk-records.tsx +724 -0
  282. package/src/components/desk.tsx +471 -0
  283. package/src/components/event-feed.tsx +5 -1
  284. package/src/components/home.tsx +12 -0
  285. package/src/components/plugin-settings.tsx +171 -12
  286. package/src/components/projects.tsx +29 -12
  287. package/src/components/rules.tsx +94 -34
  288. package/src/components/setup.tsx +18 -3
  289. package/src/console.tsx +17 -9
  290. package/src/data.ts +37 -34
  291. package/src/desk-page.tsx +332 -0
  292. package/src/desk-records-page.tsx +256 -0
  293. package/src/desk-records.ts +808 -0
  294. package/src/desk.ts +329 -0
  295. package/src/feed-stream.ts +144 -0
  296. package/src/home-tiles.ts +55 -35
  297. package/src/i18n/en.ts +196 -9
  298. package/src/i18n/ko.ts +178 -8
  299. package/src/index.ts +118 -0
  300. package/src/limits.ts +11 -0
  301. package/src/onboarding.ts +12 -4
  302. package/src/plugin/context.ts +55 -12
  303. package/src/plugin/limits.ts +2 -0
  304. package/src/plugin/manifest.ts +38 -2
  305. package/src/plugin/rest-schemas.ts +41 -0
  306. package/src/plugin/sandbox.ts +4 -1
  307. package/src/plugin/testing.ts +63 -12
  308. package/src/plugin.ts +2 -0
  309. package/src/records.ts +702 -0
  310. package/src/routes.ts +3 -1
  311. package/src/rules.ts +108 -47
  312. package/src/runner/acp.ts +47 -29
  313. package/src/runner/claude.ts +113 -23
  314. package/src/runner/codex.ts +35 -25
  315. package/src/runner/desk.ts +198 -12
  316. package/src/runner/process.ts +11 -4
  317. package/src/runner/redact.ts +92 -6
  318. package/src/runner/runner.ts +275 -34
  319. package/src/runner/task-scheduler.ts +36 -4
  320. package/src/runner/types.ts +47 -1
  321. package/src/runner.ts +27 -2
  322. package/src/schemas.ts +83 -15
  323. package/src/services.ts +49 -14
  324. package/src/setup-guide.ts +6 -2
  325. package/src/styles/README.md +11 -1
  326. package/src/styles/console.css +9 -0
  327. package/src/styles/pages/desk.css +126 -0
  328. package/src/styles/pages/documents.css +5 -0
  329. package/src/styles/parts/bars.css +80 -0
  330. package/src/styles/parts/chart.css +173 -0
  331. package/src/styles/parts/figures.css +65 -0
  332. package/src/styles/parts/legend.css +48 -0
  333. package/src/styles/parts/series.css +32 -0
  334. package/src/styles/parts/share.css +25 -0
  335. package/src/styles/parts/spark.css +23 -0
  336. package/src/styles/parts/stat.css +69 -0
  337. package/src/styles/tokens.css +13 -7
  338. package/src/vocabulary.ts +16 -3
  339. package/template/desk-web/README.md +8 -0
  340. package/template/desk-web/index.html +13 -0
  341. package/template/desk-web/package.json +25 -0
  342. package/template/desk-web/src/main.tsx +24 -0
  343. package/template/desk-web/src/page.tsx +51 -0
  344. package/template/desk-web/tsconfig.json +16 -0
  345. package/template/desk-web/vite.config.ts +15 -0
package/src/cli/cli.ts CHANGED
@@ -1,6 +1,21 @@
1
- import { basename, extname } from "node:path";
1
+ import { basename, extname, isAbsolute } from "node:path";
2
2
  import { parseArgs } from "node:util";
3
3
  import { deflateSync } from "node:zlib";
4
+ import {
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";
4
19
  import { avatarScanlines, MAX_AVATAR_PIXELS, pngFile } from "../avatar.js";
5
20
  import {
6
21
  ApiError,
@@ -8,6 +23,7 @@ import {
8
23
  createClient,
9
24
  type FetchLike,
10
25
  type FileUpload,
26
+ type PackClient,
11
27
  type PluginClient,
12
28
  type ProjectClient,
13
29
  } from "../client.js";
@@ -26,6 +42,7 @@ import { normalizeConnectCode } from "../connect.js";
26
42
  import { addDays, dayOf as dayOfDate, firstDayOfWeek, isDay, weekOf } from "../dates.js";
27
43
  import {
28
44
  DEFAULT_PAGE_LIMIT,
45
+ EVENTS_PAGE_LIMIT,
29
46
  LIST_LIMIT,
30
47
  MAX_DECIDERS,
31
48
  MAX_OPTIONS,
@@ -35,9 +52,17 @@ import {
35
52
  } from "../limits.js";
36
53
  import { capabilityWords } from "../plugin/capabilities.js";
37
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";
38
57
  import { fillRules, RULES_PATH, RULES_TITLE } from "../rules.js";
39
58
  import { DEFAULT_RUNNER_CONFIG, parseRunnerConfig } from "../runner/config.js";
40
- import { deskFiles, deskServicesOf } from "../runner/desk.js";
59
+ import {
60
+ DESK_FOLDER,
61
+ deskFiles,
62
+ deskServicesOf,
63
+ deskWebTitleOf,
64
+ personDeskFiles,
65
+ } from "../runner/desk.js";
41
66
  import { ownRunnerModules } from "../runner/modules.js";
42
67
  import { createRunner, GIT_TOKEN_SECRET, type RunnerState } from "../runner/runner.js";
43
68
  import type { ServiceCommand } from "../runner/types.js";
@@ -54,12 +79,10 @@ import {
54
79
  type RestPluginEnableInput,
55
80
  type RestPluginGrantInput,
56
81
  type RestPluginInvocation,
57
- type RestSkillBrowse,
58
- type RestSkillCode,
59
- type RestSkillFile,
60
- type RestSkillLoad,
61
- type RestSkillRows,
62
- type RestSkills,
82
+ type RestRules,
83
+ type RestRun,
84
+ type RestRunBrief,
85
+ type RestTask,
63
86
  type RestTaskPatch,
64
87
  } from "../schemas.js";
65
88
  import { agentLoginOf, deskRemoteOf } from "../services.js";
@@ -89,18 +112,31 @@ import {
89
112
  WEEK_STARTS,
90
113
  } from "../vocabulary.js";
91
114
  import { loadWebRoot, type WebRoot, WebRootError } from "../web.js";
115
+ import { commandLine, commandWord, NO_LINE_TO_RUN } from "./command-words.js";
92
116
  import {
93
117
  type CredentialStore,
94
118
  type Credentials,
95
119
  CredentialsError,
96
120
  EMPTY_CREDENTIALS,
121
+ fitsFile,
122
+ keepsNothing,
123
+ lasts,
97
124
  loginsAt,
125
+ type PendingConnection,
126
+ pendingAt,
98
127
  type Resolution,
99
128
  resolveLogin,
100
129
  withLogin,
101
130
  withoutLogin,
131
+ withoutPending,
132
+ withPending,
102
133
  } from "./credentials.js";
103
- import { type DirectorySettings, type DirectoryStore, THE_SENTENCE } from "./directory.js";
134
+ import {
135
+ DIRECTORY_FILE,
136
+ type DirectorySettings,
137
+ type DirectoryStore,
138
+ THE_SENTENCE,
139
+ } from "./directory.js";
104
140
  import {
105
141
  calledOf,
106
142
  deciderLogins,
@@ -124,6 +160,7 @@ import {
124
160
  formatPersonWork,
125
161
  formatPlugin,
126
162
  formatPluginAsks,
163
+ formatPluginEvents,
127
164
  formatPluginGrantLine,
128
165
  formatPluginHelp,
129
166
  formatPluginRecord,
@@ -134,6 +171,8 @@ import {
134
171
  formatProject,
135
172
  formatProjectLine,
136
173
  formatRules,
174
+ formatRulesChanged,
175
+ formatRulesLeftOut,
137
176
  formatRun,
138
177
  formatRunLine,
139
178
  formatSecretLine,
@@ -147,36 +186,34 @@ import {
147
186
  formatWorkspace,
148
187
  localized,
149
188
  moment,
189
+ pageLine,
190
+ rulesMark,
150
191
  setMomentZone,
151
192
  } from "./format.js";
152
193
  import { COMMAND_HELP, helpFor, ownSkillPath, usage } from "./help.js";
153
194
  import { describeInstall, type Install, updateCommandFor } from "./install.js";
154
195
  import type { NoticeStore } from "./notices.js";
155
196
  import {
156
- bodyOfFile,
157
- bodyOfFolder,
158
- bodyOfSkill,
159
- csvOfRows,
160
- dataRefusal,
161
- describeCode,
162
- describeRows,
163
- formatSkillBrowse,
164
- formatSkillFile,
165
- formatSkillFind,
166
- formatSkillLoad,
197
+ type ConsolePack,
198
+ consolePack,
167
199
  formatSkills,
168
- joinCode,
169
- joinFile,
170
- joinFolder,
171
- joinRows,
172
- joinSkill,
173
- type PackSummary,
200
+ holdsNothing,
201
+ ORGANIZATION_PACK_LINE,
202
+ type PackOwner,
203
+ PackRefusal,
204
+ packWords,
205
+ refusalWords,
174
206
  skillPathIn,
175
- summaryOf,
176
- textOfCode,
177
207
  } from "./pack.js";
178
208
  import { type RunnerHost, workPath } from "./runner-host.js";
179
- import { createServeHandler, DEFAULT_SERVE_PORT, type Listen } from "./serve.js";
209
+ import {
210
+ createServeHandler,
211
+ DEFAULT_SERVE_PORT,
212
+ type Listen,
213
+ loadRecordsRoot,
214
+ type RecordsRoot,
215
+ RecordsRootError,
216
+ } from "./serve.js";
180
217
  import type { Ran, SetupMachine } from "./setup-machine.js";
181
218
 
182
219
  // The `console` command (docs/specs/cli.md): the agent's side of the console. A thin client of
@@ -192,7 +229,7 @@ export const EXIT = {
192
229
  failed: 1,
193
230
  /** The command was not understood. */
194
231
  usage: 2,
195
- /** 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. */
196
233
  waiting: 3,
197
234
  /** The command and the console do not go together (ADR-0025): stderr says which to update, and how. */
198
235
  incompatible: 4,
@@ -209,6 +246,12 @@ const WAIT_PAUSE_MS = 500;
209
246
  const DEFAULT_ASK_WAIT_SECONDS = 60;
210
247
  /** The longest wait a person may ask for: a day. */
211
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;
212
255
 
213
256
  export interface CliIo {
214
257
  readonly env: Readonly<Record<string, string | undefined>>;
@@ -225,6 +268,14 @@ export interface CliIo {
225
268
  readonly readSecret?: ((prompt: string) => Promise<string>) | undefined;
226
269
  /** The name of the machine, for the agent to say where it runs; nothing when unknown. */
227
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;
228
279
  /** A file named with `--file`, as text. */
229
280
  readonly readFile: (path: string) => Promise<string>;
230
281
  /** A file handed in, as bytes. */
@@ -262,8 +313,22 @@ export interface CliIo {
262
313
  readonly listen?: Listen | undefined;
263
314
  /** What `runner` needs of the machine (ADR-0085); left out, the command cannot run one. */
264
315
  readonly runner?: RunnerHost | undefined;
265
- /** What `agent setup` needs of the machine (ADR-0088); left out, the command sets none up. */
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. */
266
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;
267
332
  }
268
333
 
269
334
  /** The command stops with an exit code and a word on stderr. */
@@ -344,6 +409,101 @@ interface Session {
344
409
  project(): Promise<ProjectClient>;
345
410
  /** The key of that project, or nothing when none is named. */
346
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
+ }
347
507
  }
348
508
 
349
509
  const NO_PROJECT =
@@ -363,6 +523,21 @@ async function loadCredentials(io: CliIo): Promise<Credentials | undefined> {
363
523
  }
364
524
  }
365
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
+
366
541
  /** The console a directory is bound to, as an origin, when it names one. */
367
542
  function directoryOrigin(settings: DirectorySettings | undefined): string | undefined {
368
543
  if (settings?.url === undefined) {
@@ -427,8 +602,19 @@ async function open(io: CliIo, values: Values): Promise<Session> {
427
602
  : undefined,
428
603
  );
429
604
  const client = clientOf(io, url, token);
430
- const projectKey = async () =>
431
- 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;
432
618
  return {
433
619
  client,
434
620
  url,
@@ -438,12 +624,19 @@ async function open(io: CliIo, values: Values): Promise<Session> {
438
624
  credentials,
439
625
  json: on(values, "json"),
440
626
  projectKey,
627
+ projectNamed,
441
628
  async project() {
442
- const key = await projectKey();
443
- if (key === undefined) {
629
+ const named = projectNamed();
630
+ if (named === undefined) {
444
631
  throw failed(NO_PROJECT);
445
632
  }
446
- 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
+ );
447
640
  },
448
641
  };
449
642
  }
@@ -454,17 +647,38 @@ function answer(io: CliIo, session: Session, value: unknown, words: () => string
454
647
  }
455
648
 
456
649
  /** The run a command on a run means: the one named, else the one open run of this token in the project. */
457
- 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> {
458
655
  const given = text(values, "run");
459
656
  if (given !== undefined) {
460
657
  return given;
461
658
  }
462
- 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 });
463
662
  const [only] = items;
464
663
  if (only !== undefined && items.length === 1) {
465
664
  return only.id;
466
665
  }
467
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
+ }
468
682
  throw failed(
469
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>",
470
684
  );
@@ -474,6 +688,30 @@ async function currentRun(project: ProjectClient, values: Values): Promise<strin
474
688
  );
475
689
  }
476
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
+
477
715
  /** A Markdown body: from `--file`, from standard input for `-`, or as given. */
478
716
  async function bodyOf(
479
717
  io: CliIo,
@@ -736,6 +974,8 @@ async function settle(
736
974
  decision: RestDecision,
737
975
  seconds: number,
738
976
  shown = false,
977
+ /** What is said where the decision still waits, in place of how an attended agent waits on. */
978
+ waiting?: string,
739
979
  ): Promise<number> {
740
980
  const outcome =
741
981
  decision.answer === null && seconds > 0
@@ -746,11 +986,46 @@ async function settle(
746
986
  io.stdout(`${JSON.stringify(outcome, null, 2)}\n`);
747
987
  }
748
988
  } else {
749
- 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
+ );
750
992
  }
751
993
  return outcome.answer === null ? EXIT.waiting : EXIT.ok;
752
994
  }
753
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
+
754
1029
  type Command = (args: readonly string[], io: CliIo) => Promise<number>;
755
1030
 
756
1031
  /**
@@ -792,12 +1067,6 @@ async function keep(
792
1067
  );
793
1068
  }
794
1069
  const credentials = (await loadCredentials(io)) ?? EMPTY_CREDENTIALS;
795
- const replaced = loginsAt(credentials, url).find((login) => login.account === person.login);
796
- if (replaced !== undefined && replaced.token !== token) {
797
- await clientOf(io, url, replaced.token)
798
- .giveUpToken()
799
- .catch(() => undefined);
800
- }
801
1070
  const next = withLogin(
802
1071
  credentials,
803
1072
  {
@@ -809,14 +1078,34 @@ async function keep(
809
1078
  ...(self ? { self: true } : {}),
810
1079
  timeZone: me.workspace.timeZone ?? undefined,
811
1080
  },
1081
+ io.now(),
812
1082
  { default: asDefault },
813
1083
  );
814
- 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);
815
1095
  const standing = next.default === url ? ", the default console here" : "";
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}`;
816
1105
  say(
817
1106
  self
818
- ? `Signed in to ${me.workspace.name} at ${url} as ${whoOf(person)}, the account itself${standing}: what this command does, ${person.login} does, and no agent is named beside it. The session is kept while it is used; its secret is kept in ${kept}.\nNext, say which project this directory works in: console use <key> (console projects lists them).\n`
819
- : `${agent === undefined ? "Signed in" : `Connected as "${agent}"`} to ${me.workspace.name} at ${url} as ${whoOf(person)}${standing}. The token is kept in ${kept}.\nNext, say which project this directory works in: console use <key> (console projects lists them).\n`,
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`,
820
1109
  );
821
1110
  return EXIT.ok;
822
1111
  }
@@ -829,6 +1118,7 @@ const login: Command = async (args, io) => {
829
1118
  agent: { type: "string" },
830
1119
  self: { type: "boolean" },
831
1120
  default: { type: "boolean" },
1121
+ wait: { type: "string" },
832
1122
  },
833
1123
  false,
834
1124
  );
@@ -849,39 +1139,167 @@ const login: Command = async (args, io) => {
849
1139
  // A connection (ADR-0011): a code a person approves on the console's own pages, and the token
850
1140
  // handed over here once, never shown.
851
1141
  const client = clientOf(io, url);
852
- // "<agent> on <machine>": the pages say the agent and keep the machine for a hover.
853
- const agent = text(values, "agent") ?? agentOf(io.env) ?? "An agent";
854
1142
  // With --self the command asks to be the account itself (ADR-0084): whoever approves says
855
1143
  // "this is me", and what is handed over is a session of the command's, in place of a token.
856
1144
  const self = on(values, "self");
857
- const begun = await client.connect({
858
- agent: io.hostname === undefined ? agent : `${agent} on ${io.hostname}`,
859
- ...(self ? { as: "self" as const } : {}),
860
- });
861
- io.stdout(
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 =>
862
1160
  self
863
- ? `To sign this command in as an account itself, open ${begun.url} signed in as that account, check that the page shows the code ${begun.code}, and say that it is you.\nWaiting for that, until ${begun.expiresAt}.\n`
864
- : `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`,
865
- );
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
+ }
866
1188
  for (;;) {
867
- await io.sleep(begun.interval * 1000);
868
- let claim: RestClaim;
869
- try {
870
- claim = await client.claimConnection(begun.secret);
871
- } catch (error) {
872
- if (error instanceof ApiError && error.code === "connect.not_found") {
873
- throw failed(
874
- "The connection was not approved in time, or the person said it was not theirs. Run console login again for a new code.",
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
+ ),
875
1215
  );
876
1216
  }
877
- throw error;
878
1217
  }
879
- if (claim.status === "connected") {
880
- return keep(io, url, claim.secret, claim.token.name, asDefault);
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;
881
1244
  }
882
- if (claim.status === "signed_in") {
883
- return keep(io, url, claim.secret, undefined, asDefault, true);
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) {
1285
+ throw failed(
1286
+ "The connection was not approved in time, or the person said it was not theirs. Run console login again for a new code.",
1287
+ );
1288
+ }
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;
884
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;
885
1303
  }
886
1304
  };
887
1305
 
@@ -895,7 +1313,14 @@ const logout: Command = async (args, io) => {
895
1313
  }
896
1314
  };
897
1315
  if (credentials === undefined || credentials.logins.length === 0) {
898
- 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
+ }
899
1324
  envNote();
900
1325
  return EXIT.ok;
901
1326
  }
@@ -919,8 +1344,19 @@ const logout: Command = async (args, io) => {
919
1344
  const chosen = account === undefined ? at : at.filter((login) => login.account === account);
920
1345
  const [login] = chosen;
921
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
+ }
922
1358
  throw failed(
923
- `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.`,
924
1360
  );
925
1361
  }
926
1362
  if (chosen.length > 1) {
@@ -945,8 +1381,14 @@ const logout: Command = async (args, io) => {
945
1381
  outcome = "left";
946
1382
  }
947
1383
  }
948
- const next = withoutLogin(credentials, url, login.account);
949
- 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)) {
950
1392
  await io.store.clear();
951
1393
  } else {
952
1394
  await io.store.save(next);
@@ -976,24 +1418,49 @@ const logins: Command = async (args, io) => {
976
1418
  since: login.since ?? null,
977
1419
  default: credentials?.default === login.url,
978
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
+ }));
979
1431
  if (on(values, "json")) {
980
1432
  io.stdout(
981
- `${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`,
982
1442
  );
983
1443
  return EXIT.ok;
984
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
+ }
985
1460
  if (kept.length === 0) {
986
- io.stdout("Not signed in anywhere here: console login --url <the console's origin>\n");
987
- return EXIT.ok;
1461
+ lines.unshift("Not signed in anywhere here: console login --url <the console's origin>");
988
1462
  }
989
- io.stdout(
990
- `${kept
991
- .map(
992
- (login) =>
993
- `${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)" : ""}`,
994
- )
995
- .join("\n")}\n`,
996
- );
1463
+ io.stdout(`${lines.join("\n")}\n`);
997
1464
  return EXIT.ok;
998
1465
  };
999
1466
 
@@ -1023,7 +1490,10 @@ async function rememberZone(io: CliIo, session: Session, zone: string | undefine
1023
1490
  if (kept === undefined || kept.timeZone === zone) {
1024
1491
  return;
1025
1492
  }
1026
- 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
+ );
1027
1497
  }
1028
1498
 
1029
1499
  const whoami: Command = async (args, io) => {
@@ -1035,7 +1505,29 @@ const whoami: Command = async (args, io) => {
1035
1505
  throw failed("The console does not know this token. Sign in again: console login");
1036
1506
  }
1037
1507
  await rememberZone(io, session, me.workspace.timeZone ?? undefined);
1038
- 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)}`;
1039
1531
  const command = parseVersion(io.version);
1040
1532
  const server = parseVersion(me.console?.version);
1041
1533
  const verdict =
@@ -1058,16 +1550,23 @@ const whoami: Command = async (args, io) => {
1058
1550
  ...me,
1059
1551
  console: me.console ?? null,
1060
1552
  project: key ?? null,
1553
+ projectName: projectName ?? null,
1554
+ projectSource: named?.source ?? null,
1061
1555
  command: { version: io.version ?? null, install: io.install ?? null },
1062
1556
  },
1063
1557
  () =>
1064
1558
  [
1065
- `${whoOf(person)} at ${me.workspace.name}, ${session.url}${key === undefined ? "; no project named here" : `; project ${key}`}${me.session?.kind === "command" ? "; signed in as the account itself" : ""}`,
1066
- // The pack's rules send an agent here first; from here the rules and the skill are the next
1067
- // steps. In a directory that names no project too: an agent account's desk names none,
1068
- // the command's help sends an agent here for where the skill is, and the workspace has
1069
- // rules whatever the project.
1070
- `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)}`}`,
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)}`,
1071
1570
  `This command is ${io.version ?? "of a version it does not know"}${io.install === undefined ? "" : `, ${describeInstall(io.install)}`}; ${consoleWords}.`,
1072
1571
  ...(verdict === "behind"
1073
1572
  ? [`A newer command exists. Update it: ${updateWords(io, me.console?.version)}`]
@@ -1078,6 +1577,11 @@ const whoami: Command = async (args, io) => {
1078
1577
  : []),
1079
1578
  ].join("\n"),
1080
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
+ }
1081
1585
  return EXIT.ok;
1082
1586
  };
1083
1587
 
@@ -1101,26 +1605,23 @@ const use: Command = async (args, io) => {
1101
1605
  );
1102
1606
  const session = await open(io, values);
1103
1607
  const project = await session.client.project(key).get();
1104
- // The directory names the console where that is not the default login here, or when asked,
1105
- // and the account where the console has several, or when asked; never a token.
1106
- const credentials = session.credentials ?? EMPTY_CREDENTIALS;
1107
- const pinUrl =
1108
- text(values, "url") !== undefined ||
1109
- (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();
1110
1613
  const pinAccount =
1111
- text(values, "account") !== undefined ||
1112
- (session.via === "login" && loginsAt(credentials, session.url).length > 1);
1614
+ session.account !== undefined &&
1615
+ (text(values, "account") !== undefined || before?.account === session.account);
1113
1616
  const kept = await io.directory.save({
1114
1617
  project: project.key,
1115
- ...(pinUrl ? { url: session.url } : {}),
1116
- ...(pinAccount && session.account !== undefined ? { account: session.account } : {}),
1618
+ url: session.url,
1619
+ ...(pinAccount ? { account: session.account } : {}),
1117
1620
  });
1118
- const bound = pinUrl
1119
- ? ` at ${session.url}${pinAccount && session.account !== undefined ? ` as ${session.account}` : ""}`
1120
- : "";
1621
+ const bound = ` at ${session.url}${pinAccount ? ` as ${session.account}` : ""}`;
1121
1622
  answer(io, session, project, () =>
1122
1623
  [
1123
- `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.`,
1124
1625
  // Nothing sends an agent to the console until the checkout says so; the sentence is the
1125
1626
  // skill's (references/the-sentence.md), printed here as `skillcdn use` prints its own.
1126
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:",
@@ -1194,7 +1695,7 @@ const tasks: Command = async (args, io) => {
1194
1695
  if (search === "") {
1195
1696
  throw misuse("Say what to search for: console tasks --search <words>");
1196
1697
  }
1197
- const found = await project.tasks({
1698
+ const filter = {
1198
1699
  ...(state === undefined ? {} : { state }),
1199
1700
  ...(on(values, "open") || due === "overdue" ? { open: true } : {}),
1200
1701
  ...(worker === undefined ? {} : { worker }),
@@ -1205,10 +1706,22 @@ const tasks: Command = async (args, io) => {
1205
1706
  ...(search === undefined ? {} : { q: search }),
1206
1707
  ...(on(values, "archived") ? { archived: true } : {}),
1207
1708
  ...page,
1208
- });
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()}".`;
1209
1722
  answer(io, session, found, () =>
1210
1723
  found.items.length === 0
1211
- ? "No tasks."
1724
+ ? none
1212
1725
  : found.items.map(formatTaskLine).join("\n") +
1213
1726
  formatMore(found.more, page.limit, page.offset),
1214
1727
  );
@@ -1241,157 +1754,192 @@ const categories: Command = async (args, io) => {
1241
1754
  return EXIT.ok;
1242
1755
  };
1243
1756
 
1244
- /** How many pages of a skill, of a file or of a folder the command follows before it stops: far above what one holds. */
1245
- const MAX_SKILL_PAGES = 64;
1246
- /** How many results a search answers at most: what the deployment allows on one page. */
1247
- const MAX_FIND_LIMIT = 25;
1248
- /** How many rows, and how many code blocks, one page of a read as data is asked to end after: the most the console takes. */
1249
- const DATA_PAGE_ROWS = 5000;
1250
- const DATA_PAGE_BLOCKS = 500;
1251
-
1252
- /** The pack of the project as the console lists it, and what its reads are rendered at; none when the pack did not answer. */
1253
- async function packOf(
1254
- reader: PackReader,
1255
- ): Promise<{ readonly listing: RestSkills; readonly summary: PackSummary | undefined }> {
1256
- const listing = await reader.skills();
1257
- return { listing, summary: summaryOf(listing) };
1258
- }
1259
-
1260
- /** What reads a pack: a project's client, or a plugin's, whose skills are a pack of their own. */
1261
- type PackReader = Pick<
1262
- ProjectClient,
1263
- "skills" | "skill" | "skillFile" | "skillBrowse" | "skillFind" | "skillRows" | "skillCode"
1264
- >;
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;
1265
1759
 
1266
1760
  const SKILLS_OPTIONS: OptionSpec = {
1267
1761
  search: { type: "string" },
1762
+ path: { type: "string" },
1268
1763
  limit: { type: "string" },
1269
1764
  cursor: { type: "string" },
1270
1765
  rows: { type: "boolean" },
1271
1766
  code: { type: "boolean" },
1272
1767
  heading: { type: "string" },
1768
+ format: { type: "string" },
1769
+ grep: { type: "string" },
1273
1770
  out: { type: "string" },
1274
1771
  };
1275
1772
 
1773
+ /**
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.
1778
+ */
1779
+ function refusedRead(
1780
+ io: CliIo,
1781
+ session: Session,
1782
+ owner: PackOwner,
1783
+ answered: unknown,
1784
+ words: string,
1785
+ ): CliExit {
1786
+ if (session.json) {
1787
+ io.stdout(`${JSON.stringify(answered, null, 2)}\n`);
1788
+ }
1789
+ return failed(owner === "organization" ? `${ORGANIZATION_PACK_LINE}\n${words}` : words);
1790
+ }
1791
+
1792
+ /** A whole number a flag carries, within its bounds; nothing when it is not given. */
1793
+ function countOf(
1794
+ given: string | undefined,
1795
+ name: string,
1796
+ bounds: { readonly least: number; readonly most?: number },
1797
+ ): number | undefined {
1798
+ if (given === undefined) {
1799
+ return undefined;
1800
+ }
1801
+ const count = /^\d{1,9}$/.test(given) ? Number(given) : Number.NaN;
1802
+ if (
1803
+ Number.isNaN(count) ||
1804
+ count < bounds.least ||
1805
+ (bounds.most !== undefined && count > bounds.most)
1806
+ ) {
1807
+ throw misuse(
1808
+ `--${name} takes an integer ${bounds.most === undefined ? `from ${bounds.least}` : `between ${bounds.least} and ${bounds.most}`}: ${given}`,
1809
+ );
1810
+ }
1811
+ return count;
1812
+ }
1813
+
1814
+ /**
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.
1817
+ */
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
+
1276
1890
  /**
1277
1891
  * The tables, or the code blocks, of a document or of every document under a folder, as data
1278
- * (ADR-0100): every page the console answers, joined, and printed as one CSV or as the blocks
1279
- * as written, or written to a file with `--out`. What a program takes is never a refusal: a
1280
- * read the pack refused fails with why, and so does one that did not reach its end.
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.
1281
1895
  */
1282
1896
  async function readData(
1283
1897
  io: CliIo,
1284
1898
  session: Session,
1285
- reader: PackReader,
1899
+ pack: ConsolePack,
1286
1900
  asked: {
1287
- readonly what: "rows" | "code";
1288
- readonly path: string | undefined;
1289
- readonly heading: string | undefined;
1901
+ readonly read: Extract<PackRead, { readonly read: "rows" | "code" }>;
1290
1902
  readonly out: string | undefined;
1903
+ readonly owner: PackOwner;
1904
+ readonly words: ToolWords;
1291
1905
  },
1292
1906
  ): Promise<number> {
1293
- const where = asked.path ?? "the pack";
1294
- /** The answer written to a file, or printed: what was read in a line when a file was written. */
1295
- const give = async (
1296
- body: unknown,
1297
- words: string,
1298
- summary: string,
1299
- name: string,
1300
- ): Promise<number> => {
1301
- const printed = session.json ? `${JSON.stringify(body, null, 2)}\n` : words;
1302
- if (asked.out === undefined) {
1303
- io.stdout(printed);
1304
- return EXIT.ok;
1305
- }
1306
- let saved: string;
1307
- try {
1308
- saved = await io.writeBytes(asked.out, new TextEncoder().encode(printed), name);
1309
- } catch {
1310
- throw failed(`The file could not be written at ${asked.out}.`);
1311
- }
1312
- answer(io, session, { path: saved, summary }, () => `Saved ${summary} at ${saved}`);
1313
- return EXIT.ok;
1314
- };
1315
- if (asked.what === "rows") {
1316
- const pages: RestSkillRows[] = [];
1317
- let next: string | undefined;
1318
- for (let n = 0; n < MAX_SKILL_PAGES; n += 1) {
1319
- const page = await reader.skillRows({
1320
- path: asked.path,
1321
- heading: asked.heading,
1322
- cursor: next,
1323
- limit: DATA_PAGE_ROWS,
1324
- });
1325
- const refusal = dataRefusal("tables", page);
1326
- if (refusal !== undefined) {
1327
- throw failed(refusal);
1328
- }
1329
- pages.push(page);
1330
- next = page.read?.status === "ready" ? (page.read.nextCursor ?? undefined) : undefined;
1331
- if (next === undefined) {
1332
- break;
1333
- }
1334
- }
1335
- const whole = joinRows(pages);
1336
- const last = pages[pages.length - 1];
1337
- if (whole === undefined || last === undefined) {
1338
- throw failed("The tables could not be read.");
1339
- }
1340
- if (next !== undefined) {
1341
- throw failed(
1342
- `The tables under ${where} are more than the command reads at once (${describeRows(whole)} so far): name a folder or a file under it.`,
1343
- );
1344
- }
1345
- if (whole.tables.length === 0 && !session.json) {
1346
- io.stdout(
1347
- `No tables in ${where}${asked.heading === undefined ? "" : " under that heading"}.\n`,
1348
- );
1349
- return EXIT.ok;
1350
- }
1351
- return give({ ...last, read: whole }, csvOfRows(whole), describeRows(whole), "rows.csv");
1352
- }
1353
- const pages: RestSkillCode[] = [];
1354
- let next: string | undefined;
1355
- for (let n = 0; n < MAX_SKILL_PAGES; n += 1) {
1356
- const page = await reader.skillCode({
1357
- path: asked.path,
1358
- heading: asked.heading,
1359
- cursor: next,
1360
- limit: DATA_PAGE_BLOCKS,
1361
- });
1362
- const refusal = dataRefusal("code blocks", page);
1363
- if (refusal !== undefined) {
1364
- throw failed(refusal);
1365
- }
1366
- pages.push(page);
1367
- next = page.read?.status === "ready" ? (page.read.nextCursor ?? undefined) : undefined;
1368
- if (next === undefined) {
1369
- break;
1370
- }
1371
- }
1372
- const whole = joinCode(pages);
1373
- const last = pages[pages.length - 1];
1374
- if (whole === undefined || last === undefined) {
1375
- throw failed("The code blocks could not be read.");
1376
- }
1377
- if (next !== undefined) {
1378
- throw failed(
1379
- `The code blocks under ${where} are more than the command reads at once (${describeCode(whole)} so far): name a folder or a file under it.`,
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`,
1380
1916
  );
1381
1917
  }
1382
- if (whole.blocks.length === 0 && !session.json) {
1383
- io.stdout(
1384
- `No code blocks in ${where}${asked.heading === undefined ? "" : " under that heading"}.\n`,
1385
- );
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);
1386
1924
  return EXIT.ok;
1387
1925
  }
1388
- return give({ ...last, read: whole }, textOfCode(whole), describeCode(whole), "code.txt");
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;
1389
1936
  }
1390
1937
 
1391
1938
  const SKILL_OPTIONS: OptionSpec = {
1392
1939
  file: { type: "string" },
1393
1940
  offset: { type: "string" },
1394
1941
  limit: { type: "string" },
1942
+ cursor: { type: "string" },
1395
1943
  };
1396
1944
 
1397
1945
  /** The line `console skills` ends with: where the plugins' own skills are. */
@@ -1399,8 +1947,10 @@ const PLUGIN_SKILLS_LINE =
1399
1947
  "The plugins of this console have skills of their own: console plugins lists the plugins, console plugin <key> skills the skills of one.";
1400
1948
 
1401
1949
  /**
1402
- * The pack as the words say: whole, a folder of it, a file's outline, or what words find; for
1403
- * the project's pack as `console skills`, and for a plugin's as `console plugin <key> skills`.
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).
1404
1954
  */
1405
1955
  async function readSkills(
1406
1956
  io: CliIo,
@@ -1415,26 +1965,42 @@ async function readSkills(
1415
1965
  readonly own?: string | undefined;
1416
1966
  /** A line after the listing whole. */
1417
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;
1418
1970
  },
1419
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.`;
1420
1981
  if (positionals.length > 1) {
1421
1982
  throw misuse(`Say one folder: ${extras.command} [<folder>] [--search <words>]`);
1422
1983
  }
1423
1984
  // The root of the pack is the mounted folder, which the deployment reads as no path at all.
1424
1985
  const given = positionals[0];
1425
- const folder = given === undefined || given === "/" || given === "." ? undefined : given;
1426
1986
  const words = text(values, "search");
1987
+ const within = text(values, "path");
1427
1988
  const limit = text(values, "limit");
1428
1989
  const cursor = text(values, "cursor");
1429
1990
  const rows = on(values, "rows");
1430
1991
  const code = on(values, "code");
1431
1992
  const heading = text(values, "heading");
1432
1993
  const out = text(values, "out");
1994
+ const format = text(values, "format");
1995
+ const grep = text(values, "grep");
1433
1996
  const dataUsage = `${extras.command} --rows|--code [<folder|file>] [--heading <words>] [--out <path>]`;
1434
1997
  if (rows && code) {
1435
1998
  throw misuse(`Say one: --rows for the tables, or --code for the code blocks: ${dataUsage}`);
1436
1999
  }
1437
- if ((rows || code) && (words !== undefined || limit !== undefined || cursor !== undefined)) {
2000
+ if (
2001
+ (rows || code) &&
2002
+ (words !== undefined || within !== undefined || limit !== undefined || cursor !== undefined)
2003
+ ) {
1438
2004
  throw misuse(
1439
2005
  `--rows and --code read a folder or a file whole, and go without --search: ${dataUsage}`,
1440
2006
  );
@@ -1442,32 +2008,77 @@ async function readSkills(
1442
2008
  if (!rows && !code && (heading !== undefined || out !== undefined)) {
1443
2009
  throw misuse(`--heading and --out go with --rows or --code: ${dataUsage}`);
1444
2010
  }
1445
- if (words === undefined && (limit !== undefined || cursor !== undefined)) {
2011
+ if (format !== undefined && !rows) {
1446
2012
  throw misuse(
1447
- `--limit and --cursor go with --search: ${extras.command} --search <words> [--limit <n>] [--cursor <cursor>]`,
2013
+ `--format goes with --rows: ${extras.command} --rows [<folder|file>] [--format csv|json]`,
1448
2014
  );
1449
2015
  }
1450
- const atMost = limit === undefined ? undefined : Number(limit);
1451
- if (
1452
- atMost !== undefined &&
1453
- (!Number.isInteger(atMost) || atMost < 1 || atMost > MAX_FIND_LIMIT)
1454
- ) {
1455
- throw misuse(`Not a number of results, 1 to ${MAX_FIND_LIMIT}: ${limit}`);
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
+ );
1456
2039
  }
1457
- // As data: the read answers for itself how the pack stands, and fails where it does not.
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.
1458
2050
  if (rows || code) {
1459
- return readData(io, session, reader, {
1460
- what: rows ? "rows" : "code",
1461
- path: folder,
1462
- heading,
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 },
1463
2058
  out,
2059
+ owner,
2060
+ words: toolWords,
1464
2061
  });
1465
2062
  }
1466
- const { listing, summary } = await packOf(reader);
1467
- // The pack as it stands; or why it does not answer, which a folder or a search would meet too.
1468
- if (summary === undefined || (words === undefined && given === undefined)) {
1469
- answer(io, session, listing, () =>
1470
- [formatSkills(listing, extras.own), extras.afterwards]
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]
1471
2082
  .filter((part): part is string => part !== undefined)
1472
2083
  .join("\n"),
1473
2084
  );
@@ -1475,75 +2086,99 @@ async function readSkills(
1475
2086
  }
1476
2087
  if (words !== undefined) {
1477
2088
  // One page of what the words find; more is said, and asked for with --cursor.
1478
- const found = await reader.skillFind(words, { path: folder, limit: atMost, cursor });
1479
- answer(io, session, found, () => formatSkillFind(found, summary));
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}`);
1480
2098
  return EXIT.ok;
1481
2099
  }
1482
- // The folder whole: its pages until the end, as the pack lists them.
1483
- const pages: RestSkillBrowse[] = [];
1484
- let next: string | undefined;
1485
- let last: RestSkillBrowse | undefined;
1486
- for (let n = 0; n < MAX_SKILL_PAGES; n += 1) {
1487
- last = await reader.skillBrowse({ path: folder, cursor: next });
1488
- if (last.read?.status !== "ready") {
1489
- break;
1490
- }
1491
- pages.push(last);
1492
- next = last.read.nextCursor ?? undefined;
1493
- if (next === undefined) {
1494
- break;
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
+ );
1495
2140
  }
2141
+ throw error;
1496
2142
  }
1497
- if (last === undefined) {
1498
- throw failed("The folder could not be read.");
1499
- }
1500
- const browsed = last;
1501
- const whole = joinFolder(pages, summary);
1502
- answer(io, session, { ...browsed, read: whole === undefined ? null : bodyOfFolder(whole) }, () =>
1503
- formatSkillBrowse(browsed, whole, extras.command),
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(),
1504
2158
  );
1505
- return EXIT.ok;
1506
2159
  }
1507
2160
 
1508
2161
  const skills: Command = async (args, io) => {
1509
2162
  const { values, positionals } = parse(args, SKILLS_OPTIONS);
1510
2163
  const session = await open(io, values);
1511
- const project = await session.project();
1512
- return readSkills(io, session, project, values, positionals, {
1513
- command: "console skills",
1514
- own: io.skillsDir,
1515
- afterwards: PLUGIN_SKILLS_LINE,
1516
- });
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
+ );
1517
2173
  };
1518
2174
 
1519
- /** The most characters one read of a file asks for: what the console's API allows on one page. */
1520
- const MAX_FILE_LIMIT = 100_000;
1521
-
1522
- /** A count given as a flag, within its bounds, or nothing; anything else is not understood. */
1523
- function countOf(
1524
- given: string | undefined,
1525
- name: string,
1526
- bounds: { readonly least: number; readonly most?: number },
1527
- ): number | undefined {
1528
- if (given === undefined) {
1529
- return undefined;
1530
- }
1531
- const count = Number(given);
1532
- if (
1533
- !Number.isInteger(count) ||
1534
- count < bounds.least ||
1535
- (bounds.most !== undefined && count > bounds.most)
1536
- ) {
1537
- const range =
1538
- bounds.most === undefined ? `${bounds.least} or more` : `${bounds.least} to ${bounds.most}`;
1539
- throw misuse(`Not a number for --${name}, ${range}: ${given}`);
1540
- }
1541
- return count;
1542
- }
1543
-
1544
2175
  /**
1545
- * One skill of the pack whole, a file of it, or one page of a file; for the project's pack as
1546
- * `console skill`, and for a plugin's as `console plugin <key> skill`.
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.
1547
2182
  */
1548
2183
  async function readSkill(
1549
2184
  io: CliIo,
@@ -1552,8 +2187,14 @@ async function readSkill(
1552
2187
  values: Values,
1553
2188
  positionals: readonly string[],
1554
2189
  command: string,
2190
+ owner: PackOwner = "project",
2191
+ again: readonly string[] = [],
1555
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);
1556
2196
  const file = text(values, "file");
2197
+ const cursor = text(values, "cursor");
1557
2198
  // A file is read by its own path from the repository's root; a skill's path beside it would be
1558
2199
  // ignored, which reads as if it mattered, so the two together are not understood.
1559
2200
  if (file !== undefined && positionals.length > 0) {
@@ -1561,7 +2202,7 @@ async function readSkill(
1561
2202
  `Say one: ${command} <path of its SKILL.md> for a skill, or ${command} --file <path> for a file of the pack.`,
1562
2203
  );
1563
2204
  }
1564
- // 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.
1565
2206
  if (
1566
2207
  file === undefined &&
1567
2208
  (text(values, "offset") !== undefined || text(values, "limit") !== undefined)
@@ -1570,90 +2211,92 @@ async function readSkill(
1570
2211
  `--offset and --limit go with --file: ${command} --file <path> [--offset <n>] [--limit <n>]`,
1571
2212
  );
1572
2213
  }
1573
- const offset = countOf(text(values, "offset"), "offset", { least: 0 });
1574
- const limit = countOf(text(values, "limit"), "limit", { least: 1, most: MAX_FILE_LIMIT });
1575
- const { listing, summary } = await packOf(reader);
1576
- if (summary === undefined) {
1577
- answer(io, session, listing, () => formatSkills(listing, io.skillsDir));
1578
- 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
+ );
1579
2219
  }
1580
- if (file !== undefined && (offset !== undefined || limit !== undefined)) {
1581
- // One page as asked, the section a search or an outline named; the result says where the
1582
- // file continues, and asks for nothing.
1583
- const page = await reader.skillFile(file, { offset, limit });
1584
- const section = page.read === null ? undefined : joinFile([page], summary, limit);
1585
- answer(io, session, { ...page, read: section === undefined ? null : bodyOfFile(section) }, () =>
1586
- 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),
1587
2231
  );
1588
- return EXIT.ok;
1589
2232
  }
1590
2233
  if (file !== undefined) {
1591
- // The file whole, page after page, as the console reads it from the pack.
1592
- const pages: RestSkillFile[] = [];
1593
- let offset: number | undefined;
1594
- let last: RestSkillFile | undefined;
1595
- for (let n = 0; n < MAX_SKILL_PAGES; n += 1) {
1596
- last = await reader.skillFile(file, offset === undefined ? {} : { offset });
1597
- if (last.read === null) {
1598
- break;
1599
- }
1600
- pages.push(last);
1601
- if (last.read.kind !== "file" || last.read.nextOffset === null) {
1602
- break;
1603
- }
1604
- offset = last.read.nextOffset;
1605
- }
1606
- if (last === undefined) {
1607
- throw failed("The file could not be read.");
1608
- }
1609
- const fileRead = last;
1610
- const whole = joinFile(pages, summary);
1611
- answer(io, session, { ...fileRead, read: whole === undefined ? null : bodyOfFile(whole) }, () =>
1612
- 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 },
1613
2243
  );
2244
+ say(jsonOfRead(session, pack, page), () => page.text);
1614
2245
  return EXIT.ok;
1615
2246
  }
1616
- const wanted = skillPathIn(
1617
- theOne(
1618
- positionals,
1619
- `Say which skill: ${command} <path of its SKILL.md>, or ${command} --file <path> for a file of the pack`,
1620
- ),
1621
- 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`,
1622
2250
  );
2251
+ const wanted = skillPathIn(given, listing.address);
1623
2252
  if ("error" in wanted) {
1624
2253
  throw misuse(wanted.error);
1625
2254
  }
1626
- // The skill whole: its pages until complete, the rules first, as load_skill lays them out.
1627
- const pages: RestSkillLoad[] = [];
1628
- let cursor: string | undefined;
1629
- let last: RestSkillLoad | undefined;
1630
- for (let n = 0; n < MAX_SKILL_PAGES; n += 1) {
1631
- last = await reader.skill(wanted.path, cursor);
1632
- if (last.read?.status !== "ready") {
1633
- break;
1634
- }
1635
- pages.push(last);
1636
- cursor = last.read.skill.nextCursor ?? undefined;
1637
- if (last.read.skill.complete === true || cursor === undefined) {
1638
- break;
1639
- }
1640
- }
1641
- if (last === undefined) {
1642
- throw failed("The skill could not be read.");
1643
- }
1644
- const loaded = last;
1645
- const whole = joinSkill(pages, summary);
1646
- answer(io, session, { ...loaded, read: whole === undefined ? null : bodyOfSkill(whole) }, () =>
1647
- 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,
1648
2282
  );
1649
2283
  return EXIT.ok;
1650
2284
  }
1651
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
+
1652
2293
  const skill: Command = async (args, io) => {
1653
2294
  const { values, positionals } = parse(args, SKILL_OPTIONS);
1654
2295
  const session = await open(io, values);
1655
- const project = await session.project();
1656
- 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
+ );
1657
2300
  };
1658
2301
 
1659
2302
  // ---- The plugins (docs/specs/plugins.md, "The command") ----
@@ -1729,7 +2372,7 @@ function splitWords(
1729
2372
  }
1730
2373
 
1731
2374
  const PLUGIN_USAGE =
1732
- "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.";
1733
2376
 
1734
2377
  const plugin: Command = async (args, io) => {
1735
2378
  const { values, words } = splitWords(args, PLUGIN_GLOBAL_FLAGS);
@@ -1765,6 +2408,8 @@ const plugin: Command = async (args, io) => {
1765
2408
  }
1766
2409
  case "records":
1767
2410
  return pluginRecords(io, session, client, rest, text(values, "project"));
2411
+ case "events":
2412
+ return pluginEvents(io, session, client, rest);
1768
2413
  case "skills": {
1769
2414
  const parsed = parse(rest, SKILLS_OPTIONS);
1770
2415
  return readSkills(io, session, client, parsed.values, parsed.positionals, {
@@ -1780,6 +2425,8 @@ const plugin: Command = async (args, io) => {
1780
2425
  parsed.values,
1781
2426
  parsed.positionals,
1782
2427
  `console plugin ${key} skill`,
2428
+ "project",
2429
+ whereGiven(values),
1783
2430
  );
1784
2431
  }
1785
2432
  case "enable":
@@ -1932,6 +2579,53 @@ function whereValueOf(word: string): unknown {
1932
2579
  }
1933
2580
 
1934
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
+
1935
2629
  async function pluginRecords(
1936
2630
  io: CliIo,
1937
2631
  session: Session,
@@ -2249,31 +2943,38 @@ async function pluginSecret(
2249
2943
  client: PluginClient,
2250
2944
  rest: readonly string[],
2251
2945
  ): Promise<number> {
2252
- const { values, positionals } = parse(rest, { remove: { type: "boolean" } });
2946
+ const { values, positionals } = parse(rest, {
2947
+ remove: { type: "boolean" },
2948
+ key: { type: "string" },
2949
+ });
2253
2950
  const name = theOne(
2254
2951
  positionals,
2255
- `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.`,
2256
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 };
2257
2958
  if (on(values, "remove")) {
2258
- await client.removeSecret(name);
2259
- 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}.`);
2260
2961
  return EXIT.ok;
2261
2962
  }
2262
2963
  const value = await secretGiven(
2263
2964
  io,
2264
- `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): `,
2265
2966
  );
2266
2967
  if (value.length === 0) {
2267
2968
  throw misuse(
2268
- `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.`,
2269
2970
  );
2270
2971
  }
2271
- await client.setSecret(name, value);
2972
+ await client.setSecret(name, value, key);
2272
2973
  answer(
2273
2974
  io,
2274
2975
  session,
2275
- { name, set: true },
2276
- () => `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.`,
2277
2978
  );
2278
2979
  return EXIT.ok;
2279
2980
  }
@@ -2345,8 +3046,9 @@ function versionOf(given: string | undefined): number | undefined {
2345
3046
  return version;
2346
3047
  }
2347
3048
 
2348
- // The rules of the board (ADR-0023): read before a task is taken, written by an owner for the
2349
- // 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.
2350
3052
  const rules: Command = async (args, io) => {
2351
3053
  const [verb, ...rest] = args;
2352
3054
  if (verb === "write") {
@@ -2364,7 +3066,7 @@ const rules: Command = async (args, io) => {
2364
3066
  const body = none ? undefined : await bodyOf(io, values, given);
2365
3067
  if (!none && body === undefined) {
2366
3068
  throw misuse(
2367
- "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.",
2368
3070
  );
2369
3071
  }
2370
3072
  const baseVersion = versionOf(text(values, "base"));
@@ -2376,18 +3078,28 @@ const rules: Command = async (args, io) => {
2376
3078
  io,
2377
3079
  session,
2378
3080
  put,
2379
- () => "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.",
2380
3082
  );
2381
3083
  return EXIT.ok;
2382
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
+ }
2383
3095
  const written = await session.client.writeRules({
2384
3096
  body: body ?? "",
2385
3097
  ...(baseVersion === undefined ? {} : { baseVersion }),
2386
3098
  });
2387
3099
  answer(io, session, written, () =>
2388
3100
  written.page === null
2389
- ? "Nothing written: these are the console's own rules as they stand, and they hold already."
2390
- : `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}.`,
2391
3103
  );
2392
3104
  return EXIT.ok;
2393
3105
  }
@@ -2395,12 +3107,22 @@ const rules: Command = async (args, io) => {
2395
3107
  if (none) {
2396
3108
  try {
2397
3109
  const put = await project.archiveDocument(RULES_PATH);
2398
- 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
+ );
2399
3116
  } catch (error) {
2400
3117
  if (!(error instanceof ApiError) || error.code !== "document.not_found") {
2401
3118
  throw error;
2402
3119
  }
2403
- 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
+ );
2404
3126
  }
2405
3127
  return EXIT.ok;
2406
3128
  }
@@ -2409,14 +3131,19 @@ const rules: Command = async (args, io) => {
2409
3131
  body: body ?? "",
2410
3132
  ...(baseVersion === undefined ? {} : { baseVersion }),
2411
3133
  });
2412
- 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
+ );
2413
3140
  return EXIT.ok;
2414
3141
  }
2415
3142
  const { values } = parse(args, {}, false);
2416
3143
  const session = await open(io, values);
2417
3144
  const key = await session.projectKey();
2418
3145
  const [found, me] = await Promise.all([
2419
- key === undefined ? session.client.rules() : session.client.project(key).rules(),
3146
+ key === undefined ? session.client.rules() : (await session.project()).rules(),
2420
3147
  session.client.me(),
2421
3148
  ]);
2422
3149
  const read =
@@ -2427,19 +3154,27 @@ const rules: Command = async (args, io) => {
2427
3154
  ...(found.plugins === undefined ? {} : { plugins: found.plugins }),
2428
3155
  }
2429
3156
  : forPerson(found, readingLanguage(me));
2430
- 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
+ );
2431
3161
  return EXIT.ok;
2432
3162
  };
2433
3163
 
2434
3164
  /**
2435
3165
  * The rules as they read for the person whose token the command holds: `{language}` filled
2436
- * 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.
2437
3168
  */
2438
- function forPerson<T extends { readonly body: string | null }>(
2439
- half: T,
2440
- language: string | null,
2441
- ): T {
2442
- 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
+ };
2443
3178
  }
2444
3179
 
2445
3180
  /** The flags that set a task's fields, shared by writing one and changing one. */
@@ -2520,8 +3255,28 @@ const newTask: Command = async (args, io) => {
2520
3255
  ...TASK_FIELDS,
2521
3256
  body: { type: "string" },
2522
3257
  file: { type: "string" },
3258
+ take: { type: "boolean" },
3259
+ agent: { type: "string" },
3260
+ rules: { type: "string" },
2523
3261
  });
2524
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
+ }
2525
3280
  const body = await bodyOf(io, values, text(values, "body"));
2526
3281
  const session = await open(io, values);
2527
3282
  const project = await session.project();
@@ -2529,14 +3284,46 @@ const newTask: Command = async (args, io) => {
2529
3284
  const made = await project.createTask({
2530
3285
  title,
2531
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 } : {}),
2532
3289
  ...fields,
2533
3290
  });
2534
- answer(
2535
- io,
2536
- session,
2537
- made,
2538
- () => `Task #${made.number} written: ${made.title}\ntask id: ${made.id}`,
2539
- );
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);
2540
3327
  return EXIT.ok;
2541
3328
  };
2542
3329
 
@@ -2567,7 +3354,8 @@ const editTask: Command = async (args, io) => {
2567
3354
  }
2568
3355
  const found = await project.task(ref);
2569
3356
  const changed = await project.updateTask(found.id, patch);
2570
- 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));
2571
3359
  return EXIT.ok;
2572
3360
  };
2573
3361
 
@@ -2630,14 +3418,17 @@ const task: Command = async (args, io) => {
2630
3418
  const found = await project.task(ref);
2631
3419
  const [decisions, runs, comments] = await Promise.all([
2632
3420
  project.decisions({ task: found.id }),
2633
- 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 }),
2634
3424
  project.comments(found.id),
2635
3425
  ]);
3426
+ const page = await taskPage(session, found.number);
2636
3427
  answer(
2637
3428
  io,
2638
3429
  session,
2639
3430
  { task: found, decisions: decisions.items, runs: runs.items, comments: comments.items },
2640
- () => formatTask(found, decisions.items, runs.items, comments.items),
3431
+ () => formatTask(found, decisions.items, runs.items, comments.items, page),
2641
3432
  );
2642
3433
  return EXIT.ok;
2643
3434
  };
@@ -2740,17 +3531,40 @@ const file: Command = async (args, io) => {
2740
3531
  return EXIT.ok;
2741
3532
  };
2742
3533
 
2743
- const take: Command = async (args, io) => {
2744
- const { values, positionals } = parse(args, { agent: { type: "string" } });
2745
- const ref = theOne(positionals, "Say which task: console take <number|id>");
2746
- const session = await open(io, values);
2747
- const project = await session.project();
2748
- 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> {
2749
3547
  const agent = text(values, "agent");
2750
- const run = await project.startRun({
3548
+ return project.startRun({
2751
3549
  taskId: found.id,
2752
3550
  ...(agent === undefined ? {} : { agent }),
2753
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> {
2754
3568
  // The rules come with the run, as they read for the person: everything from here acts
2755
3569
  // within them (ADR-0023); the task is read again, as it stands now that it is taken.
2756
3570
  const [ruling, me, taken, comments, openRuns] = await Promise.all([
@@ -2758,7 +3572,7 @@ const take: Command = async (args, io) => {
2758
3572
  session.client.me(),
2759
3573
  project.task(ref),
2760
3574
  project.comments(found.id),
2761
- project.runs({ open: true, mine: true }),
3575
+ project.runBriefs({ open: true, mine: true }),
2762
3576
  ]);
2763
3577
  // Taking a task with a run open on it ends that run (ADR-0020): said when it happened.
2764
3578
  const tookOver =
@@ -2777,21 +3591,51 @@ const take: Command = async (args, io) => {
2777
3591
  project: forPerson(ruling.project, readingLanguage(me)),
2778
3592
  ...(ruling.plugins === undefined ? {} : { plugins: ruling.plugins }),
2779
3593
  };
2780
- answer(io, session, { run, task: taken, comments: comments.items, rules }, () =>
2781
- [
2782
- `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}`,
2783
- // The ids on a line of their own, each named: a run's and a task's begin alike, and a
2784
- // task has a number for people as well.
2785
- `run id: ${run.id} task id: ${found.id} (task #${found.number})`,
2786
- "",
2787
- formatTask(taken, undefined, undefined, comments.items),
2788
- "",
2789
- formatRules(rules, readingLanguage(me)),
2790
- "",
2791
- 'Say how it goes: console report "<what you found or did>". Hand in what you make: console hand-in <https url | file path>.',
2792
- '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>".',
2793
- ].join("\n"),
2794
- );
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);
2795
3639
  return EXIT.ok;
2796
3640
  };
2797
3641
 
@@ -2811,7 +3655,7 @@ const report: Command = async (args, io) => {
2811
3655
  }
2812
3656
  const session = await open(io, values);
2813
3657
  const project = await session.project();
2814
- const runId = await currentRun(project, values);
3658
+ const runId = await currentRun(session, project, values);
2815
3659
  const run = await project.report(runId, { body });
2816
3660
  answer(
2817
3661
  io,
@@ -2857,7 +3701,7 @@ const handIn: Command = async (args, io) => {
2857
3701
  const label = text(values, "label");
2858
3702
  const session = await open(io, values);
2859
3703
  const project = await session.project();
2860
- const runId = await currentRun(project, values);
3704
+ const runId = await currentRun(session, project, values);
2861
3705
  // A URL is handed in as a link, and the console says whether it takes it; anything else
2862
3706
  // names a file on this machine.
2863
3707
  if (/^[a-z][a-z0-9+.-]*:\/\//i.test(what)) {
@@ -2928,7 +3772,7 @@ const ask: Command = async (args, io) => {
2928
3772
  const files = await attachmentsOf(io, texts(values, "attach"));
2929
3773
  const session = await open(io, values);
2930
3774
  const project = await session.project();
2931
- const runId = await currentRun(project, values);
3775
+ const runId = await currentRun(session, project, values);
2932
3776
  // Whom the decision is for (ADR-0042, ADR-0057): the person the agent works for, unless --to
2933
3777
  // names others of the project, each once; several, and any of them may answer.
2934
3778
  const deciderIds: string[] = [];
@@ -2954,13 +3798,28 @@ const ask: Command = async (args, io) => {
2954
3798
  );
2955
3799
  const withFiles =
2956
3800
  files.length === 0 ? "" : `, with ${files.length} file${files.length === 1 ? "" : "s"}`;
2957
- // 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.
2958
3803
  io.stdout(
2959
3804
  session.json
2960
3805
  ? `${JSON.stringify(raised, null, 2)}\n`
2961
- : `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`,
2962
3807
  );
2963
- 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);
2964
3823
  };
2965
3824
 
2966
3825
  /**
@@ -2992,7 +3851,8 @@ const answering: Command = async (args, io) => {
2992
3851
  ...(own === undefined ? { option } : { own }),
2993
3852
  ...(note === undefined ? {} : { note }),
2994
3853
  });
2995
- 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 }));
2996
3856
  return EXIT.ok;
2997
3857
  };
2998
3858
 
@@ -3046,6 +3906,27 @@ async function reachDecision(
3046
3906
  }
3047
3907
  }
3048
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
+
3049
3930
  /** Writes an answer on a decision as the command reaches it (ADR-0068): in the project, else wherever it is. */
3050
3931
  async function answerReached(
3051
3932
  session: Session,
@@ -3101,7 +3982,7 @@ const decision: Command = async (args, io) => {
3101
3982
  if (tos.length > 0) {
3102
3983
  // Whom a decision that waits is for, said anew (ADR-0096): the people named take the place
3103
3984
  // of those it was for, each once in the order named.
3104
- const project = await session.project();
3985
+ const project = await projectOfDecision(session, id);
3105
3986
  const deciderIds: string[] = [];
3106
3987
  for (const to of tos) {
3107
3988
  const named = await personIdOf(session, to);
@@ -3110,22 +3991,34 @@ const decision: Command = async (args, io) => {
3110
3991
  }
3111
3992
  }
3112
3993
  const addressed = await project.addressDecision(id, deciderIds);
3113
- answer(io, session, addressed, () => formatDecision(addressed));
3994
+ const page = await decisionPage(session, addressed.id);
3995
+ answer(io, session, addressed, () => formatDecision(addressed, { page }));
3114
3996
  return EXIT.ok;
3115
3997
  }
3116
3998
  if (outcome !== undefined) {
3117
3999
  // What followed the decision: the record grows, and is printed as it stands.
3118
- const project = await session.project();
4000
+ const project = await projectOfDecision(session, id);
3119
4001
  const grown = await project.updateDecision(id, { outcome });
3120
- answer(io, session, grown, () => formatDecision(grown));
4002
+ const page = await decisionPage(session, grown.id);
4003
+ answer(io, session, grown, () => formatDecision(grown, { page }));
3121
4004
  return EXIT.ok;
3122
4005
  }
3123
4006
  const { decision: found, waiter, atItsAddress } = await reachDecision(session, id);
3124
4007
  if (seconds === 0) {
3125
- 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 }));
3126
4010
  return EXIT.ok;
3127
4011
  }
3128
- 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);
3129
4022
  };
3130
4023
 
3131
4024
  const docs: Command = async (args, io) => {
@@ -3139,8 +4032,10 @@ const docs: Command = async (args, io) => {
3139
4032
  const search = text(values, "search");
3140
4033
  const session = await open(io, values);
3141
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(/\/+$/, "");
3142
4037
  const found = await project.documents({
3143
- ...(positionals[0] === undefined ? {} : { folder: positionals[0] }),
4038
+ ...(folder === undefined || folder === "" ? {} : { folder }),
3144
4039
  ...(search === undefined ? {} : { q: search }),
3145
4040
  ...(on(values, "archived") ? { archived: true } : {}),
3146
4041
  });
@@ -3219,12 +4114,15 @@ const write: Command = async (args, io) => {
3219
4114
  body,
3220
4115
  ...(baseVersion === undefined ? {} : { baseVersion }),
3221
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)}`;
3222
4120
  answer(
3223
4121
  io,
3224
4122
  session,
3225
4123
  written,
3226
4124
  () =>
3227
- `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)}`}`,
3228
4126
  );
3229
4127
  return EXIT.ok;
3230
4128
  };
@@ -3402,7 +4300,9 @@ const goal: Command = async (args, io) => {
3402
4300
  const session = await open(io, values);
3403
4301
  const project = await session.project();
3404
4302
  const found = await project.goal(id);
3405
- 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 });
3406
4306
  answer(io, session, { goal: found, tasks: towards.items }, () =>
3407
4307
  formatGoal(found, towards.items),
3408
4308
  );
@@ -3450,6 +4350,37 @@ const decisions: Command = async (args, io) => {
3450
4350
  return EXIT.ok;
3451
4351
  };
3452
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
+
3453
4384
  const ending =
3454
4385
  (status: "finished" | "failed"): Command =>
3455
4386
  async (args, io) => {
@@ -3461,16 +4392,12 @@ const ending =
3461
4392
  const summary = await bodyOf(io, values, text(values, "summary"));
3462
4393
  const session = await open(io, values);
3463
4394
  const project = await session.project();
3464
- const runId = await currentRun(project, values);
4395
+ const runId = await currentRun(session, project, values);
3465
4396
  const run = await project.endRun(runId, {
3466
4397
  status,
3467
4398
  ...(summary === undefined ? {} : { summary }),
3468
4399
  });
3469
- answer(io, session, run, () =>
3470
- status === "finished"
3471
- ? `Run ${run.id} finished; the task is up for review.`
3472
- : `Run ${run.id} failed; the task stays as it is.`,
3473
- );
4400
+ await sayEnded(io, session, project, run, status);
3474
4401
  return EXIT.ok;
3475
4402
  };
3476
4403
 
@@ -3486,12 +4413,12 @@ const abandon: Command = async (args, io) => {
3486
4413
  const summary = await bodyOf(io, values, text(values, "summary"));
3487
4414
  const session = await open(io, values);
3488
4415
  const project = await session.project();
3489
- const runId = positionals[0] ?? (await currentRun(project, values));
4416
+ const runId = positionals[0] ?? (await currentRun(session, project, values));
3490
4417
  const run = await project.endRun(runId, {
3491
4418
  status: "abandoned",
3492
4419
  ...(summary === undefined ? {} : { summary }),
3493
4420
  });
3494
- answer(io, session, run, () => `Run ${run.id} abandoned; the task stays as it is.`);
4421
+ await sayEnded(io, session, project, run, "abandoned");
3495
4422
  return EXIT.ok;
3496
4423
  };
3497
4424
 
@@ -3511,20 +4438,49 @@ const runs: Command = async (args, io) => {
3511
4438
  const project = await session.project();
3512
4439
  const ref = text(values, "task");
3513
4440
  const taskId = ref === undefined ? undefined : (await project.task(ref)).id;
3514
- const found = await project.runs({
4441
+ const mine = on(values, "mine");
4442
+ const filter = {
3515
4443
  ...(taskId === undefined ? {} : { task: taskId }),
3516
4444
  ...(on(values, "open") ? { open: true } : {}),
3517
- ...(on(values, "mine") ? { mine: true } : {}),
4445
+ ...(mine ? { mine: true } : {}),
3518
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}`;
3519
4468
  });
3520
- answer(io, session, found, () =>
3521
- found.items.length === 0
3522
- ? "No runs."
3523
- : found.items.map(formatRunLine).join("\n") + formatMore(found.more, page.limit, page.offset),
3524
- );
3525
4469
  return EXIT.ok;
3526
4470
  };
3527
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
+
3528
4484
  const run: Command = async (args, io) => {
3529
4485
  const { values, positionals } = parse(args, {});
3530
4486
  const id = theOne(positionals, "Say which run: console run <id>");
@@ -3549,12 +4505,16 @@ function portOf(value: string | undefined): number {
3549
4505
 
3550
4506
  /**
3551
4507
  * A console of the person's own, served from this machine (ADR-0014): the build's pages here,
3552
- * and everything under /api/ carried to the console with the token, which the pages never see.
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.
3553
4510
  */
3554
4511
  const serve: Command = async (args, io) => {
3555
- const { values, positionals } = parse(args, { port: { type: "string" } });
4512
+ const { values, positionals } = parse(args, {
4513
+ port: { type: "string" },
4514
+ records: { type: "string" },
4515
+ });
3556
4516
  if (positionals.length > 1) {
3557
- throw misuse("Say at most one directory: console serve [<dir>] [--port <n>]");
4517
+ throw misuse("Say at most one directory: console serve [<dir>] [--port <n>] [--records <dir>]");
3558
4518
  }
3559
4519
  const [dir] = positionals;
3560
4520
  const port = portOf(text(values, "port"));
@@ -3581,6 +4541,20 @@ const serve: Command = async (args, io) => {
3581
4541
  throw error;
3582
4542
  }
3583
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
+ }
3584
4558
  const listening = await listen(
3585
4559
  (bound) =>
3586
4560
  createServeHandler({
@@ -3589,13 +4563,22 @@ const serve: Command = async (args, io) => {
3589
4563
  fetch: io.fetch,
3590
4564
  port: bound,
3591
4565
  web,
4566
+ records,
3592
4567
  }),
3593
4568
  port,
3594
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.`;
3595
4578
  io.stdout(
3596
4579
  web === undefined
3597
- ? `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`
3598
- : `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`,
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`,
3599
4582
  );
3600
4583
  await listening.closed;
3601
4584
  return EXIT.ok;
@@ -3917,8 +4900,13 @@ const agentNew = async (args: readonly string[], io: CliIo): Promise<number> =>
3917
4900
  formatAgentLine(made),
3918
4901
  made.person.invited === true
3919
4902
  ? host === "gh"
3920
- ? // A login at a git host goes to whoever registers it, and the console lets that one in.
3921
- `It is a member now, and work can be assigned to it. It signs in as ${made.person.login}: that account has to be the organization's own at the git host already, since until its first sign-in binds it here the console lets in whoever holds that login.`
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.`
3922
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.`
3923
4911
  : `${made.person.login} is an agent account from now on, with everything it did.`,
3924
4912
  ...(made.onboarding === null || made.onboarding === undefined
@@ -4010,7 +4998,22 @@ const agentSecrets = async (args: readonly string[], io: CliIo): Promise<number>
4010
4998
  const { values, positionals } = parse(args, {});
4011
4999
  const handle = handleOf(theOne(positionals, "Say whose: console agent secrets <handle>"));
4012
5000
  const session = await open(io, values);
4013
- const found = await session.client.agentSecrets(handle);
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
+ }
4014
5017
  answer(io, session, found, () =>
4015
5018
  found.items.length === 0
4016
5019
  ? `@${handle} keeps no secret yet.`
@@ -4505,8 +5508,12 @@ async function signInAsAccount(
4505
5508
  URL.canParse(begun.url) && new URL(begun.url).origin === url
4506
5509
  ? await machine.open(begun.url)
4507
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);
4508
5515
  io.stdout(
4509
- `${opened ? `The page is opened in this machine's browser: ${begun.url}` : `Open ${begun.url} in this machine's browser`}. Sign in there as ${login}, check that the page shows the code ${begun.code}, and say that it is you. On a machine without a screen, open the address in any browser that is signed in as the account.\nWaiting for that, until ${begun.expiresAt}.\n`,
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`,
4510
5517
  );
4511
5518
  let secret: string;
4512
5519
  for (;;) {
@@ -4679,6 +5686,216 @@ const agentSetup = async (args: readonly string[], io: CliIo): Promise<number> =
4679
5686
  return EXIT.ok;
4680
5687
  };
4681
5688
 
5689
+ const DESK_USAGE = "Say at most one directory: console desk [<directory>] [--web]";
5690
+
5691
+ /**
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.
5696
+ */
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, {});
5728
+ if (positionals.length > 1) {
5729
+ throw misuse("Say at most one directory: console desk check [<directory>]");
5730
+ }
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);
5786
+ }
5787
+ const session = await open(io, values);
5788
+ const me = await session.client.me();
5789
+ const person = me.person;
5790
+ if (person === null) {
5791
+ throw failed("The console does not know this token. Sign in again: console login");
5792
+ }
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);
5855
+ }
5856
+ }
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"),
5895
+ );
5896
+ return EXIT.ok;
5897
+ };
5898
+
4682
5899
  // One agent account by its handle; with --avatar, its picture written as a file (ADR-0084): the
4683
5900
  // parts are drawn here, by the package's own function, and the console sends no picture.
4684
5901
  const agent: Command = async (args, io) => {
@@ -5488,6 +6705,7 @@ const COMMANDS: Readonly<Record<string, Command>> = {
5488
6705
  whoami,
5489
6706
  serve,
5490
6707
  runner,
6708
+ desk,
5491
6709
  projects,
5492
6710
  use,
5493
6711
  work,
@@ -5542,7 +6760,7 @@ function help(io: CliIo, name: string | undefined): number {
5542
6760
  io.stdout(usage(io.version, io.skillsDir));
5543
6761
  return EXIT.ok;
5544
6762
  }
5545
- const found = helpFor(name);
6763
+ const found = helpFor(name, io.skillsDir);
5546
6764
  if (found === undefined) {
5547
6765
  throw misuse(`Not a command: ${name}. The commands: ${Object.keys(COMMAND_HELP).join(", ")}`);
5548
6766
  }
@@ -5788,6 +7006,10 @@ export async function runCli(argv: readonly string[], io: CliIo): Promise<number
5788
7006
  io.stderr(`${error.message}\n`);
5789
7007
  return error.exit;
5790
7008
  }
7009
+ if (error instanceof UnseenProject) {
7010
+ io.stderr(`${error.words}\n`);
7011
+ return EXIT.failed;
7012
+ }
5791
7013
  if (error instanceof ApiError) {
5792
7014
  io.stderr(`${error.code}: ${error.message}\n${hintFor(error, io, seen)}`);
5793
7015
  return error.code === "client.outdated" ||