@illuminis/comprism 0.1.8 → 2.4.0

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 (225) hide show
  1. package/out/{graph → build/machine/codemap}/read-python.js +2 -2
  2. package/out/{executor → build/machine/executor}/diagnostics.js +1 -1
  3. package/out/{executor → build/machine/executor}/hooks.js +1 -1
  4. package/out/{executor → build/machine/executor}/sandbox.js +1 -1
  5. package/out/build/machine/line/index.js +339 -0
  6. package/out/{commands/privacy.js → build/machine/runtime/home.js} +10 -19
  7. package/out/build/machine/runtime/needs.js +89 -0
  8. package/out/{lib → build/machine/runtime}/self.js +25 -3
  9. package/out/build/machine/terminal/jobs.js +67 -0
  10. package/out/build/machine/terminal/sign-in.js +212 -0
  11. package/out/build/machine/terminal/steps.js +460 -0
  12. package/out/build/machine/terminal/voice.js +136 -0
  13. package/out/build/machine/voice/record.js +286 -0
  14. package/out/cli-start.js +128 -0
  15. package/out/machine/line/index.js +339 -0
  16. package/out/machine/runtime/self.js +22 -0
  17. package/out/machine/terminal/clipboard.js +182 -0
  18. package/out/machine/terminal/jobs.js +67 -0
  19. package/out/machine/terminal/sign-in.js +212 -0
  20. package/out/machine/terminal/steps.js +460 -0
  21. package/out/machine/terminal/voice.js +136 -0
  22. package/out/machine/voice/record.js +79 -1
  23. package/out/native/dictate +0 -0
  24. package/out/server.generated.js +6 -0
  25. package/package.json +8 -40
  26. package/README.md +0 -343
  27. package/out/agent/command.d.ts +0 -157
  28. package/out/agent/command.js +0 -454
  29. package/out/agent/render.d.ts +0 -169
  30. package/out/agent/render.js +0 -689
  31. package/out/agent/session.d.ts +0 -334
  32. package/out/agent/session.js +0 -1232
  33. package/out/commands/agents.d.ts +0 -2
  34. package/out/commands/agents.js +0 -79
  35. package/out/commands/ask.d.ts +0 -1
  36. package/out/commands/ask.js +0 -222
  37. package/out/commands/codemap.d.ts +0 -2
  38. package/out/commands/codemap.js +0 -151
  39. package/out/commands/commands-thin.d.ts +0 -39
  40. package/out/commands/commands-thin.js +0 -244
  41. package/out/commands/config.d.ts +0 -1
  42. package/out/commands/config.js +0 -138
  43. package/out/commands/cost.d.ts +0 -1
  44. package/out/commands/cost.js +0 -167
  45. package/out/commands/decisionEngine.d.ts +0 -1
  46. package/out/commands/decisionEngine.js +0 -66
  47. package/out/commands/hooks.d.ts +0 -1
  48. package/out/commands/hooks.js +0 -83
  49. package/out/commands/install.d.ts +0 -206
  50. package/out/commands/install.js +0 -738
  51. package/out/commands/instructions.d.ts +0 -1
  52. package/out/commands/instructions.js +0 -113
  53. package/out/commands/integrations.d.ts +0 -3
  54. package/out/commands/integrations.js +0 -215
  55. package/out/commands/jobs.d.ts +0 -5
  56. package/out/commands/jobs.js +0 -157
  57. package/out/commands/keys.d.ts +0 -55
  58. package/out/commands/keys.js +0 -344
  59. package/out/commands/login.d.ts +0 -9
  60. package/out/commands/login.js +0 -606
  61. package/out/commands/memory.d.ts +0 -3
  62. package/out/commands/memory.js +0 -113
  63. package/out/commands/permissions.d.ts +0 -1
  64. package/out/commands/permissions.js +0 -94
  65. package/out/commands/plugins.d.ts +0 -4
  66. package/out/commands/plugins.js +0 -192
  67. package/out/commands/privacy.d.ts +0 -1
  68. package/out/commands/providerKey.d.ts +0 -32
  69. package/out/commands/providerKey.js +0 -108
  70. package/out/commands/repl.d.ts +0 -12
  71. package/out/commands/repl.js +0 -2303
  72. package/out/commands/report.d.ts +0 -39
  73. package/out/commands/report.js +0 -115
  74. package/out/commands/review.d.ts +0 -5
  75. package/out/commands/review.js +0 -223
  76. package/out/commands/sessions.d.ts +0 -23
  77. package/out/commands/sessions.js +0 -115
  78. package/out/commands/settings.d.ts +0 -23
  79. package/out/commands/settings.js +0 -153
  80. package/out/commands/skills.d.ts +0 -21
  81. package/out/commands/skills.js +0 -207
  82. package/out/commands/unattended.d.ts +0 -7
  83. package/out/commands/unattended.js +0 -351
  84. package/out/commands/update.d.ts +0 -1
  85. package/out/commands/update.js +0 -123
  86. package/out/commands/welcome.d.ts +0 -25
  87. package/out/commands/welcome.js +0 -223
  88. package/out/commands/worktrees.d.ts +0 -5
  89. package/out/commands/worktrees.js +0 -186
  90. package/out/executor/browser.d.ts +0 -14
  91. package/out/executor/diagnostics.d.ts +0 -2
  92. package/out/executor/documents.d.ts +0 -40
  93. package/out/executor/files.d.ts +0 -2
  94. package/out/executor/git.d.ts +0 -48
  95. package/out/executor/hooks.d.ts +0 -51
  96. package/out/executor/index.d.ts +0 -45
  97. package/out/executor/notebook.d.ts +0 -2
  98. package/out/executor/paths.d.ts +0 -20
  99. package/out/executor/sandbox.d.ts +0 -40
  100. package/out/executor/shell.d.ts +0 -86
  101. package/out/executor/toolservers.d.ts +0 -20
  102. package/out/executor/worktree.d.ts +0 -9
  103. package/out/graph/build.d.ts +0 -45
  104. package/out/graph/facts.d.ts +0 -47
  105. package/out/graph/files.d.ts +0 -45
  106. package/out/graph/read-locales.d.ts +0 -29
  107. package/out/graph/read-python.d.ts +0 -11
  108. package/out/graph/read-typescript.d.ts +0 -16
  109. package/out/graph/sync.d.ts +0 -66
  110. package/out/graph/sync.js +0 -242
  111. package/out/lib/attach.d.ts +0 -106
  112. package/out/lib/attach.js +0 -396
  113. package/out/lib/clipboard.d.ts +0 -23
  114. package/out/lib/commandlist.d.ts +0 -20
  115. package/out/lib/commandlist.js +0 -58
  116. package/out/lib/config.d.ts +0 -94
  117. package/out/lib/config.js +0 -197
  118. package/out/lib/connection.d.ts +0 -73
  119. package/out/lib/connection.js +0 -188
  120. package/out/lib/decision.d.ts +0 -22
  121. package/out/lib/decision.js +0 -50
  122. package/out/lib/fingerprint.d.ts +0 -25
  123. package/out/lib/fingerprint.js +0 -58
  124. package/out/lib/gateway.d.ts +0 -427
  125. package/out/lib/gateway.js +0 -226
  126. package/out/lib/history.d.ts +0 -24
  127. package/out/lib/history.js +0 -137
  128. package/out/lib/ide.d.ts +0 -19
  129. package/out/lib/ide.js +0 -131
  130. package/out/lib/keyboard.d.ts +0 -98
  131. package/out/lib/keyboard.js +0 -390
  132. package/out/lib/lastlogin.d.ts +0 -14
  133. package/out/lib/lastlogin.js +0 -105
  134. package/out/lib/machine.d.ts +0 -21
  135. package/out/lib/machine.js +0 -91
  136. package/out/lib/notify.d.ts +0 -4
  137. package/out/lib/notify.js +0 -52
  138. package/out/lib/output.d.ts +0 -48
  139. package/out/lib/output.js +0 -108
  140. package/out/lib/picker.d.ts +0 -1
  141. package/out/lib/picker.js +0 -158
  142. package/out/lib/project-ops.d.ts +0 -19
  143. package/out/lib/project-ops.js +0 -146
  144. package/out/lib/project.d.ts +0 -28
  145. package/out/lib/prompt.d.ts +0 -37
  146. package/out/lib/prompt.js +0 -142
  147. package/out/lib/queue.d.ts +0 -13
  148. package/out/lib/queue.js +0 -116
  149. package/out/lib/readiness.d.ts +0 -22
  150. package/out/lib/readiness.js +0 -207
  151. package/out/lib/self.d.ts +0 -23
  152. package/out/lib/servicecommand.d.ts +0 -14
  153. package/out/lib/servicecommand.js +0 -74
  154. package/out/lib/sessions.d.ts +0 -19
  155. package/out/lib/sessions.js +0 -221
  156. package/out/lib/startcache.d.ts +0 -13
  157. package/out/lib/startcache.js +0 -78
  158. package/out/lib/stdin.d.ts +0 -32
  159. package/out/lib/stdin.js +0 -117
  160. package/out/lib/store.d.ts +0 -40
  161. package/out/lib/store.js +0 -138
  162. package/out/lib/sync.d.ts +0 -18
  163. package/out/lib/sync.js +0 -81
  164. package/out/lib/types.d.ts +0 -417
  165. package/out/lib/types.js +0 -21
  166. package/out/lib/ui.d.ts +0 -123
  167. package/out/lib/ui.js +0 -299
  168. package/out/lib/version.d.ts +0 -23
  169. package/out/lib/version.js +0 -46
  170. package/out/lib/voice.d.ts +0 -49
  171. package/out/lib/voice.js +0 -236
  172. package/out/lib/words.d.ts +0 -20
  173. package/out/lib/words.js +0 -27
  174. package/out/machine/codemap/build.d.ts +0 -45
  175. package/out/machine/codemap/facts.d.ts +0 -47
  176. package/out/machine/codemap/files.d.ts +0 -45
  177. package/out/machine/codemap/read-locales.d.ts +0 -29
  178. package/out/machine/codemap/read-python.d.ts +0 -11
  179. package/out/machine/codemap/read-typescript.d.ts +0 -16
  180. package/out/machine/executor/browser.d.ts +0 -14
  181. package/out/machine/executor/diagnostics.d.ts +0 -2
  182. package/out/machine/executor/documents.d.ts +0 -40
  183. package/out/machine/executor/files.d.ts +0 -2
  184. package/out/machine/executor/git.d.ts +0 -48
  185. package/out/machine/executor/hooks.d.ts +0 -51
  186. package/out/machine/executor/index.d.ts +0 -45
  187. package/out/machine/executor/notebook.d.ts +0 -2
  188. package/out/machine/executor/paths.d.ts +0 -20
  189. package/out/machine/executor/sandbox.d.ts +0 -40
  190. package/out/machine/executor/shell.d.ts +0 -86
  191. package/out/machine/executor/toolservers.d.ts +0 -20
  192. package/out/machine/executor/worktree.d.ts +0 -9
  193. package/out/machine/folder/project.d.ts +0 -28
  194. package/out/machine/runtime/home.d.ts +0 -2
  195. package/out/machine/runtime/needs.d.ts +0 -30
  196. package/out/machine/runtime/self.d.ts +0 -23
  197. package/out/machine/voice/record.d.ts +0 -38
  198. package/out/postinstall.d.ts +0 -2
  199. package/out/postinstall.js +0 -120
  200. package/out/providers/anthropic.d.ts +0 -22
  201. package/out/providers/anthropic.js +0 -80
  202. package/out/providers/index.d.ts +0 -8
  203. package/out/providers/index.js +0 -84
  204. package/out/providers/openai.d.ts +0 -11
  205. package/out/providers/openai.js +0 -57
  206. package/out/thin.d.ts +0 -2
  207. package/out/thin.js +0 -855
  208. package/scripts/read_python.py +0 -270
  209. /package/out/{graph → build/machine/codemap}/build.js +0 -0
  210. /package/out/{graph → build/machine/codemap}/facts.js +0 -0
  211. /package/out/{graph → build/machine/codemap}/files.js +0 -0
  212. /package/out/{graph → build/machine/codemap}/read-locales.js +0 -0
  213. /package/out/{graph → build/machine/codemap}/read-typescript.js +0 -0
  214. /package/out/{executor → build/machine/executor}/browser.js +0 -0
  215. /package/out/{executor → build/machine/executor}/documents.js +0 -0
  216. /package/out/{executor → build/machine/executor}/files.js +0 -0
  217. /package/out/{executor → build/machine/executor}/git.js +0 -0
  218. /package/out/{executor → build/machine/executor}/index.js +0 -0
  219. /package/out/{executor → build/machine/executor}/notebook.js +0 -0
  220. /package/out/{executor → build/machine/executor}/paths.js +0 -0
  221. /package/out/{executor → build/machine/executor}/shell.js +0 -0
  222. /package/out/{executor → build/machine/executor}/toolservers.js +0 -0
  223. /package/out/{executor → build/machine/executor}/worktree.js +0 -0
  224. /package/out/{lib → build/machine/folder}/project.js +0 -0
  225. /package/out/{lib → build/machine/terminal}/clipboard.js +0 -0
@@ -1,2303 +0,0 @@
1
- "use strict";
2
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
- if (k2 === undefined) k2 = k;
4
- var desc = Object.getOwnPropertyDescriptor(m, k);
5
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
- desc = { enumerable: true, get: function() { return m[k]; } };
7
- }
8
- Object.defineProperty(o, k2, desc);
9
- }) : (function(o, m, k, k2) {
10
- if (k2 === undefined) k2 = k;
11
- o[k2] = m[k];
12
- }));
13
- var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
- Object.defineProperty(o, "default", { enumerable: true, value: v });
15
- }) : function(o, v) {
16
- o["default"] = v;
17
- });
18
- var __importStar = (this && this.__importStar) || (function () {
19
- var ownKeys = function(o) {
20
- ownKeys = Object.getOwnPropertyNames || function (o) {
21
- var ar = [];
22
- for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
- return ar;
24
- };
25
- return ownKeys(o);
26
- };
27
- return function (mod) {
28
- if (mod && mod.__esModule) return mod;
29
- var result = {};
30
- if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
- __setModuleDefault(result, mod);
32
- return result;
33
- };
34
- })();
35
- var __importDefault = (this && this.__importDefault) || function (mod) {
36
- return (mod && mod.__esModule) ? mod : { "default": mod };
37
- };
38
- Object.defineProperty(exports, "__esModule", { value: true });
39
- exports.runRepl = runRepl;
40
- /**
41
- * The product, running.
42
- *
43
- * ── What changed and why ──────────────────────────────────────────────────
44
- *
45
- * Typing `comprism` used to print a screen and exit, so every question meant
46
- * typing the program's name again. Nobody works that way, and it makes a
47
- * conversation look like a series of unrelated commands when the product's
48
- * whole value is the thread between them.
49
- *
50
- * So `comprism` STARTS. It opens a session, shows where you are, and then
51
- * waits for work. You type a question and get an answer with its receipt. You
52
- * type the next one and it continues the same session.
53
- *
54
- * A bare word is a command; anything else is work. That is the only rule a
55
- * person has to hold, and it is the rule every shell already taught them.
56
- *
57
- * comprism
58
- * > what is the capital of Canada? ← work
59
- * > sessions ← a command
60
- * > new ← a command
61
- * > exit ← or Ctrl-C
62
- *
63
- * ── A session with no key cannot do anything ──────────────────────────────
64
- *
65
- * Every answer is billed to the customer's own provider account, so with no key
66
- * there is nothing to run. Rather than accept a prompt and refuse it, the
67
- * session sends the person to `keys` first and will not start until one is
68
- * stored. Being stopped early and told why beats being stopped late.
69
- */
70
- const node_crypto_1 = require("node:crypto");
71
- const path = __importStar(require("node:path"));
72
- const node_readline_1 = __importDefault(require("node:readline"));
73
- const connection_1 = require("../lib/connection");
74
- const keys_1 = require("./keys");
75
- const welcome_1 = require("./welcome");
76
- const attach = __importStar(require("../lib/attach"));
77
- const commandlist_1 = require("../lib/commandlist");
78
- const history_1 = require("../lib/history");
79
- const keyboard_1 = require("../lib/keyboard");
80
- const machine_1 = require("../lib/machine");
81
- const ui = __importStar(require("../lib/ui"));
82
- const render_1 = require("../agent/render");
83
- const shell_1 = require("../machine/executor/shell");
84
- const voice = __importStar(require("../lib/voice"));
85
- const out = (s = '') => process.stdout.write(s + '\n');
86
- /**
87
- * The session's reader, and the two calls that lend the keyboard out.
88
- *
89
- * Lending it out is for the handful of COMMANDS that open a reader of their own
90
- * (`keys`, `model`, `workspace`). A job no longer needs it: the agent is handed
91
- * this reader instead of opening a second one, so the session keeps the
92
- * keyboard for the whole of its life. See `build`.
93
- */
94
- let reader = null;
95
- let onLine = null;
96
- /** Earlier requests, for Up, Down and Ctrl+R (manual 6.5). */
97
- const earlier = new history_1.History();
98
- /** Pastes, Alt+Enter and Ctrl+R, between the keyboard and the reader (6.2,
99
- * 6.3, 6.5). Only in a terminal: piped input is read as lines, as before. */
100
- const keyboard = new keyboard_1.Keyboard(() => earlier.entries);
101
- /** Where the session's keystrokes arrive, for a key the session handles
102
- * itself such as Shift+Tab. Nothing arrives while a command has the keyboard. */
103
- const keys = () => (process.stdin.isTTY ? keyboard.input : process.stdin);
104
- function releaseTerminal() {
105
- reader?.close();
106
- reader = null;
107
- // The keyboard goes back with the reader, so the command that asks its own
108
- // question is the only thing reading it (manual 6.1).
109
- keyboard.bind(null);
110
- keyboard.detach();
111
- }
112
- function takeTerminal() {
113
- if (reader || !onLine)
114
- return;
115
- const tty = process.stdin.isTTY === true;
116
- if (tty)
117
- keyboard.attach();
118
- reader = node_readline_1.default.createInterface({
119
- input: tty ? keyboard.input : process.stdin,
120
- output: process.stdout,
121
- terminal: tty,
122
- // The session's own list, walked by Up and Down. Size 0 so the reader
123
- // never adds to it itself: it would add each half of a request continued
124
- // with a backslash, and the session adds the whole request once sent.
125
- history: earlier.entries,
126
- historySize: 0,
127
- completer: complete,
128
- });
129
- keyboard.bind(reader);
130
- // Enter has already moved the cursor onto the first line of the live list,
131
- // so clearing from here down removes it before anything else prints.
132
- reader.on('line', () => {
133
- if (popupShown)
134
- process.stdout.write(`${CSI}J`);
135
- popupShown = 0;
136
- });
137
- reader.on('line', onLine);
138
- reader.on('SIGINT', () => interrupt());
139
- }
140
- /**
141
- * Tab (manual 3.1 and 6.4). After `/` it offers the service's list of
142
- * commands and skills, one line each; after `@` the project's file names.
143
- * Anywhere else it offers nothing, so it never rewrites a sentence.
144
- */
145
- function complete(line, done) {
146
- clearPopup();
147
- const slash = /^\/(\S*)$/.exec(line);
148
- if (!slash) {
149
- done(null, attach.completeAt(line, () => {
150
- if (!completion.files || Date.now() - completion.at > 30_000) {
151
- completion.files = attach.projectFiles(completion.root);
152
- completion.at = Date.now();
153
- }
154
- return completion.files;
155
- }));
156
- return;
157
- }
158
- const typed = slash[1].toLowerCase();
159
- const hits = listedItems().filter((i) => i.name.startsWith(typed));
160
- if (hits.length === 1) {
161
- done(null, [[`/${hits[0].name} `], line]);
162
- return;
163
- }
164
- done(null, [[], line]);
165
- if (hits.length === 0 || !reader)
166
- return;
167
- out();
168
- drawList(hits);
169
- // Filled in as far as every match agrees, then the prompt drawn again under
170
- // the list with the cursor at the end.
171
- const common = hits.map((h) => h.name).reduce((a, b) => {
172
- let n = 0;
173
- while (n < a.length && a[n] === b[n])
174
- n += 1;
175
- return a.slice(0, n);
176
- });
177
- const edit = reader;
178
- if (common.length > typed.length)
179
- edit.line = `/${common}`;
180
- edit.cursor = edit.line.length;
181
- reader.prompt(true);
182
- }
183
- const CSI = `${String.fromCharCode(27)}[`;
184
- const SAVE = `${String.fromCharCode(27)}7`;
185
- const RESTORE = `${String.fromCharCode(27)}8`;
186
- /** How many lines the live list under the prompt holds now, 0 when none. */
187
- let popupShown = 0;
188
- const POPUP_ROWS = 8;
189
- /** What the list under the prompt holds, and which of it is marked (-1: none). */
190
- let popupHits = [];
191
- let popupAt = -1;
192
- /**
193
- * Up and Down move through the list under the prompt; Enter runs the marked
194
- * command, Tab fills it in to add to. With nothing marked, or no list showing,
195
- * every key does what it always did (Up and Down recall earlier requests).
196
- */
197
- keyboard.onMenuKey = (key) => {
198
- if (!popupShown || !reader || popupHits.length === 0)
199
- return false;
200
- const edit = reader;
201
- if (key === 'up' || key === 'down') {
202
- popupAt = key === 'down' ? Math.min(popupHits.length - 1, popupAt + 1) : Math.max(-1, popupAt - 1);
203
- updatePopup();
204
- return true;
205
- }
206
- if (popupAt < 0)
207
- return false;
208
- const chosen = `/${popupHits[popupAt].name}`;
209
- if (key === 'tab') {
210
- edit.line = `${chosen} `;
211
- edit.cursor = edit.line.length;
212
- edit._refreshLine();
213
- clearPopup();
214
- return true;
215
- }
216
- // Enter: the marked command replaces what was typed, then Enter goes on.
217
- edit.line = chosen;
218
- edit.cursor = chosen.length;
219
- popupAt = -1;
220
- return false;
221
- };
222
- /** Takes the live list away, leaving the prompt and the cursor where they are. */
223
- function clearPopup() {
224
- if (!popupShown || !process.stdout.isTTY)
225
- return;
226
- // Each row the list used, blanked; never a clear to the end of the screen.
227
- process.stdout.write(`${SAVE}${`${CSI}1E${CSI}2K`.repeat(popupShown)}${RESTORE}`);
228
- popupShown = 0;
229
- }
230
- /**
231
- * The commands and skills that match what is typed, shown under the prompt
232
- * while it is typed (manual 6.4). The same list Tab and `help` offer, from the
233
- * service, so a skill added on the server appears here with no new build.
234
- * Drawn only while the line is `/` and a word; anything else clears it.
235
- */
236
- function updatePopup() {
237
- if (!reader || !process.stdout.isTTY)
238
- return;
239
- const line = reader.line ?? '';
240
- const slash = /^\/(\S*)$/.exec(line);
241
- const typed = slash ? slash[1].toLowerCase() : '';
242
- const hits = slash ? listedItems().filter((i) => i.name.startsWith(typed)) : [];
243
- // A different set of matches starts with nothing marked, so Enter still
244
- // sends what was typed until Down is pressed.
245
- if (hits.map((h) => h.name).join() !== popupHits.map((h) => h.name).join())
246
- popupAt = -1;
247
- popupHits = hits;
248
- // Shown for a whole word too, so the list stays in sight while it is chosen.
249
- if (!hits.length) {
250
- clearPopup();
251
- return;
252
- }
253
- const first = Math.max(0, Math.min(popupAt - POPUP_ROWS + 1, hits.length - POPUP_ROWS));
254
- const shown = hits.slice(first, first + POPUP_ROWS);
255
- const width = Math.min(18, Math.max(...shown.map((i) => i.name.length)) + 1);
256
- const room = Math.max(20, (process.stdout.columns || 100) - width - 8);
257
- const rows = shown.map((i, k) => {
258
- const from = i.source === 'session' ? '' : ` ${i.source}`;
259
- const words = `${i.description}${from}`;
260
- const name = `/${i.name}`.padEnd(width + 1);
261
- const marked = first + k === popupAt;
262
- return `${marked ? ui.c.blue('\u25B8 ') : ' '}${marked ? ui.c.bold(ui.c.blue(name)) : ui.c.bold(name)} `
263
- + ui.c.dim(words.length > room ? `${words.slice(0, room - 3)}...` : words);
264
- });
265
- if (hits.length > shown.length)
266
- rows.push(ui.c.dim(` ${hits.length - shown.length} more, Down to see them`));
267
- const col = reader.getCursorPos().cols;
268
- // A shorter list than last time blanks the rows it no longer uses, rather
269
- // than clearing to the end of the screen: on the bottom row there is no line
270
- // below to move to, and that clear wiped the list's own last row.
271
- const height = rows.length;
272
- while (rows.length < popupShown)
273
- rows.push('');
274
- // Room is made first, so a prompt on the bottom row scrolls up rather than
275
- // the list running off the screen, and the cursor comes back to its column.
276
- process.stdout.write(`${'\n'.repeat(rows.length)}${CSI}${rows.length}A${CSI}${col + 1}G${SAVE}`
277
- + rows.map((r) => `${CSI}1E${CSI}2K${r}`).join('') + RESTORE);
278
- popupShown = Math.max(height, 1);
279
- }
280
- /** The service's list for this session, once fetched (manual 6.4). */
281
- let listed = null;
282
- /** The session words this tool runs. Sent to the service, which lists only
283
- * these and counts the rest as needing a newer version. */
284
- function sessionWords() {
285
- return [...COMMANDS, 'project', 'folders', 'instructions', 'remember', 'detach', 'output', 'processes', 'stop', 'agents'];
286
- }
287
- async function refreshList() {
288
- const { resolveProject } = await Promise.resolve().then(() => __importStar(require('../machine/folder/project')));
289
- const root = resolveProject(await sessionFolder(), place.added).root;
290
- const got = await (0, commandlist_1.fetchCommandList)(root, sessionWords());
291
- // A failed refresh keeps the list already held rather than emptying it.
292
- if (got.ok || !listed)
293
- listed = got;
294
- }
295
- /** What Tab and `help` offer: the service's list, or, when it could not be
296
- * asked, this tool's own words with no descriptions. */
297
- function listedItems() {
298
- if (listed?.ok)
299
- return listed.items;
300
- return sessionWords().map((name) => ({ name, description: '', source: 'session' }));
301
- }
302
- function drawList(items) {
303
- const width = Math.min(18, Math.max(...items.map((i) => i.name.length)) + 1);
304
- for (const i of items) {
305
- const from = i.source === 'session' ? '' : ` ${ui.c.dim(i.source)}`;
306
- out(` ${ui.c.bold(`/${i.name}`.padEnd(width + 1))} ${ui.c.dim(i.description)}${from}`);
307
- }
308
- out();
309
- }
310
- /** The project whose files Tab offers after `@`, and the list, briefly kept. */
311
- const completion = {
312
- root: process.cwd(), files: null, at: 0,
313
- };
314
- /** Set by the session so the handover can end it too. */
315
- let leaveSession = () => { };
316
- /** Ctrl+C (manual 6.7): stop the job, clear the line, or leave. Set by the
317
- * session; before one starts it leaves. */
318
- let interrupt = () => leaveSession();
319
- /** Words that are commands. Anything else typed is work. */
320
- const COMMANDS = new Set([
321
- 'new', 'sessions', 'branch', 'remote', 'model', 'providers', 'keys', 'status',
322
- 'voice', 'help', 'exit', 'quit', 'clear', 'login', 'logout', 'signout', 'history',
323
- 'disconnect', 'cost', 'spend', 'attached', 'paste', 'plan', 'todo', 'mode',
324
- 'queue', 'transcript', 'edit', 'context', 'compact', 'why', 'unpin', 'pin', 'effort',
325
- 'optimize',
326
- ]);
327
- /** `processes` and `stop pN` (manual 5.13): what this session started, and
328
- * stopping one by its number. Works while a job runs, too. True if handled. */
329
- function processWord(said) {
330
- if (/^\/?processes$/i.test(said)) {
331
- const rows = (0, shell_1.listProcesses)();
332
- if (!rows.length)
333
- out(ui.c.dim(' No background processes were started in this session.'));
334
- for (const p of rows) {
335
- const age = p.seconds < 60 ? `${p.seconds} s` : `${Math.round(p.seconds / 60)} min`;
336
- out(` ${ui.c.bold(p.id)} ${p.command} ${ui.c.dim(p.running ? `running ${age}` : 'finished')}`
337
- + (p.port ? ui.c.dim(` port ${p.port}`) : ''));
338
- }
339
- out();
340
- return true;
341
- }
342
- const stop = /^\/?stop\s+(p\d+)$/i.exec(said);
343
- if (stop) {
344
- const r = (0, shell_1.stopProcess)(stop[1].toLowerCase());
345
- out(r.isError ? ui.fail(r.content) : ui.c.dim(` ${r.content}`));
346
- out();
347
- return true;
348
- }
349
- return false;
350
- }
351
- /** `agents` between jobs: the helpers defined here (manual 5.24). */
352
- async function showHelpers() {
353
- const { helperLines } = await Promise.resolve().then(() => __importStar(require('./agents')));
354
- for (const line of await helperLines(await sessionFolder()))
355
- out(` ${line}`);
356
- out();
357
- }
358
- /** The permission modes, in the order Shift+Tab moves through them (4.5). */
359
- /** The modes Shift+Tab steps through, as the service last listed them. */
360
- const MODES = ['read_only', 'approve_writes', 'auto_edit', 'full_auto'];
361
- /** How the next job in this session runs: its mode and whether it plans first
362
- * (manual 4.1, 4.5). Changed by `mode`, Shift+Tab, `plan` and `plan off`, and
363
- * applied from the next job; the service still decides what each mode allows. */
364
- const steering_ = { mode: 'approve_writes', plan: false, pin: '', effort: '', modes: MODES };
365
- /**
366
- * The line as a command, with a leading slash taken off.
367
- *
368
- * Every other tool in this space teaches a slash, so people type `/model` here.
369
- * That used to miss the command list entirely and go to the agent as a piece of
370
- * work: it answered the question and the answer was charged to the person's own
371
- * provider account. A command is the same command whether or not it is
372
- * announced with a slash, and a slashed word that is NOT a command is refused
373
- * rather than billed.
374
- */
375
- function commandWord(typed) {
376
- const slashed = typed.startsWith('/');
377
- // `comprism sessions`, typed at the comprism prompt. Everybody does it, and
378
- // it used to be sent to the model as work: the agent looked around the
379
- // project for something called "comprism sessions", found nothing, and asked
380
- // what was meant. Reading the program's own name as part of a question is a
381
- // product refusing to recognize itself.
382
- const bare = (slashed ? typed.slice(1) : typed).trim().replace(/^comprism\s+/i, '');
383
- return { word: bare.toLowerCase(), slashed };
384
- }
385
- /**
386
- * Run a command that asks its own questions.
387
- *
388
- * The session holds the keyboard so it can read what is typed at its prompt. A
389
- * command like `keys` opens its own reader to ask a question, and two readers
390
- * on one keyboard divide the typing between them: the answer either reached the
391
- * wrong reader or arrived nowhere at all and the session sat there waiting.
392
- *
393
- * So the session stands down for the length of the command, the command's own
394
- * reader is closed behind it whatever happened, and the session picks the
395
- * keyboard back up. The same handover a job gets, for the same reason.
396
- */
397
- async function withTerminal(run) {
398
- releaseTerminal();
399
- try {
400
- await run();
401
- }
402
- finally {
403
- const { closePrompt } = await Promise.resolve().then(() => __importStar(require('../lib/prompt')));
404
- closePrompt();
405
- takeTerminal();
406
- }
407
- }
408
- /**
409
- * This account's earlier sessions, from the service's record (manual 8.5).
410
- *
411
- * The in-memory list only ever knew about the current run, so closing the
412
- * window lost every thread. The record has held all of it the whole time.
413
- * Sessions of this run are left out, since they are listed above it, and their
414
- * names are taken from the record, which names a session from its first
415
- * request. Returns nothing when the workspace cannot be reached: a list is not
416
- * worth stopping a session over.
417
- */
418
- async function earlierSessions(run, limit = 10) {
419
- const { sessions } = await Promise.resolve().then(() => __importStar(require('../lib/sessions')));
420
- const reply = await sessions('list', { limit });
421
- if (!reply.ok || !reply.sessions?.sessions)
422
- return [];
423
- const rows = reply.sessions.sessions;
424
- const lines = reply.sessions.lines;
425
- const found = [];
426
- rows.forEach((r, i) => {
427
- const here = run.find((s) => s.serverId === r.session_id);
428
- if (here) {
429
- if (r.title)
430
- here.title = r.title;
431
- here.id = r.number;
432
- return;
433
- }
434
- found.push({ number: r.number, line: lines[i] ?? r.number, card: r.card });
435
- });
436
- return found;
437
- }
438
- function newSession() {
439
- // A UUID, because that is what the job record's session column holds. A
440
- // dated `cli_...` string was refused by the database, so no job started
441
- // in a session was ever recorded (found 23 September 2026, prompt 03).
442
- const serverId = (0, node_crypto_1.randomUUID)();
443
- return {
444
- // The session's number, the same one the portal shows (manual 8.1). The
445
- // service writes it; `numbered` asks for it as soon as the session opens.
446
- id: serverId,
447
- serverId,
448
- startedAt: new Date().toISOString(),
449
- jobs: [],
450
- spentUsd: 0,
451
- savedUsd: 0,
452
- compared: 0,
453
- };
454
- }
455
- const money = (n) => `$${n.toFixed(4)}`;
456
- /**
457
- * Ask the service for a new session's number and its opening line (8.2).
458
- * Returns the line to print, or null when the service could not be asked, in
459
- * which case the session keeps its full id until the next answer names it.
460
- */
461
- async function numbered(s) {
462
- const { sessions } = await Promise.resolve().then(() => __importStar(require('../lib/sessions')));
463
- const reply = await sessions('opened', { session_id: s.serverId });
464
- if (!reply.ok || !reply.sessions?.number)
465
- return null;
466
- s.id = reply.sessions.number;
467
- return reply.sessions.lines?.[0] ?? null;
468
- }
469
- /**
470
- * A session the service already holds, opened again (manual 8.4, 8.5).
471
- *
472
- * Same id, so every new job files under the same record; its jobs and its cost
473
- * so far, so the running total carries on without counting anything twice; and
474
- * the last job to continue from only when the service says the conversation
475
- * was kept. Session approvals (`a` answers) belong to the run that gave them
476
- * and are not carried over.
477
- */
478
- function reopened(r) {
479
- return {
480
- id: r.number ?? r.session_id ?? '',
481
- serverId: r.session_id ?? '',
482
- title: r.title ?? null,
483
- startedAt: new Date().toISOString(),
484
- jobs: Array.from({ length: Number(r.jobs ?? 0) }, () => ({ request: '' })),
485
- spentUsd: Number(r.cost_usd ?? 0),
486
- savedUsd: 0,
487
- compared: 0,
488
- ...(r.continues_job ? { lastJobId: r.continues_job } : {}),
489
- };
490
- }
491
- /** Ask the service for the session to open, choosing from the list when no
492
- * number was given. Prints the resume lines, or why there are none. */
493
- async function opening(how) {
494
- const { sessions, pick, failure, exitFor } = await Promise.resolve().then(() => __importStar(require('../lib/sessions')));
495
- let key = how.resume;
496
- if (how.pick) {
497
- const listed = await sessions('list', { limit: 20 });
498
- if (!listed.ok || !listed.sessions) {
499
- out(ui.fail(failure(listed)));
500
- process.exitCode = exitFor(listed);
501
- return null;
502
- }
503
- const rows = listed.sessions.sessions ?? [];
504
- if (rows.length === 0) {
505
- for (const line of listed.sessions.lines)
506
- out(line);
507
- return null;
508
- }
509
- const chosen = await pick(listed.sessions.lines);
510
- if (chosen === null)
511
- return null;
512
- key = rows[chosen]?.number;
513
- }
514
- const reply = how.latest
515
- ? await sessions('latest')
516
- : await sessions('resume', { key: key ?? '' });
517
- if (!reply.ok || !reply.sessions?.session_id) {
518
- out(ui.fail(failure(reply)));
519
- process.exitCode = exitFor(reply);
520
- return null;
521
- }
522
- out();
523
- for (const line of reply.sessions.lines)
524
- out(line);
525
- out();
526
- // What the session was about, before the next question goes in.
527
- await showConversation(reply.sessions.session_id, false);
528
- return reopened(reply.sessions);
529
- }
530
- /**
531
- * A session's earlier questions and answers, read back (manual 8.4).
532
- *
533
- * On reopening, the last three exchanges, each answer cut to its first lines,
534
- * so the screen says what the session was about without filling it. `history`
535
- * shows every turn in full. Answers are drawn the way a new answer is: tables
536
- * as tables, emphasis as emphasis.
537
- */
538
- async function showConversation(key, full) {
539
- const { sessions } = await Promise.resolve().then(() => __importStar(require('../lib/sessions')));
540
- const { plain } = await Promise.resolve().then(() => __importStar(require('../agent/render')));
541
- const reply = await sessions('read', { key });
542
- let turns = (reply.sessions?.turns) ?? [];
543
- // A service released before it sent the turns still hands over the whole
544
- // session on export, every request and answer in full. Read from there, so
545
- // the answers are drawn with their headings and tables rather than as the
546
- // one line summaries an older service lists.
547
- if (reply.ok && turns.length === 0)
548
- turns = await exportedTurns(key);
549
- if (!reply.ok || turns.length === 0) {
550
- if (full) {
551
- out(ui.c.dim(' Nothing earlier in this session was kept to show.'));
552
- out();
553
- }
554
- return;
555
- }
556
- const exchanges = turns.filter((t) => t.role === 'you').length;
557
- let shown = turns;
558
- if (!full) {
559
- // From the third question from the end, so what is shown is whole exchanges.
560
- let asked = 0;
561
- let from = turns.length;
562
- for (let i = turns.length - 1; i >= 0; i--) {
563
- if (turns[i].role === 'you' && ++asked === 3) {
564
- from = i;
565
- break;
566
- }
567
- if (i === 0)
568
- from = 0;
569
- }
570
- shown = turns.slice(from);
571
- }
572
- out(ui.c.dim(full ? ` The whole session, ${exchanges} question(s):`
573
- : ` Earlier in this session${exchanges > 3 ? `, the last 3 of ${exchanges} questions` : ''}:`));
574
- out();
575
- for (const t of shown) {
576
- if (t.role === 'you') {
577
- out(` ${ui.c.bold(ui.c.blue('you'))} ${ui.c.bold(t.text.trim())}`);
578
- out();
579
- continue;
580
- }
581
- // Drawn exactly as a new answer is, rail and all, never indented further.
582
- const lines = plain(t.text.trim()).split('\n');
583
- const keep = full ? lines : lines.slice(0, openingCut(lines));
584
- for (const l of keep)
585
- out(l);
586
- if (keep.length < lines.length)
587
- out(ui.c.dim(` ... ${lines.length - keep.length} more lines. Type /history to read it all.`));
588
- out();
589
- }
590
- }
591
- /**
592
- * Where to cut an earlier answer on reopening: the last paragraph break in its
593
- * first dozen lines, so a table or a list is never shown half drawn. An answer
594
- * with no break that early is cut at eight lines, as before.
595
- */
596
- function openingCut(lines) {
597
- if (lines.length <= 12)
598
- return lines.length;
599
- // A break is the rail on its own; a blank row inside a table has more rules.
600
- const isBreak = (l) => /^│?$/.test(l.replace(/\x1b\[[0-9;]*m/g, '').trim());
601
- for (let i = 12; i >= 3; i--)
602
- if (isBreak(lines[i]))
603
- return i;
604
- return 8;
605
- }
606
- /** A session's questions and answers in full, from the service's export. */
607
- async function exportedTurns(key) {
608
- const { sessions } = await Promise.resolve().then(() => __importStar(require('../lib/sessions')));
609
- const reply = await sessions('export', { key, format: 'json' });
610
- const doc = reply.sessions?.document;
611
- const turns = [];
612
- for (const job of doc?.work ?? []) {
613
- if (job.request)
614
- turns.push({ role: 'you', text: job.request });
615
- if (job.answer)
616
- turns.push({ role: 'agent', text: job.answer });
617
- }
618
- return turns;
619
- }
620
- /** The command and skill list, as the service sent it (manual 6.4). */
621
- function printHelp() {
622
- out();
623
- out(ui.c.dim(' Type a question and press enter. Or one of these:'));
624
- out();
625
- drawList(listedItems());
626
- if (!listed?.ok) {
627
- out(ui.c.amber(' Your organization could not be asked for its skills, so only this tool\'s own words are shown.'));
628
- out();
629
- }
630
- else if (listed.needsUpdate.length > 0) {
631
- out(ui.c.dim(` ${listed.needsUpdate.length} more need a newer comprism: npm install -g @illuminis/comprism`));
632
- out();
633
- }
634
- out(ui.c.dim(' A slash is fine as well, so `/model` and `model` do the same thing. Type / and press Tab to pick one.'));
635
- out(ui.c.dim(' Drag a file onto this window, or type @ and a path, to have it read.'));
636
- out(ui.c.dim(' End a line with \\ or press Alt+Enter for a new line. Up and Down recall earlier requests; Ctrl+R searches them.'));
637
- out();
638
- }
639
- /**
640
- * Hand a request to the coding agent, in the folder this session is working in.
641
- *
642
- * The agent reads the project, shows every change as it makes it, and runs
643
- * the tests. It is the same agent the standalone command runs; there is one
644
- * implementation, so the session and the command cannot behave differently.
645
- */
646
- /**
647
- * The folders this session works in (manual 2.1 and 2.3). `project <path>`
648
- * changes the folder for the rest of the session; `folders add <path>` allows
649
- * another. Neither changes the saved default, which is `comprism workspace`.
650
- */
651
- const place = { folder: null, added: [], workspace: '' };
652
- /**
653
- * One command the service runs itself (web manual 13.2, 13.3). The service says
654
- * what it means and writes every line; this answers whether a folder exists on
655
- * this computer when asked, prints the lines, and carries out the one action it
656
- * names. True when the session's workspace or folders changed; the request to
657
- * run when a next step was chosen.
658
- */
659
- async function serviceCommand(words) {
660
- const { runServiceCommand } = await Promise.resolve().then(() => __importStar(require('../lib/servicecommand')));
661
- const said = await runServiceCommand(words, { cwd: await sessionFolder(), current: place.workspace });
662
- if (!said.reached) {
663
- out(ui.fail(said.message || 'Your organization could not answer that.'));
664
- return false;
665
- }
666
- for (const line of said.lines)
667
- out(line);
668
- const a = said.action;
669
- if (!a)
670
- return false;
671
- if (a.run)
672
- return a.run;
673
- if (a.open_workspace)
674
- place.workspace = a.open_workspace;
675
- if (a.use_folder) {
676
- place.folder = a.use_folder;
677
- (await Promise.resolve().then(() => __importStar(require('../lib/project-ops')))).useSessionFolder(a.use_folder);
678
- }
679
- if (a.add_folder && !place.added.includes(a.add_folder))
680
- place.added.push(a.add_folder);
681
- if (a.remove_folder)
682
- place.added = place.added.filter((f) => f !== a.remove_folder);
683
- return true;
684
- }
685
- async function sessionFolder() {
686
- if (place.folder)
687
- return place.folder;
688
- const { currentWorkspace } = await Promise.resolve().then(() => __importStar(require('./settings')));
689
- return currentWorkspace().path;
690
- }
691
- /** The line this session begins with, as the service wrote it (manual 2.2). */
692
- async function projectLine() {
693
- const { resolveProject, asWire } = await Promise.resolve().then(() => __importStar(require('../machine/folder/project')));
694
- const { ask } = await Promise.resolve().then(() => __importStar(require('../lib/gateway')));
695
- const facts = resolveProject(await sessionFolder(), place.added);
696
- const reply = await ask({ intent: 'project', prompt: '', project: asWire(facts, 'approve_writes') });
697
- // Drawn as sent. When the service cannot answer, the folder alone, so the
698
- // person still knows where they are.
699
- return reply.ok && reply.project_line ? reply.project_line : ` ${facts.root}`;
700
- }
701
- /** `asked` is the same line already on its way, when startup asked early. */
702
- async function showProjectLine(asked) {
703
- out(ui.c.bold(await (asked ?? projectLine())));
704
- out();
705
- }
706
- /** Ctrl+O's choice, kept for the next job too, and notes left over from the
707
- * last one (manual 6.8, 6.9). */
708
- const view = { full: false, late: [] };
709
- /** `context` and `compact [what to keep]`, answered and worded by the
710
- * service for the session's latest job (manual 6.13, 6.15). */
711
- async function contextOf(intent, jobId, keep = '', sessionKey) {
712
- const { ask } = await Promise.resolve().then(() => __importStar(require('../lib/gateway')));
713
- out();
714
- if (intent === 'compact')
715
- out(ui.c.dim(' summarizing the conversation so far to keep it affordable'));
716
- // The session is named too, so a session with no job yet (questions asked in
717
- // Work) gets the same figure the web meter shows (web manual 3.11).
718
- const reply = await ask({
719
- intent, prompt: keep, ...(jobId ? { jobId } : {}), ...(sessionKey ? { spendSession: sessionKey } : {}),
720
- });
721
- if (!reply.ok || !reply.context) {
722
- out(ui.fail(reply.message || 'Your organization could not answer that.'));
723
- }
724
- else {
725
- for (const line of reply.context.lines)
726
- out(line);
727
- }
728
- out();
729
- }
730
- /** One job's full record, as the service writes it (manual 6.9). */
731
- async function showTranscript(jobId) {
732
- out();
733
- if (!jobId) {
734
- out(ui.c.dim(' Nothing has run in this session yet, so there is no transcript.'));
735
- out();
736
- return;
737
- }
738
- const { ask } = await Promise.resolve().then(() => __importStar(require('../lib/gateway')));
739
- const reply = await ask({ intent: 'transcript', prompt: '', jobId });
740
- if (!reply.ok || !reply.transcript) {
741
- out(ui.fail(reply.message || 'The transcript could not be read from your organization.'));
742
- }
743
- else {
744
- for (const line of reply.transcript.lines)
745
- out(line);
746
- }
747
- out();
748
- }
749
- /**
750
- * Open the request in the person's editor and put what they saved back at the
751
- * prompt, unsent (manual 6.6). The file exists only while the editor is open,
752
- * in a folder only this account can read, and is removed the moment it closes.
753
- */
754
- async function editRequest(current) {
755
- const chosen = process.env.VISUAL || process.env.EDITOR || (0, machine_1.machineSettings)().editor;
756
- const put = (text) => {
757
- if (!reader)
758
- return;
759
- reader.setPrompt(`${ui.c.bold(ui.c.blue('comprism'))} ${ui.c.dim('>')} `);
760
- reader.prompt();
761
- reader.write((0, keyboard_1.asOneLine)(text));
762
- };
763
- if (!chosen) {
764
- out();
765
- out(ui.fail('No editor is set. Set VISUAL or EDITOR, or run: comprism config set editor <command>'));
766
- put(current);
767
- return;
768
- }
769
- const fs = await Promise.resolve().then(() => __importStar(require('node:fs')));
770
- const os = await Promise.resolve().then(() => __importStar(require('node:os')));
771
- const { spawnSync } = await Promise.resolve().then(() => __importStar(require('node:child_process')));
772
- const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'comprism-edit-'));
773
- const file = path.join(dir, 'request.md');
774
- fs.writeFileSync(file, current, { mode: 0o600 });
775
- releaseTerminal();
776
- let back = current;
777
- try {
778
- const [program, ...extra] = chosen.split(/\s+/).filter(Boolean);
779
- // nosemgrep: javascript.lang.security.detect-child-process.detect-child-process
780
- spawnSync(program, [...extra, file], { stdio: 'inherit' });
781
- const saved = fs.readFileSync(file, 'utf8');
782
- // Closed without saving leaves the prompt exactly as it was.
783
- if (saved !== current)
784
- back = saved.replace(/\r?\n$/, '');
785
- }
786
- catch {
787
- out(ui.fail(`${chosen} could not be opened, so the request is as it was.`));
788
- }
789
- finally {
790
- fs.rmSync(dir, { recursive: true, force: true });
791
- takeTerminal();
792
- }
793
- put(back);
794
- }
795
- async function build(session, request, confirm, onStarted, attachmentIds = [], leftOut = [], ask) {
796
- const { runAgent } = await Promise.resolve().then(() => __importStar(require('../agent/command')));
797
- out();
798
- // Counted the moment it starts, not when it returns. A person who leaves
799
- // part-way through a job was told "nothing asked in that session" over work
800
- // that had already been paid for, which is the one number this product cannot
801
- // get wrong.
802
- session.jobs.push({ request });
803
- const began = Date.now();
804
- let busy = false;
805
- const code = await runAgent({
806
- request: [request],
807
- cwd: await sessionFolder(),
808
- addFolders: place.added,
809
- // Carry on from the last question rather than starting again. `new` clears
810
- // it, which is what `new` is for.
811
- continuesJob: session.lastJobId,
812
- // The session the person is actually in. Without it the server files every
813
- // job of the day under one row, which is why `sessions` here listed three
814
- // and the Sessions screen showed one.
815
- conversationId: session.serverId,
816
- // A server started by one question is still there for the next (5.13).
817
- keepProcesses: true,
818
- // The session's own keyboard, handed to the agent.
819
- //
820
- // The agent has to put a change in front of the person and wait. It used to
821
- // open a reader of its own to do that, and with the session already reading
822
- // the same keyboard the question landed nowhere: every command came back
823
- // "needs approval and nobody is watching", refused by the product rather
824
- // than by the person. One reader, owned by whoever started the process,
825
- // passed down.
826
- confirm,
827
- prompt: ask,
828
- onStarted,
829
- fullView: view.full,
830
- // Files the person attached, already read and waiting on the server.
831
- attachments: attachmentIds,
832
- // Files named that could not be attached, so the agent is told (3.10).
833
- leftOut,
834
- // Ask before a change and before a command, because now the person can
835
- // actually answer. This was auto_edit only because approving a write was
836
- // impossible from inside a session; it is the mode the standalone command
837
- // uses, so the two behave the same way.
838
- mode: steering_.mode,
839
- plan: steering_.plan,
840
- // A pin and effort set with `pin` and `effort` are the session's, held by
841
- // the service (manual 4.17, 4.18; web manual 4.5, 4.6), which applies them
842
- // to this job. So a pin set in the browser applies here, and the reverse.
843
- // The running total is the whole point of a session, so it is added up
844
- // from what each job actually cost. It used to be declared and never
845
- // touched, so a session ended by reporting zero spent and zero saved
846
- // directly underneath a job that had just charged three cents.
847
- onFinished: (r) => {
848
- // Busy in another place (manual 8.8): nothing ran, nothing was charged.
849
- if (r.outcome === 'busy') {
850
- busy = true;
851
- return;
852
- }
853
- // Recorded even when the job did not finish. A run that was stopped or
854
- // ran out of steps still said things, and the next question is usually
855
- // about exactly that.
856
- if (r.jobId)
857
- session.lastJobId = r.jobId;
858
- // Which job answered which request, for `rewind` (manual 7.4 to 7.6).
859
- const asked = session.jobs[session.jobs.length - 1];
860
- if (asked && r.jobId && !asked.jobId)
861
- asked.jobId = r.jobId;
862
- session.todos = r.todos;
863
- if (r.why && r.why.length)
864
- session.why = r.why;
865
- // Notes that arrived after the last step become requests of their own
866
- // (manual 6.8); the service has already said so on screen.
867
- view.late = r.lateNotes;
868
- session.spentUsd += r.totalUsd;
869
- if (r.savedUsd !== null) {
870
- session.savedUsd += r.savedUsd;
871
- session.compared += 1;
872
- }
873
- },
874
- });
875
- if (busy) {
876
- session.jobs.pop();
877
- return whileBusy(session, request, confirm, onStarted, attachmentIds, leftOut, ask);
878
- }
879
- out();
880
- if (code !== 0)
881
- out(ui.c.amber(' the job did not finish'));
882
- // A job long enough to switch windows during is worth being told about
883
- // (manual 6.11).
884
- if (Date.now() - began > 30_000) {
885
- const { notify } = await Promise.resolve().then(() => __importStar(require('../lib/notify')));
886
- notify(code === 0 ? 'Your job finished.' : 'Your job stopped before finishing.', (l) => out(ui.c.dim(l)));
887
- }
888
- }
889
- /**
890
- * The session is busy in another place (manual 8.8). Offer to wait, or to read
891
- * it here. Waiting asks the service until the session is free, then runs the
892
- * request; reading prints the session's turns and runs nothing.
893
- */
894
- async function whileBusy(session, request, confirm, onStarted, attachmentIds, leftOut, ask) {
895
- const { sessions } = await Promise.resolve().then(() => __importStar(require('../lib/sessions')));
896
- const said = ((await ask?.('w to wait for it, r to read it here: ')) ?? 'r').trim().toLowerCase();
897
- if (said.startsWith('w')) {
898
- out(ui.c.dim(' waiting for the session to be free...'));
899
- for (let i = 0; i < 120; i++) {
900
- await new Promise((r) => setTimeout(r, 3000));
901
- const now = await sessions('lease', { key: session.serverId });
902
- if (now.ok && now.sessions && !now.sessions.busy_in) {
903
- return build(session, request, confirm, onStarted, attachmentIds, leftOut, ask);
904
- }
905
- }
906
- out(ui.c.amber(' still busy after six minutes, so nothing was run.'));
907
- return;
908
- }
909
- const read = await sessions('read', { key: session.serverId });
910
- out();
911
- for (const line of read.sessions?.lines ?? [read.message ?? ''])
912
- out(line);
913
- out(ui.c.dim(' Read only: nothing was run.'));
914
- out();
915
- }
916
- /** What `remote` holds while it is on (manual 8.11). */
917
- const remote = { timer: null, session: null, take: () => undefined, idle: () => false };
918
- async function remoteOn(session) {
919
- const { sessions, failure } = await Promise.resolve().then(() => __importStar(require('../lib/sessions')));
920
- const reply = await sessions('remote_on', { key: session.serverId });
921
- if (!reply.ok || !reply.sessions) {
922
- out(ui.fail(failure(reply)));
923
- out();
924
- return;
925
- }
926
- for (const line of reply.sessions.lines)
927
- out(line);
928
- out();
929
- remote.session = session.serverId;
930
- if (remote.timer)
931
- clearInterval(remote.timer);
932
- let asking = false;
933
- remote.timer = setInterval(() => {
934
- if (asking || !remote.idle() || !remote.session)
935
- return;
936
- asking = true;
937
- void sessions('remote_poll', { key: remote.session }).then((got) => {
938
- const body = got.sessions;
939
- if (body?.off) {
940
- stopRemoteTimer();
941
- return;
942
- }
943
- for (const text of body?.requests ?? [])
944
- remote.take(text);
945
- }).finally(() => { asking = false; });
946
- }, 2000);
947
- remote.timer.unref();
948
- }
949
- function stopRemoteTimer() {
950
- if (remote.timer)
951
- clearInterval(remote.timer);
952
- remote.timer = null;
953
- remote.session = null;
954
- }
955
- async function remoteOff(session, quiet = false) {
956
- const key = remote.session ?? session.serverId;
957
- const was = remote.session;
958
- stopRemoteTimer();
959
- if (quiet && !was)
960
- return;
961
- const { sessions } = await Promise.resolve().then(() => __importStar(require('../lib/sessions')));
962
- const reply = await sessions('remote_off', { key });
963
- if (!quiet) {
964
- for (const line of reply.sessions?.lines ?? [' Remote was not on.'])
965
- out(line);
966
- out();
967
- }
968
- }
969
- /** The running total, shown when a session ends or another is opened. */
970
- function summarize(s) {
971
- // The session is over: where the company keeps no content, its checkpoints
972
- // end with it (manual 7.3). The service decides; nothing is kept here.
973
- if (s.jobs.length > 0) {
974
- void Promise.resolve().then(() => __importStar(require('./review'))).then((m) => m.review('session_ended', { session_id: s.serverId }))
975
- .catch(() => undefined);
976
- }
977
- if (s.jobs.length === 0) {
978
- out(ui.c.dim(' nothing asked in that session'));
979
- return;
980
- }
981
- // A saving is only shown when at least one job could be priced against the
982
- // comparison model. Otherwise there is nothing to compare, and printing
983
- // "$0.0000 saved" would state a figure nobody measured.
984
- const saving = s.compared > 0
985
- ? ` ${ui.c.green(money(s.savedUsd))} ${ui.c.dim('saved')}`
986
- : ` ${ui.c.dim('nothing to compare against yet')}`;
987
- out(` ${ui.c.dim('session')} ${ui.c.bold(s.id)} ${s.jobs.length} job(s)`
988
- + ` ${money(s.spentUsd)} ${ui.c.dim('spent')}${saving}`);
989
- }
990
- async function runRepl(how = {}) {
991
- // Resolved when the person leaves. The reader is closed and reopened around
992
- // every job, so waiting on it closing would end the session at the first one.
993
- let done = () => { };
994
- const finished = new Promise((resolve) => { done = resolve; });
995
- const conn = (0, connection_1.readConnection)();
996
- if (!conn?.url || !conn.workspaceKey) {
997
- await (0, welcome_1.showWelcome)(undefined, process.stdin.isTTY === true && !how.noSignIn);
998
- // Signed out: sign in right here rather than naming another command to
999
- // type. The last person is offered, so it is usually Enter and a password.
1000
- if (process.stdin.isTTY === true && !how.noSignIn) {
1001
- const { cmdLogin } = await Promise.resolve().then(() => __importStar(require('./login')));
1002
- await cmdLogin(['--into-session']);
1003
- const { closePrompt } = await Promise.resolve().then(() => __importStar(require('../lib/prompt')));
1004
- closePrompt();
1005
- if ((0, connection_1.readConnection)()?.workspaceKey)
1006
- return runRepl({ ...how, noSignIn: true, noMark: true });
1007
- }
1008
- return;
1009
- }
1010
- // Everything the opening screen needs is asked for AT ONCE, then drawn in
1011
- // order as it arrives. Asked one after another it was five round trips end
1012
- // to end, about fifteen seconds on a laptop before the prompt appeared.
1013
- //
1014
- // And what the service said LAST time is drawn at once, so the prompt is
1015
- // ready in well under a second. The same questions are still asked; their
1016
- // answers are kept for next time, and a change that matters is said as soon
1017
- // as it arrives. A first start, or another workspace, waits as before.
1018
- const { readStart, saveStart } = await Promise.resolve().then(() => __importStar(require('../lib/startcache')));
1019
- const { session: whoAmI } = await Promise.resolve().then(() => __importStar(require('./welcome')));
1020
- const known = readStart(conn.url);
1021
- const here = await sessionFolder();
1022
- const meAsked = whoAmI().then((me) => { if (me)
1023
- saveStart(conn.url, { me }); return me; });
1024
- const stateAsked = (0, keys_1.keyState)().then((s) => {
1025
- if (s.reached)
1026
- saveStart(conn.url, { hasKey: s.hasKey });
1027
- return s;
1028
- });
1029
- const lineAsked = projectLine()
1030
- .then((l) => { saveStart(conn.url, { lines: { [here]: l } }); return l; })
1031
- .catch(() => '');
1032
- const listAsked = refreshList()
1033
- .then(() => { if (listed?.ok)
1034
- saveStart(conn.url, { list: listed }); })
1035
- .catch(() => undefined);
1036
- if (known.list?.ok && !listed)
1037
- listed = known.list;
1038
- await (0, welcome_1.showWelcome)(known.me ? known.me : await meAsked, false, !how.noMark);
1039
- // A key, before anything else. With none there is nothing to bill and nothing
1040
- // to measure, so a prompt accepted here could only ever be refused later.
1041
- //
1042
- // THREE outcomes, not two. Telling "your account holds no key" apart from "we
1043
- // could not ask your account" is the whole point: on 17 September a person
1044
- // whose workspace held four working keys was shown the first message and sent
1045
- // to a form, because an unanswered question was read as an answer of none.
1046
- const state = known.hasKey === true ? { reached: true, hasKey: true } : await stateAsked;
1047
- if (known.hasKey === true) {
1048
- // Drawn from the last answer; the fresh one says so if the key has gone.
1049
- void stateAsked.then((fresh) => {
1050
- if (fresh.reached && !fresh.hasKey) {
1051
- out();
1052
- out(ui.c.amber(' Your account no longer has a provider key stored, so requests will be refused.'));
1053
- out(` ${ui.c.dim('run')} ${ui.c.bold('keys')} ${ui.c.dim('to add one')}`);
1054
- reader?.prompt(true);
1055
- }
1056
- });
1057
- }
1058
- if (!state.reached) {
1059
- out(ui.fail(`Your organization could not be reached, so ${ui.c.bold('nothing is known')} about your keys.`));
1060
- out(` ${ui.c.dim(state.why)}`);
1061
- out(` ${ui.c.dim('check the address with')} ${ui.c.bold('comprism status')}${ui.c.dim(', or sign in again with')} ${ui.c.bold('comprism login')}`);
1062
- out();
1063
- process.exitCode = 1;
1064
- return;
1065
- }
1066
- if (!state.hasKey) {
1067
- out(ui.c.amber(' Your account has no provider key stored, so nothing can run yet.'));
1068
- out(ui.c.dim(' Every answer is billed to your own provider account.'));
1069
- out();
1070
- await (0, keys_1.cmdKeys)([]);
1071
- const after = await (0, keys_1.keyState)();
1072
- if (!(after.reached && after.hasKey)) {
1073
- out(ui.fail('Still no key stored on your account, so the session cannot start.'));
1074
- out(` ${ui.c.dim('run')} ${ui.c.bold('comprism keys')} ${ui.c.dim('when you have one')}`);
1075
- out();
1076
- process.exitCode = 1;
1077
- return;
1078
- }
1079
- out();
1080
- }
1081
- const history = [];
1082
- let session = newSession();
1083
- /** Read, or change, this session's pin and effort on the service (manual
1084
- * 4.17, 4.18). Says the service's refusal and returns null on one. */
1085
- const steer = async (change) => {
1086
- const { sessions, failure } = await Promise.resolve().then(() => __importStar(require('../lib/sessions')));
1087
- const changing = Object.keys(change).length > 0;
1088
- const reply = await sessions(changing ? 'steer' : 'steering', { session_id: session.serverId, ...change });
1089
- const said = reply.sessions;
1090
- if (!reply.ok || !said || reply.granted === false) {
1091
- out(ui.fail(failure(reply)));
1092
- return null;
1093
- }
1094
- steering_.pin = said.pin ?? '';
1095
- steering_.effort = said.effort === 'normal' ? '' : said.effort;
1096
- // Mode and plan are the service's too (CLI manual 4.1, 4.5); kept here only
1097
- // to send with the next job and to draw the prompt.
1098
- if (said.mode)
1099
- steering_.mode = said.mode;
1100
- if (typeof said.plan === 'boolean')
1101
- steering_.plan = said.plan;
1102
- if (said.modes?.length)
1103
- steering_.modes = said.modes;
1104
- return said;
1105
- };
1106
- if (how.latest || how.resume || how.pick) {
1107
- const found = await opening(how);
1108
- if (!found) {
1109
- out();
1110
- if (!process.exitCode)
1111
- process.exitCode = 1;
1112
- return;
1113
- }
1114
- session = found;
1115
- }
1116
- else {
1117
- // The session's number arrives while the person is already typing.
1118
- void numbered(session);
1119
- }
1120
- history.push(session);
1121
- // Ctrl-C leaves, and says what the session cost on the way out. A product
1122
- // that vanishes without telling you what it spent is the thing this one
1123
- // exists to replace.
1124
- // Set while the agent is waiting on a yes or no. The next line typed is that
1125
- // answer, not the next request, so it is handed straight to whoever is
1126
- // waiting instead of joining the queue.
1127
- let answering = null;
1128
- /** Rings or notifies when an approval has waited 30 seconds (6.11). */
1129
- let waitingTimer = null;
1130
- const startWaiting = () => {
1131
- if (waitingTimer)
1132
- clearTimeout(waitingTimer);
1133
- waitingTimer = setTimeout(() => {
1134
- void Promise.resolve().then(() => __importStar(require('../lib/notify'))).then(({ notify }) => notify('comprism is waiting for your answer.', (l) => out(ui.c.dim(l))));
1135
- }, 30_000);
1136
- waitingTimer.unref();
1137
- };
1138
- const takeAnswer = (line) => {
1139
- if (waitingTimer) {
1140
- clearTimeout(waitingTimer);
1141
- waitingTimer = null;
1142
- }
1143
- if (!answering)
1144
- return false;
1145
- const waiting = answering;
1146
- answering = null;
1147
- waiting(line);
1148
- return true;
1149
- };
1150
- /**
1151
- * The keyboard, lent to the agent for one question.
1152
- *
1153
- * The session keeps its reader. The agent is given a way to use it, and gets
1154
- * back a plain yes or no. Anything other than yes is no, which is the same
1155
- * rule the standalone command applies, so an approval is never assumed from a
1156
- * stray keystroke.
1157
- */
1158
- const confirm = (question) => new Promise((resolve) => {
1159
- if (leaving || !reader) {
1160
- resolve(false);
1161
- return;
1162
- }
1163
- answering = (line) => resolve(/^y(es)?$/i.test((line ?? '').trim()));
1164
- startWaiting();
1165
- reader.setPrompt(` ${question} `);
1166
- reader.prompt();
1167
- });
1168
- /** The same lent keyboard, for a line of text: the plan question and the
1169
- * agent's questions (manual 4.2, 4.3). Null when the person left. */
1170
- const askLine = (question) => new Promise((resolve) => {
1171
- if (leaving || !reader) {
1172
- resolve(null);
1173
- return;
1174
- }
1175
- answering = resolve;
1176
- startWaiting();
1177
- reader.setPrompt(` ${question} `);
1178
- reader.prompt();
1179
- });
1180
- /** The next line typed, whatever it says. The same lent keyboard, used to
1181
- * wait rather than to ask: nothing is read here, the press of enter is the
1182
- * whole signal. */
1183
- const nextLine = () => new Promise((resolve) => {
1184
- if (leaving || !reader) {
1185
- resolve('');
1186
- return;
1187
- }
1188
- answering = (line) => resolve(line ?? '');
1189
- reader.setPrompt('');
1190
- reader.prompt();
1191
- });
1192
- /**
1193
- * Say it instead of typing it.
1194
- *
1195
- * Recorded here, transcribed on the server, and then put INTO the prompt
1196
- * rather than sent. Speech is misheard often enough that sending it
1197
- * unseen would eventually spend somebody's money on a question they never
1198
- * asked, and the fix costs one glance.
1199
- *
1200
- * This draws its own prompt at the end, which is why the caller must not.
1201
- * The words go into the line buffer, and a buffer written before the prompt
1202
- * exists is echoed once by readline and again when the prompt redraws, so
1203
- * the person saw their sentence twice and could edit only the second copy.
1204
- */
1205
- const speak = async () => {
1206
- // On a Mac, the words appear as they are spoken, the way the web app shows
1207
- // them, from the Mac's own recogniser. Anywhere it cannot listen (no
1208
- // helper, or permission not given) this falls through to recording and
1209
- // having the server write it down when Enter is pressed.
1210
- if (process.stdout.isTTY) {
1211
- const live = voice.listenLive();
1212
- if (live) {
1213
- await new Promise((r) => setTimeout(r, 400));
1214
- if (live.problem() && !live.words()) {
1215
- await live.stop();
1216
- out(ui.c.dim(` ${live.problem()}`));
1217
- }
1218
- else {
1219
- out();
1220
- out(ui.c.green(' listening...') + ui.c.dim(' say it, then press enter'));
1221
- const draw = () => {
1222
- const bars = Math.round(live.level() * 12);
1223
- const meter = ui.c.green('█'.repeat(bars)) + ui.c.dim('░'.repeat(12 - bars));
1224
- const room = Math.max(20, (process.stdout.columns || 100) - 20);
1225
- const heard = live.words();
1226
- const shown = heard.length > room ? `...${heard.slice(-(room - 3))}` : heard;
1227
- process.stdout.write(`\r${CSI}2K ${meter} ${shown}`);
1228
- };
1229
- const ticking = setInterval(draw, 80);
1230
- await nextLine();
1231
- clearInterval(ticking);
1232
- process.stdout.write(`${CSI}1A\r${CSI}2K`);
1233
- const said = await live.stop();
1234
- if (said === null) {
1235
- out(ui.c.dim(` ${live.problem() || 'dictation stopped'}`));
1236
- out();
1237
- return prompt();
1238
- }
1239
- if (!said) {
1240
- out(ui.c.dim(' no words in that one'));
1241
- out();
1242
- return prompt();
1243
- }
1244
- // Into the prompt, not sent: the person reads it, fixes what was
1245
- // misheard, and presses Enter. Nothing is asked or charged until then.
1246
- prompt();
1247
- reader?.write(said);
1248
- return;
1249
- }
1250
- }
1251
- }
1252
- const short = voice.missing();
1253
- if (short) {
1254
- out();
1255
- out(ui.c.amber(` ${short}`));
1256
- out();
1257
- return prompt();
1258
- }
1259
- let live;
1260
- try {
1261
- live = voice.start();
1262
- }
1263
- catch (err) {
1264
- out(ui.fail(err.message));
1265
- out();
1266
- return prompt();
1267
- }
1268
- out();
1269
- out(ui.c.green(' listening...') + ui.c.dim(' say it, then press enter'));
1270
- // What it hears, while it hears it: a meter that moves with the voice at
1271
- // once, and the words so far, refreshed every few seconds. Without these
1272
- // a person talks into a blank line with no idea whether anything is
1273
- // arriving. The words so far are a preview; the whole recording is
1274
- // written down again when they press Enter, and that is what they get.
1275
- const tty = process.stdout.isTTY === true;
1276
- let heard = '';
1277
- let asking = false;
1278
- let lastAsked = 0;
1279
- const draw = () => {
1280
- const bars = Math.round(voice.level(live.file) * 12);
1281
- const meter = ui.c.green('█'.repeat(bars)) + ui.c.dim('░'.repeat(12 - bars));
1282
- const room = Math.max(20, (process.stdout.columns || 100) - 20);
1283
- const words = heard.length > room ? `...${heard.slice(-(room - 3))}` : heard;
1284
- process.stdout.write(`\r${CSI}2K ${meter} ${words}`);
1285
- };
1286
- const preview = async () => {
1287
- if (asking || Date.now() - lastAsked < 2500)
1288
- return;
1289
- const part = voice.soFar(live.file);
1290
- if (!part)
1291
- return;
1292
- asking = true;
1293
- lastAsked = Date.now();
1294
- try {
1295
- const got = await voice.transcribe(conn.url, conn.workspaceKey, part);
1296
- if (got.text)
1297
- heard = got.text.trim();
1298
- }
1299
- catch { /* a preview that fails leaves the last one showing */ }
1300
- asking = false;
1301
- };
1302
- const ticking = tty ? setInterval(() => { draw(); void preview(); }, 120) : null;
1303
- await nextLine();
1304
- if (ticking)
1305
- clearInterval(ticking);
1306
- // The line the typed Enter left behind is the meter's; clear it.
1307
- if (tty)
1308
- process.stdout.write(`${CSI}1A\r${CSI}2K`);
1309
- const { file, bytes } = await live.stop();
1310
- try {
1311
- if (bytes < 2000) {
1312
- // Nothing heard is usually the microphone permission, never asked for
1313
- // or refused, so it is named (manual 6.16).
1314
- out(ui.c.dim(process.platform === 'darwin'
1315
- ? ' nothing was recorded. Your terminal may not have microphone permission: System Settings, Privacy and Security, Microphone.'
1316
- : ' nothing was recorded. Check that a microphone is connected and not muted.'));
1317
- out();
1318
- return prompt();
1319
- }
1320
- out(ui.c.dim(' writing that down...'));
1321
- const said = await voice.transcribe(conn.url, conn.workspaceKey, file);
1322
- if (!said.text) {
1323
- out(ui.c.dim(' no words in that one'));
1324
- out();
1325
- return prompt();
1326
- }
1327
- out();
1328
- // The prompt first, THEN the words into it. The person sees their own
1329
- // sentence at the prompt, edits it where the microphone misheard, and
1330
- // presses enter. Nothing has been asked or charged until they do.
1331
- prompt();
1332
- reader?.write(said.text);
1333
- }
1334
- catch (err) {
1335
- out(ui.fail(err.message));
1336
- out();
1337
- prompt();
1338
- }
1339
- finally {
1340
- // The recording is deleted here, always. It is the most personal thing
1341
- // this product ever touches and there is no reason on earth to keep it.
1342
- voice.discard(file);
1343
- }
1344
- };
1345
- /** Files attached and not yet sent: they go with the next request
1346
- * (manual 3.6). `attached` lists them and `detach N` takes one off. */
1347
- let pending = [];
1348
- /** Pastes this session, so each is `clipboard-N.png` with its own N. */
1349
- let pastes = 0;
1350
- /**
1351
- * The clipboard's picture, attached to the next request (manual 3.4). Saved
1352
- * to a temporary file, uploaded like any file, and the file removed
1353
- * whatever happened.
1354
- */
1355
- const pasteImage = async () => {
1356
- const { readClipboardImage, discard } = await Promise.resolve().then(() => __importStar(require('../lib/clipboard')));
1357
- const clip = await readClipboardImage(pastes + 1);
1358
- out();
1359
- if (!clip.ok) {
1360
- out(ui.c.amber(` ${clip.why}`));
1361
- out();
1362
- return;
1363
- }
1364
- pastes += 1;
1365
- try {
1366
- const { attached, refused } = await attach.upload(conn.url, conn.workspaceKey, [clip.file]);
1367
- for (const line of attach.describe(attached))
1368
- out(ui.c.dim(` ${line}`));
1369
- for (const r of refused)
1370
- out(ui.c.amber(` ${r.why}`));
1371
- pending = [...pending, ...attached];
1372
- }
1373
- finally {
1374
- discard(clip.folder);
1375
- }
1376
- out();
1377
- };
1378
- /**
1379
- * Files the person pointed at, read and ready, and the question without the
1380
- * long paths in it.
1381
- *
1382
- * Uploading happens before the job starts and is reported before anything is
1383
- * charged, because the commonest complaint about any assistant is that it
1384
- * answered without looking at the thing you gave it. A file with a problem
1385
- * gets one line saying so and is never sent (manual 3.10).
1386
- *
1387
- * `send` is false when the line named files and said nothing else: that is
1388
- * a drag and drop, and the files wait for the question that follows.
1389
- */
1390
- const gather = async (typed) => {
1391
- const { resolveProject } = await Promise.resolve().then(() => __importStar(require('../machine/folder/project')));
1392
- const here = await sessionFolder();
1393
- const root = resolveProject(here, place.added).root;
1394
- completion.root = root;
1395
- const found = attach.mentions(typed, root, here);
1396
- const waiting = () => pending.map((a) => a.id);
1397
- if (found.length === 0)
1398
- return { text: typed, ids: waiting(), leftOut: [], send: true };
1399
- out();
1400
- const problems = found.filter((m) => m.problem);
1401
- const readable = found.filter((m) => !m.problem);
1402
- const { attached, refused } = readable.length > 0
1403
- ? await attach.upload(conn.url, conn.workspaceKey, readable.map((m) => m.file))
1404
- : { attached: [], refused: [] };
1405
- for (const line of attach.describe(attached))
1406
- out(ui.c.dim(` ${line}`));
1407
- for (const m of problems)
1408
- out(ui.c.amber(` ${m.problem?.message}`));
1409
- for (const r of refused)
1410
- out(ui.c.amber(` ${r.why}`));
1411
- const failed = [...problems.map((m) => m.file), ...refused.map((r) => r.file)];
1412
- const leftOut = failed.map((f) => path.basename(f));
1413
- const landed = found.filter((m) => !failed.includes(m.file));
1414
- const words = attach.withoutMentions(typed, found);
1415
- pending = [...pending, ...attached];
1416
- if (!words) {
1417
- if (pending.length > 0)
1418
- out(ui.c.dim(' Waiting for your question. `attached` lists what will go with it.'));
1419
- out();
1420
- return { text: '', ids: [], leftOut, send: false };
1421
- }
1422
- // Every file failed and the request was about them: nothing is sent until
1423
- // the person says so (manual 3.10).
1424
- if (attached.length === 0 && pending.length === 0) {
1425
- const go = await confirm('None of those files could be attached. Send the request anyway? (y/n)');
1426
- if (!go) {
1427
- out(ui.c.dim(' Nothing was sent.'));
1428
- out();
1429
- return { text: '', ids: [], leftOut, send: false };
1430
- }
1431
- }
1432
- return { text: attach.withoutPaths(typed, landed), ids: waiting(), leftOut, send: true };
1433
- };
1434
- // A way to stop the job that is running, while it is running. Null between
1435
- // jobs, which is also the answer to "is anything running".
1436
- /** The earlier jobs shown by the last `sessions`, so `sessions w2` means the
1437
- * same thing the person just read. */
1438
- let recent = [];
1439
- let cancelJob = null;
1440
- /** Set while a job is running, so a line typed mid job reaches it instead of
1441
- * queueing up behind it as the next question. */
1442
- let steerJob = null;
1443
- /** Everything else a running job can be asked: pause, carry on, the queue,
1444
- * the full view (manual 6.7 to 6.9). Null between jobs. */
1445
- let job = null;
1446
- // Esc pauses a running job; at the prompt it does nothing (6.7).
1447
- keyboard.onEscape = () => {
1448
- if (!job || job.isPaused())
1449
- return false;
1450
- job.pause();
1451
- return true;
1452
- };
1453
- // Ctrl+O, the short or the full view, from now on (6.9).
1454
- keyboard.onFullView = () => {
1455
- view.full = !view.full;
1456
- job?.setFull(view.full);
1457
- out();
1458
- out(ui.c.dim(view.full ? ' full view: each action\'s input and output in full' : ' short view'));
1459
- if (!job)
1460
- prompt();
1461
- };
1462
- // Ctrl+G: the request so far, in your own editor (6.6). At the prompt only.
1463
- keyboard.onEditor = () => {
1464
- if (job || working)
1465
- return;
1466
- const edit = reader;
1467
- const now = [...draft, edit?.line ?? ''].join('\n');
1468
- draft = [];
1469
- void editRequest(now);
1470
- };
1471
- // Ctrl+V: the clipboard's picture, as `paste` (3.4). At the prompt only;
1472
- // what is typed so far stays on the line.
1473
- keyboard.onPasteImage = () => {
1474
- if (job || working)
1475
- return;
1476
- void pasteImage().then(() => prompt());
1477
- };
1478
- keyboard.vi = (0, machine_1.machineSettings)().keys === 'vi';
1479
- // Ctrl+C: the job, then the line, then the session (6.7).
1480
- interrupt = () => {
1481
- if (job) {
1482
- // An approval on screen is answered no, a question as stopped.
1483
- takeAnswer(null);
1484
- job.cancel();
1485
- return;
1486
- }
1487
- const edit = reader;
1488
- if (draft.length > 0 || (edit && edit.line)) {
1489
- draft = [];
1490
- if (edit)
1491
- edit.line = '';
1492
- out();
1493
- return prompt();
1494
- }
1495
- leave();
1496
- };
1497
- let leaving = false;
1498
- /**
1499
- * Ctrl-C, or `exit`.
1500
- *
1501
- * Three things in order, and the order is the point. The question on screen
1502
- * is answered no, because nobody said yes. The job is stopped, because the
1503
- * person asked to leave and a job left running spends money nobody is
1504
- * watching. Then the session waits for the job to report before it says what
1505
- * it cost, since a figure printed before the job replies is a figure of zero
1506
- * over work already paid for.
1507
- *
1508
- * The wait is capped. A server that never answers must not turn Ctrl-C into
1509
- * something a person has to press twice.
1510
- */
1511
- const leave = () => {
1512
- if (leaving)
1513
- return;
1514
- leaving = true;
1515
- // The portal link ends with the session (manual 8.11).
1516
- if (remote.session)
1517
- void remoteOff(session, true);
1518
- // A question on screen is answered as stopped, not as a word (4.3).
1519
- takeAnswer(null);
1520
- cancelJob?.();
1521
- const close = () => {
1522
- out();
1523
- const said = (0, render_1.stoppedLines)((0, shell_1.stopEverything)());
1524
- if (said)
1525
- process.stdout.write(said);
1526
- summarize(session);
1527
- out();
1528
- releaseTerminal();
1529
- earlier.finish();
1530
- done();
1531
- };
1532
- if (!working)
1533
- return close();
1534
- const waitedFrom = Date.now();
1535
- const settle = setInterval(() => {
1536
- if (!working || Date.now() - waitedFrom > 5000) {
1537
- clearInterval(settle);
1538
- close();
1539
- }
1540
- }, 50);
1541
- };
1542
- leaveSession = leave;
1543
- const prompt = () => {
1544
- if (leaving || !reader)
1545
- return;
1546
- reader.setPrompt(`${ui.c.bold(ui.c.blue('comprism'))} ${ui.c.dim('>')} `);
1547
- reader.prompt();
1548
- };
1549
- const lastLine = known.lines?.[here];
1550
- await showProjectLine(lastLine ? Promise.resolve(lastLine) : lineAsked);
1551
- // The command and skill list, and whether this company lets typed requests
1552
- // be kept on this machine (manual 6.4, 6.5). Unknown keeps them for this
1553
- // session only and leaves any file alone. The last list serves until the
1554
- // fresh one lands.
1555
- if (!known.list?.ok)
1556
- await listAsked;
1557
- // `config set history off` keeps nothing at all, not even for this session.
1558
- const historyOff = (0, machine_1.machineSettings)().history === 'off';
1559
- earlier.start(historyOff ? false : listed?.ok ? listed.keepHistory : null);
1560
- if (historyOff)
1561
- earlier.disable();
1562
- out(ui.c.dim(' Type what you want done. / lists commands and skills, voice dictates, Ctrl+C leaves.'));
1563
- out();
1564
- // One line at a time, in the order they arrived.
1565
- //
1566
- // Readline keeps reading while an answer is still coming back, so two
1567
- // questions typed quickly ran at once and the second finished first. Pausing
1568
- // the reader fixed the order and THREW AWAY anything already typed, which is
1569
- // worse: a person who types ahead loses what they typed.
1570
- //
1571
- // So lines are queued and worked through one at a time. Nothing is dropped
1572
- // and nothing overtakes.
1573
- const queue = [];
1574
- let working = false;
1575
- const drain = async () => {
1576
- if (working)
1577
- return;
1578
- working = true;
1579
- while (queue.length > 0 && !leaving) {
1580
- await handle(queue.shift());
1581
- }
1582
- working = false;
1583
- };
1584
- // Requests sent from the portal while `remote` is on (manual 8.11). This
1585
- // terminal asks the service for them every two seconds between jobs, which
1586
- // is also how the service knows the session is still running here; they are
1587
- // run here, on this machine, exactly as if typed, approvals included.
1588
- remote.take = (text) => {
1589
- out(`\n ${ui.c.bold('from the portal:')} ${text}`);
1590
- queue.push(text);
1591
- void drain();
1592
- };
1593
- remote.idle = () => !job && !working && !leaving;
1594
- /** The lines of a request continued with `\\` or Alt+Enter, so far. */
1595
- let draft = [];
1596
- onLine = (typedLine) => {
1597
- // Up and Down start again from the newest request after every line.
1598
- if (reader)
1599
- reader.historyIndex = -1;
1600
- const continued = keyboard.takeContinued();
1601
- // An answer the agent is waiting for jumps the queue, because it is not a
1602
- // request. Queued, it would sit behind the very job that is waiting on it.
1603
- if (draft.length === 0 && takeAnswer(keyboard.expand(typedLine)))
1604
- return;
1605
- // A request on more than one line (manual 6.2). Held until a line ends
1606
- // without a continuation, then sent once with its line breaks.
1607
- if (continued || typedLine.endsWith('\\')) {
1608
- draft.push(continued ? typedLine : typedLine.slice(0, -1));
1609
- reader?.setPrompt(ui.c.dim(' ... '));
1610
- reader?.prompt();
1611
- return;
1612
- }
1613
- const shown = [...draft, typedLine].join('\n');
1614
- draft = [];
1615
- // Paste labels swapped back for what was pasted (6.3).
1616
- const line = keyboard.expand(shown);
1617
- if (line.trim())
1618
- earlier.add(shown, line);
1619
- // Something said while a job is RUNNING goes to that job, not into the
1620
- // queue behind it. A person who sees the agent going the wrong way at step
1621
- // three had two options before this: stop it and lose everything, or watch
1622
- // it finish doing the wrong thing and pay for the privilege. It joins the
1623
- // conversation before the next step, which is the earliest moment it can
1624
- // change anything.
1625
- const said = line.trim();
1626
- // Paused with Esc: whatever comes next, even an empty Enter, is the answer
1627
- // to "carry on how" (manual 6.7).
1628
- if (job?.isPaused()) {
1629
- job.carryOn(said);
1630
- return;
1631
- }
1632
- // `queue`, `queue clear` and `transcript` while it runs are for the
1633
- // session, not notes for the agent (6.8, 6.9).
1634
- if (job && /^\/?queue(\s+clear)?$/i.test(said)) {
1635
- job.queue(/clear$/i.test(said));
1636
- return;
1637
- }
1638
- if (job && /^\/?transcript$/i.test(said)) {
1639
- void showTranscript(job.jobId());
1640
- return;
1641
- }
1642
- if (job && processWord(said))
1643
- return;
1644
- // `agents` and `stop h2` while helpers run (manual 5.25).
1645
- if (job && /^\/?agents$/i.test(said)) {
1646
- const running = job.helpers();
1647
- if (!running.length)
1648
- out(ui.c.dim(' No helpers are running.'));
1649
- for (const h of running)
1650
- out(` ${ui.c.bold(h.id)} ${h.agent ? `${h.agent}: ` : ''}${h.question}`);
1651
- return;
1652
- }
1653
- const helperStop = /^\/?stop\s+(h\d+)$/i.exec(said);
1654
- if (job && helperStop) {
1655
- job.stopHelper(helperStop[1].toLowerCase());
1656
- return;
1657
- }
1658
- if (steerJob && said) {
1659
- // The session says nothing back. `steer` already prints its own
1660
- // acknowledgement, and two lines for one thing typed reads as a stutter.
1661
- steerJob(said);
1662
- return;
1663
- }
1664
- queue.push(line);
1665
- void drain();
1666
- };
1667
- // The keyboard first, THEN the prompt. Drawing the prompt before the reader
1668
- // existed printed nothing, and the session looked dead on arrival.
1669
- takeTerminal();
1670
- prompt();
1671
- // Shift+Tab moves to the next permission mode (manual 4.5). Only at the
1672
- // prompt: during a job the change would apply from the next job anyway, and
1673
- // redrawing over a running job's output is unreadable.
1674
- // The live list of commands and skills, redrawn after each key at the prompt,
1675
- // once the reader has applied the key to the line.
1676
- keys().on('keypress', (_s, key) => {
1677
- if (working || answering || leaving || key?.name === 'return' || key?.name === 'tab')
1678
- return;
1679
- setImmediate(updatePopup);
1680
- });
1681
- keys().on('keypress', (_s, key) => {
1682
- if (!key || key.name !== 'tab' || !key.shift || working || answering || leaving)
1683
- return;
1684
- // The next mode in the service's own list, set by the service.
1685
- const modes = steering_.modes;
1686
- const next = modes[(modes.indexOf(steering_.mode) + 1) % modes.length];
1687
- out();
1688
- void steer({ mode: next }).then((said) => {
1689
- for (const line of said?.lines ?? [])
1690
- out(ui.c.dim(line));
1691
- prompt();
1692
- });
1693
- });
1694
- async function handle(line) {
1695
- const typed = line.trim();
1696
- if (!typed)
1697
- return prompt();
1698
- const { word, slashed: slashWord } = commandWord(typed);
1699
- // A dragged file starting with `/` is a path, not a slashed command
1700
- // (manual 3.3). Only when the whole first word is something on the disk.
1701
- const slashed = slashWord && !attach.startsWithPath(typed);
1702
- // Where the session works (manual 2.1 to 2.3). Read off the typed line, not
1703
- // `word`, because a path keeps its case.
1704
- const bare = typed.replace(/^\//, '').replace(/^comprism\s+/i, '').trim();
1705
- // The instructions in force, and a note for this project (manual 2.8, 2.9).
1706
- if (/^instructions$/i.test(bare)) {
1707
- const { cmdInstructions } = await Promise.resolve().then(() => __importStar(require('./instructions')));
1708
- await withTerminal(async () => { await cmdInstructions([]); });
1709
- return prompt();
1710
- }
1711
- const remember = /^remember\s+(.+)$/i.exec(bare);
1712
- if (remember) {
1713
- const { addNote } = await Promise.resolve().then(() => __importStar(require('./memory')));
1714
- await addNote(remember[1]);
1715
- out();
1716
- return prompt();
1717
- }
1718
- // Commands the service runs itself (web manual 13.2, 13.3): any word the
1719
- // service lists as its own, and `project`, the old name for `workspace`.
1720
- // What they mean and every line printed are the service's; this sends what
1721
- // was typed, answers whether a folder exists, and carries out the action.
1722
- const head = (bare.split(/\s+/)[0] ?? '').toLowerCase();
1723
- const { waitingNextSteps } = await Promise.resolve().then(() => __importStar(require('../agent/session')));
1724
- const serviceWord = head === 'project'
1725
- || (/^\d+$/.test(bare) && waitingNextSteps > 0)
1726
- || (listed?.items ?? []).some((i) => i.source === 'service' && i.name === head);
1727
- if (serviceWord) {
1728
- const words = head === 'project' ? bare.replace(/^project\b/i, 'workspace') : bare;
1729
- const acted = await serviceCommand(words);
1730
- out();
1731
- // A next step chosen: it runs as the request it stands for.
1732
- if (typeof acted === 'string')
1733
- return handle(`work ${acted}`);
1734
- if (acted) {
1735
- await showProjectLine();
1736
- // Another folder has other skills.
1737
- await refreshList();
1738
- }
1739
- return prompt();
1740
- }
1741
- // `pin <model>` and `effort <level>` (manual 4.17, 4.18), kept by the
1742
- // service for this session, so the browser shows the same pin.
1743
- const pinTo = /^pin\s+(\S+)$/.exec(word);
1744
- if (pinTo) {
1745
- const said = await steer({ pin: pinTo[1] });
1746
- if (said)
1747
- out(ui.c.dim(` pinned ${ui.c.bold(said.pin_label ?? steering_.pin)} for the next requests. \`unpin\` hands the choice back.`));
1748
- out();
1749
- return prompt();
1750
- }
1751
- // `optimize on` and `optimize off <model>` (manual 4.17): the same switch
1752
- // as beside the model in the browser and VS Code. Off is the session pin.
1753
- const optimizeTo = /^optimize\s+(on|off)(?:\s+(\S+))?$/i.exec(word);
1754
- if (optimizeTo) {
1755
- const on = optimizeTo[1].toLowerCase() === 'on';
1756
- const hold = optimizeTo[2] ?? steering_.pin;
1757
- if (on) {
1758
- if (await steer({ pin: '' }))
1759
- out(ui.c.dim(' Optimize is on: CompletionPrism picks the model for each step'));
1760
- }
1761
- else if (!hold) {
1762
- out(ui.fail('Name the model to keep, such as `optimize off sonnet`.'));
1763
- }
1764
- else {
1765
- const said = await steer({ pin: hold });
1766
- if (said)
1767
- out(ui.c.dim(` Optimize is off: ${ui.c.bold(said.pin_label ?? hold)} answers every request. Work is not optimized. \`optimize on\` hands the choice back.`));
1768
- }
1769
- out();
1770
- return prompt();
1771
- }
1772
- const effortTo = /^effort\s+(\S+)$/.exec(word);
1773
- if (effortTo) {
1774
- // The service checks the word and says what is allowed.
1775
- const said = await steer({ effort: effortTo[1] });
1776
- if (said) {
1777
- out(ui.c.dim(` effort ${ui.c.bold(said.effort)} for the next requests`));
1778
- if (said.effort_note)
1779
- out(ui.c.dim(` ${said.effort_note}`));
1780
- }
1781
- out();
1782
- return prompt();
1783
- }
1784
- // `mode <name>` and `plan off` (manual 4.1, 4.5).
1785
- const modeTo = /^mode\s+(\S+)$/.exec(word);
1786
- if (modeTo) {
1787
- const said = await steer({ mode: modeTo[1] });
1788
- for (const line of said?.lines ?? [])
1789
- out(ui.c.dim(line));
1790
- out();
1791
- return prompt();
1792
- }
1793
- if (word === 'plan off') {
1794
- const said = await steer({ plan: false });
1795
- for (const line of said?.lines ?? [])
1796
- out(ui.c.dim(line));
1797
- out();
1798
- return prompt();
1799
- }
1800
- if (processWord(word))
1801
- return prompt();
1802
- if (/^\/?agents$/i.test(word)) {
1803
- await showHelpers();
1804
- return prompt();
1805
- }
1806
- if (/^\/?stop\s+h\d+$/i.test(word)) {
1807
- out(ui.c.dim(' No job is running, so there are no helpers to stop.'));
1808
- out();
1809
- return prompt();
1810
- }
1811
- // `output 3`: a command's whole output, kept on this machine (5.12).
1812
- const outputOf = /^output(?:\s+(\d+))?$/.exec(word);
1813
- if (outputOf) {
1814
- const { keptOutput } = await Promise.resolve().then(() => __importStar(require('../machine/executor/shell')));
1815
- const kept = outputOf[1] ? keptOutput(Number(outputOf[1])) : undefined;
1816
- if (!outputOf[1])
1817
- out(ui.c.dim(' output N shows the whole output of command N, the number on its line.'));
1818
- else if (!kept)
1819
- out(ui.fail(`No output ${outputOf[1]} is kept in this session.`));
1820
- else {
1821
- out(ui.c.dim(` output ${outputOf[1]}: ${kept.command}`));
1822
- out(kept.text.replace(/\n$/, '') || ui.c.dim(' (no output)'));
1823
- }
1824
- out();
1825
- return prompt();
1826
- }
1827
- // `detach 2` takes the second waiting file off the list (manual 3.6).
1828
- const detach = /^detach\s+(\d+)$/.exec(word);
1829
- if (detach) {
1830
- const n = Number(detach[1]);
1831
- const gone = pending[n - 1];
1832
- if (!gone) {
1833
- out(ui.fail(pending.length === 0
1834
- ? 'Nothing is waiting to be attached.'
1835
- : `There is no attachment ${n}. Type \`attached\` for the list.`));
1836
- }
1837
- else {
1838
- pending = pending.filter((_, i) => i !== n - 1);
1839
- out(ui.c.dim(` detached ${gone.filename}`));
1840
- }
1841
- out();
1842
- return prompt();
1843
- }
1844
- // `changes`, `diff` and `rewind`, with what follows them (manual 7.1 to 7.6).
1845
- const reviewWord = /^(changes|diff|rewind)(?:\s+(.*))?$/.exec(word);
1846
- if (reviewWord) {
1847
- const w = reviewWord[1];
1848
- const rest = reviewWord[2] ?? '';
1849
- // What the agent changed in this session, its diff, and putting it
1850
- // back, files and conversation (manual 7.1 to 7.6).
1851
- if (w === 'changes' || w === 'diff') {
1852
- const done = session.jobs.filter((j) => j.jobId);
1853
- if (!done.length) {
1854
- out(ui.c.dim(' Nothing has run in this session yet.'));
1855
- out();
1856
- return prompt();
1857
- }
1858
- const { cmdChanges, cmdDiff } = await Promise.resolve().then(() => __importStar(require('./review')));
1859
- for (const j of done) {
1860
- if (w === 'changes')
1861
- await cmdChanges([j.jobId]);
1862
- else
1863
- await cmdDiff([j.jobId, ...rest.split(/\s+/).filter(Boolean)]);
1864
- }
1865
- return prompt();
1866
- }
1867
- if (w === 'rewind') {
1868
- const done = session.jobs.filter((j) => j.jobId);
1869
- if (!done.length) {
1870
- out(ui.c.dim(' Nothing has run in this session yet, so there is nothing to rewind.'));
1871
- out();
1872
- return prompt();
1873
- }
1874
- const conversation = /--conversation|--both/.test(rest);
1875
- const files = !/--conversation/.test(rest) || /--both/.test(rest);
1876
- out();
1877
- out(` ${conversation ? 'Your requests in this session' : 'The steps of this session'}:`);
1878
- done.forEach((j, i) => out(` ${i + 1} ${j.request.slice(0, 70)}`));
1879
- const picked = await askLine(` Go back to before which request? [1 to ${done.length}, Enter for ${done.length}] `);
1880
- if (picked === null) {
1881
- out();
1882
- return prompt();
1883
- }
1884
- const n = picked.trim() ? Number(picked.trim()) : done.length;
1885
- if (!Number.isInteger(n) || n < 1 || n > done.length) {
1886
- out(ui.fail(`Choose a number from 1 to ${done.length}.`));
1887
- out();
1888
- return prompt();
1889
- }
1890
- if (files) {
1891
- // The files of every job from that request on, latest first.
1892
- const { cmdRewind } = await Promise.resolve().then(() => __importStar(require('./review')));
1893
- const yesNo = async (q) => /^y(es)?$/i.test(((await askLine(q)) ?? '').trim());
1894
- for (const j of done.slice(n - 1).reverse())
1895
- await cmdRewind([j.jobId], yesNo);
1896
- }
1897
- if (conversation) {
1898
- const { sessions: ask8, failure } = await Promise.resolve().then(() => __importStar(require('../lib/sessions')));
1899
- const before = done[n - 2]?.jobId ?? '';
1900
- const reply = await ask8('branch', { key: session.serverId, at_job: before });
1901
- if (!reply.ok || !reply.sessions?.session_id) {
1902
- out(ui.fail(failure(reply)));
1903
- out();
1904
- return prompt();
1905
- }
1906
- summarize(session);
1907
- const kept = done.slice(0, n - 1);
1908
- session = reopened(reply.sessions);
1909
- session.jobs = kept.map((j) => ({ ...j }));
1910
- history.push(session);
1911
- out(ui.ok(`The conversation is back to before request ${n}, as a new branch.`));
1912
- for (const line of reply.sessions.lines)
1913
- out(line);
1914
- out(ui.c.dim(' The original, with everything it cost, is kept and can be reopened.'));
1915
- out();
1916
- }
1917
- return prompt();
1918
- }
1919
- return prompt();
1920
- }
1921
- if (COMMANDS.has(word)) {
1922
- switch (word) {
1923
- case 'plan': {
1924
- const said = await steer({ plan: true });
1925
- for (const line of said?.lines ?? [])
1926
- out(ui.c.dim(line));
1927
- out();
1928
- break;
1929
- }
1930
- case 'mode': {
1931
- const said = await steer({});
1932
- for (const line of said?.lines ?? [])
1933
- out(ui.c.dim(line));
1934
- out();
1935
- break;
1936
- }
1937
- case 'pin': {
1938
- const said = await steer({});
1939
- out(said?.pin
1940
- ? ` ${ui.c.dim('pinned')} ${ui.c.bold(said.pin_label ?? said.pin)}`
1941
- : ui.c.dim(' Nothing is pinned; the service chooses the model for each step. `pin <model>` pins one.'));
1942
- out();
1943
- break;
1944
- }
1945
- case 'optimize': {
1946
- const said = await steer({});
1947
- out(said?.pin
1948
- ? ` ${ui.c.dim('Optimize is off:')} ${ui.c.bold(said.pin_label ?? said.pin)} ${ui.c.dim('answers every request. `optimize on` turns it back on.')}`
1949
- : ui.c.dim(' Optimize is on: CompletionPrism picks the model for each step. `optimize off <model>` keeps one.'));
1950
- out();
1951
- break;
1952
- }
1953
- case 'unpin':
1954
- if (await steer({ pin: '' }))
1955
- out(ui.c.dim(' unpinned: the service chooses the model for each step again'));
1956
- out();
1957
- break;
1958
- case 'effort': {
1959
- const said = await steer({});
1960
- out(ui.c.dim(said ? ` effort ${said.effort}` : ' effort not known.'));
1961
- if (said?.effort_note)
1962
- out(ui.c.dim(` ${said.effort_note}`));
1963
- out();
1964
- break;
1965
- }
1966
- case 'why':
1967
- if (!session.why || session.why.length === 0)
1968
- out(ui.c.dim(' No step has run in this session yet.'));
1969
- else
1970
- for (const line of session.why)
1971
- out(line);
1972
- out();
1973
- break;
1974
- case 'todo':
1975
- if (!session.todos || session.todos.length === 0)
1976
- out(ui.c.dim(' No checklist yet.'));
1977
- else
1978
- out((0, render_1.todos)(session.todos).trimEnd());
1979
- out();
1980
- break;
1981
- case 'edit':
1982
- // Returns without the redraw below: the editor puts the text back at
1983
- // the prompt itself.
1984
- return editRequest('');
1985
- case 'context':
1986
- await contextOf('context', session.lastJobId, '', session.serverId || session.id);
1987
- break;
1988
- case 'compact':
1989
- await contextOf('compact', session.lastJobId);
1990
- break;
1991
- case 'queue':
1992
- // Between jobs nothing can be waiting: a note typed now is a request.
1993
- out(ui.c.dim(' No notes are waiting. Notes typed while a job runs join it at its next step.'));
1994
- out();
1995
- break;
1996
- case 'transcript':
1997
- await showTranscript(session.lastJobId);
1998
- break;
1999
- case 'paste':
2000
- await pasteImage();
2001
- break;
2002
- case 'attached':
2003
- if (pending.length === 0)
2004
- out(ui.c.dim(' Nothing is waiting to be attached.'));
2005
- for (const row of attach.listing(pending))
2006
- out(` ${row}`);
2007
- out();
2008
- break;
2009
- case 'exit':
2010
- case 'quit':
2011
- return leave();
2012
- case 'clear':
2013
- process.stdout.write('\x1b[2J\x1b[H');
2014
- break;
2015
- case 'help':
2016
- // Asked again, so a skill saved a minute ago is on the list.
2017
- await refreshList();
2018
- printHelp();
2019
- break;
2020
- // A new session from a copy of this one's conversation (manual 8.6).
2021
- case 'branch': {
2022
- if (session.jobs.length === 0) {
2023
- out(ui.c.dim(' Nothing has run in this session yet, so there is nothing to branch.'));
2024
- out();
2025
- break;
2026
- }
2027
- const { sessions: ask8, failure } = await Promise.resolve().then(() => __importStar(require('../lib/sessions')));
2028
- const reply = await ask8('branch', { key: session.serverId });
2029
- if (!reply.ok || !reply.sessions?.session_id) {
2030
- out(ui.fail(failure(reply)));
2031
- out();
2032
- break;
2033
- }
2034
- summarize(session);
2035
- session = reopened(reply.sessions);
2036
- history.push(session);
2037
- for (const line of reply.sessions.lines)
2038
- out(line);
2039
- out();
2040
- break;
2041
- }
2042
- case 'remote': {
2043
- await remoteOn(session);
2044
- break;
2045
- }
2046
- case 'new': {
2047
- await remoteOff(session, true);
2048
- summarize(session);
2049
- session = newSession();
2050
- history.push(session);
2051
- const line = await numbered(session);
2052
- out(line ? ui.c.bold(line) : ui.ok('New session.'));
2053
- out();
2054
- break;
2055
- }
2056
- case 'sessions': {
2057
- out();
2058
- // What this account did before this window was opened, from the
2059
- // service's record of sessions (manual 8.5). Kept numbered
2060
- // separately so a number never means two different things.
2061
- // Every session the service keeps a record of for this person, up to
2062
- // its limit, when they can be moved through and picked by number; a
2063
- // typed list stays short enough to read.
2064
- const onTerminal = process.stdin.isTTY === true && process.stdout.isTTY === true;
2065
- recent = await earlierSessions(history, onTerminal ? 200 : 10);
2066
- // On a terminal, the list is picked from with the arrow keys; the
2067
- // typed forms below still work everywhere, and in a pipe are the
2068
- // only way.
2069
- if (onTerminal && history.length + recent.length > 1) {
2070
- // Names, dates and cost only. The ids are for typing a session
2071
- // back, and nobody types in a list they move through with arrows.
2072
- const noId = (line) => line.trimStart().replace(/^(?:srv|s)_[0-9a-f]+\s+/i, '');
2073
- const rows = [
2074
- ...history.map((s) => [
2075
- `${s.title ?? 'this session'}${s === session ? ' (now)' : ''}`,
2076
- `this window \u00b7 ${s.jobs.length} job(s) \u00b7 ${money(s.spentUsd)}`,
2077
- ]),
2078
- // The service's two lines where it sent them; its one line otherwise.
2079
- ...recent.map((r) => (r.card?.length ? r.card : [noId(r.line)])),
2080
- ];
2081
- const { pick } = await Promise.resolve().then(() => __importStar(require('../lib/picker')));
2082
- let choice = null;
2083
- out(ui.c.dim(' choose a session:'));
2084
- await withTerminal(async () => {
2085
- choice = await pick(rows, 'Up and Down to choose, or type its number, Enter to open, Esc to stay here', history.indexOf(session), true);
2086
- });
2087
- out();
2088
- if (choice === null)
2089
- return prompt();
2090
- const n = choice;
2091
- if (n < history.length) {
2092
- if (history[n] === session)
2093
- return prompt();
2094
- return handle(`sessions ${n + 1}`);
2095
- }
2096
- return handle(`sessions w${n - history.length + 1}`);
2097
- }
2098
- history.forEach((s, i) => {
2099
- const here = s === session ? ui.c.green(' now') : ' ';
2100
- // The NAME where our server has made one, and the id beside it
2101
- // rather than instead of it: the id is what a person types back to
2102
- // reopen the session, so it can never be replaced by the name.
2103
- const named = s.title ? ` ${ui.c.text(s.title)}` : '';
2104
- out(`${here} ${String(i + 1).padStart(2)}. ${ui.c.bold(s.id)}`
2105
- + ` ${s.jobs.length} job(s) ${money(s.spentUsd)}${named}`);
2106
- });
2107
- if (recent.length > 0) {
2108
- out();
2109
- out(ui.c.dim(' earlier work on this account:'));
2110
- recent.forEach((r, i) => {
2111
- out(` ${ui.c.bold(`w${i + 1}`.padStart(3))}. ${r.line.trimStart()}`);
2112
- });
2113
- }
2114
- out();
2115
- out(ui.c.dim(' `sessions 2` reopens one from this run.'
2116
- + (recent.length ? ' `sessions w1` picks up earlier work.' : '')));
2117
- out();
2118
- break;
2119
- }
2120
- case 'status': {
2121
- const { cmdStatus } = await Promise.resolve().then(() => __importStar(require('./commands-thin')));
2122
- await cmdStatus();
2123
- break;
2124
- }
2125
- // The session being stood in, unless an id is typed after it. Asking
2126
- // the server for "the newest" here would answer about a different
2127
- // session the moment two are open, and this one is on the screen.
2128
- case 'cost':
2129
- case 'spend': {
2130
- // Nothing sent is nothing charged: the service answers even before
2131
- // the first job, so a refusal can be checked as costing nothing (6.1).
2132
- const { cmdCost } = await Promise.resolve().then(() => __importStar(require('./cost')));
2133
- await cmdCost([session.serverId || session.id]);
2134
- break;
2135
- }
2136
- case 'model': {
2137
- const { cmdModel } = await Promise.resolve().then(() => __importStar(require('./settings')));
2138
- await withTerminal(() => cmdModel([]));
2139
- break;
2140
- }
2141
- case 'providers': {
2142
- const { cmdProviders } = await Promise.resolve().then(() => __importStar(require('./settings')));
2143
- await cmdProviders();
2144
- break;
2145
- }
2146
- case 'voice':
2147
- // Returns without the redraw below: `speak` has drawn the prompt
2148
- // already, and has put the dictated words into it.
2149
- return speak();
2150
- case 'keys':
2151
- await withTerminal(() => (0, keys_1.cmdKeys)([]));
2152
- break;
2153
- // Signing out ends the session, because everything after it would be
2154
- // refused anyway. It used to answer "not available inside a session",
2155
- // which left quitting and running a second command as the only way.
2156
- case 'history':
2157
- // Every earlier question and answer in the session being stood in.
2158
- out();
2159
- await showConversation(session.serverId, true);
2160
- break;
2161
- case 'login': {
2162
- // Signing in again, or as somebody else, from inside a session. The
2163
- // session was opened with the old sign in, so it ends and the next
2164
- // `comprism` opens with the new one.
2165
- const { cmdLogin } = await Promise.resolve().then(() => __importStar(require('./login')));
2166
- const before = (0, connection_1.readConnection)()?.token;
2167
- await withTerminal(async () => {
2168
- // The Enter that sent `/login` is still in the terminal's input.
2169
- // Given a moment it goes to the session, not to the email question.
2170
- await new Promise((r) => setTimeout(r, 150));
2171
- // Anything already typed but not yet read is thrown away, so the
2172
- // first question waits for a real answer.
2173
- while (process.stdin.read() !== null) { /* discard */ }
2174
- await cmdLogin([]);
2175
- });
2176
- // Canceled or refused: nothing changed, so the session carries on.
2177
- if ((0, connection_1.readConnection)()?.token === before)
2178
- break;
2179
- out(ui.c.dim(` type ${ui.c.bold('comprism')} to start a session with this sign in`));
2180
- out();
2181
- return leave();
2182
- }
2183
- case 'logout':
2184
- case 'signout':
2185
- case 'disconnect': {
2186
- const { cmdDisconnect } = await Promise.resolve().then(() => __importStar(require('./commands-thin')));
2187
- await withTerminal(() => cmdDisconnect());
2188
- return leave();
2189
- }
2190
- default:
2191
- out(ui.c.dim(` \`${word}\` is not available inside a session.`));
2192
- out();
2193
- }
2194
- return prompt();
2195
- }
2196
- // `remote off` ends the link (manual 8.11).
2197
- if (/^\/?remote\s+off$/.test(word)) {
2198
- await remoteOff(session);
2199
- return prompt();
2200
- }
2201
- // `sessions 2` reopens the second one from this run.
2202
- const reopen = /^sessions\s+(\d+)$/.exec(word);
2203
- if (reopen) {
2204
- const target = history[Number(reopen[1]) - 1];
2205
- if (!target) {
2206
- out(ui.fail(`There is no session ${reopen[1]}.`));
2207
- }
2208
- else {
2209
- summarize(session);
2210
- session = target;
2211
- out(ui.ok(`Back in session ${ui.c.bold(session.id)}, ${session.jobs.length} job(s) so far.`));
2212
- }
2213
- out();
2214
- return prompt();
2215
- }
2216
- // `compact keep the requirement that ...` keeps those words exactly (6.15).
2217
- // Read off `typed`, because what to keep keeps its case.
2218
- const compactKeep = /^\/?compact\s+(.+)$/is.exec(typed);
2219
- if (compactKeep) {
2220
- await contextOf('compact', session.lastJobId, compactKeep[1].replace(/^keep\s+/i, '').trim());
2221
- return prompt();
2222
- }
2223
- // `cost <session>` breaks down a session other than the one being stood in.
2224
- // Read off `typed` rather than `word`, because `word` is lowercased so that
2225
- // command matching is forgiving, and a session id is not a word.
2226
- const costOf = /^\/?(?:cost|spend)\s+(\S+)$/i.exec(typed);
2227
- if (costOf) {
2228
- const { cmdCost } = await Promise.resolve().then(() => __importStar(require('./cost')));
2229
- await cmdCost([costOf[1]]);
2230
- return prompt();
2231
- }
2232
- // `sessions w1` picks up work from before this window was opened. A new
2233
- // session is started rather than an old one edited: what it inherits is the
2234
- // conversation, not the spending, and adding yesterday's cost to today's
2235
- // running total would make the session summary a wrong number.
2236
- const carryOn = /^sessions\s+w(\d+)$/.exec(word);
2237
- if (carryOn) {
2238
- if (recent.length === 0)
2239
- recent = await earlierSessions(history);
2240
- const target = recent[Number(carryOn[1]) - 1];
2241
- if (!target) {
2242
- out(ui.fail(`There is no earlier session w${carryOn[1]}. Type \`sessions\` for the list.`));
2243
- out();
2244
- return prompt();
2245
- }
2246
- // The same session, resumed: its conversation and its running cost carry
2247
- // on, and it never becomes a new session that has lost them (8.5).
2248
- summarize(session);
2249
- const found = await opening({ resume: target.number });
2250
- if (found) {
2251
- session = found;
2252
- history.push(session);
2253
- }
2254
- return prompt();
2255
- }
2256
- // A slash means "this is a command", so an unknown one is a typo and not a
2257
- // question. Sending it on would answer the typo and charge for the answer,
2258
- // which is exactly what `/model` used to do.
2259
- // A skill or saved command on the service's list is work for the agent,
2260
- // slash and all: the service expands it (chapter 9).
2261
- const isListed = () => Boolean(listed?.ok && listed.items.some((i) => i.source !== 'session' && i.name === word.split(/\s+/)[0]));
2262
- let offered = isListed();
2263
- if (slashed && !offered) {
2264
- // A skill written since the list was read is found by asking again,
2265
- // once, before the word is called a typo (manual 9.1, 9.2).
2266
- await refreshList();
2267
- offered = isListed();
2268
- }
2269
- if (slashed && !offered) {
2270
- out(ui.fail(`\`${typed}\` is not a command, so nothing ran and nothing was charged.`));
2271
- out(ui.c.dim(' Type `help` for the list, or ask without a slash to have work done.'));
2272
- out();
2273
- return prompt();
2274
- }
2275
- // EVERYTHING is work, and work means the agent.
2276
- //
2277
- // There used to be two paths: a question was answered by a model, and only
2278
- // an explicit build request reached the agent. A person who asked it to
2279
- // build them an application got a polite description of how they might do
2280
- // it themselves. The agent answers questions perfectly well and can also
2281
- // act, so the second path was never worth the confusion it caused.
2282
- const explicit = /^work\s+(.+)$/i.exec(typed);
2283
- const asked = explicit ? explicit[1] : typed;
2284
- const { text, ids, leftOut, send } = await gather(asked);
2285
- if (!send)
2286
- return prompt();
2287
- // Sent with this request, so no longer waiting for the next one.
2288
- pending = [];
2289
- try {
2290
- await build(session, text || asked, confirm, (controls) => { job = controls; cancelJob = controls.cancel; steerJob = controls.steer; }, ids, leftOut, askLine);
2291
- }
2292
- finally {
2293
- job = null;
2294
- cancelJob = null;
2295
- steerJob = null;
2296
- }
2297
- // A note that arrived after the last step is the next request (6.8).
2298
- queue.unshift(...view.late);
2299
- view.late = [];
2300
- prompt();
2301
- }
2302
- await finished;
2303
- }