@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,1232 +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
- Object.defineProperty(exports, "__esModule", { value: true });
36
- exports.TerminalSession = exports.waitingNextSteps = void 0;
37
- /**
38
- * A coding job, run from a terminal.
39
- *
40
- * Specification: docs/modules/CODING_AGENT_BUILD_SPECIFICATION.md, register
41
- * items A6 (interactive), A7 (scriptable), A10 and H6 (one job, any client),
42
- * C14 (resume) and D40 (a terminal the human can watch).
43
- *
44
- * ## What this file is, and what it is not
45
- *
46
- * It is the wire between a terminal and the loop, plus the rendering. **The loop
47
- * is not here.** Which model takes each step, what an action costs, whether an
48
- * action is allowed and what gets written down are all decided on the server,
49
- * exactly as they are for the browser. This connects, performs what it is asked,
50
- * prints what happened, and asks the person when the server says to.
51
- *
52
- * That is deliberate and it is the whole reason a terminal agent was cheap to
53
- * build at all: the second client reuses everything except the drawing.
54
- *
55
- * ## Two ways to run
56
- *
57
- * Interactive, with a person at the keyboard who can approve, interrupt and
58
- * steer. And headless, driven by a script with nobody present, where an
59
- * approval has no one to ask and the permission mode decides everything up
60
- * front. Both are the same session; the difference is who answers.
61
- */
62
- const gateway_1 = require("../lib/gateway");
63
- const fs = __importStar(require("fs"));
64
- const path = __importStar(require("path"));
65
- const readline = __importStar(require("readline"));
66
- const executor_1 = require("../machine/executor");
67
- const project_1 = require("../machine/folder/project");
68
- const ui = __importStar(require("./render"));
69
- const jobs_1 = require("../commands/jobs");
70
- /** The actions that change a file, whose change is shown as it is made. */
71
- const CHANGES = new Set(["edit_file", "multi_edit", "write_file"]);
72
- /** How many next steps the last job offered (web manual 13.4), so a bare number
73
- * typed next is sent to the service to run one rather than to the agent. */
74
- exports.waitingNextSteps = 0;
75
- /** Files with changes in Git as the job starts: the person's, not the agent's. */
76
- function dirtyFiles(root) {
77
- try {
78
- const { spawnSync } = require("child_process");
79
- const r = spawnSync("git", ["status", "--porcelain", "-uall"], { cwd: root, encoding: "utf8", timeout: 5000 });
80
- if (r.status !== 0)
81
- return [];
82
- return String(r.stdout).split("\n").filter(Boolean).map((l) => l.slice(3).split(" -> ").pop() ?? "")
83
- .filter(Boolean).slice(0, 500);
84
- }
85
- catch {
86
- return [];
87
- }
88
- }
89
- class TerminalSession {
90
- /** The VS Code window this terminal is inside, when there is one (VS Code manual 9.12). */
91
- editor = null;
92
- socket = null;
93
- executor;
94
- opts;
95
- out;
96
- lastTodos = "";
97
- /** The last thing it said on screen, so the ending does not say it twice.
98
- * Every step prints what the model said, and the closing frame carries the
99
- * final text again, so the answer to a one step job appeared twice in a row
100
- * with nothing between the copies. */
101
- lastSaid = "";
102
- canceled = false;
103
- /** The live "thinking 12s" line while the model works on a step. Drawn in
104
- * place and erased before anything else prints, so it never lands in the
105
- * answer. Without it a step is a blank screen for as long as the model takes,
106
- * and "thinking" and "hung" look identical. */
107
- working = null;
108
- /** When the current wait began, kept across the line being redrawn. Cleared
109
- * when a step finishes, so the next step counts from its own start. */
110
- workFrom = null;
111
- write;
112
- constructor(opts, write = (s) => process.stdout.write(s)) {
113
- this.opts = opts;
114
- this.write = write;
115
- this.out = (s) => { this.stopWorking(); write(s); };
116
- this.executor = new executor_1.NativeExecutor({
117
- root: opts.root,
118
- added: opts.project?.added ?? [],
119
- // Streamed straight through while a command runs. A build that takes two
120
- // minutes must not look like a hang, and the output is the only thing
121
- // that proves it is not.
122
- onOutput: (chunk) => {
123
- if (!opts.headless)
124
- this.stream(chunk);
125
- },
126
- });
127
- }
128
- /** Where the socket lives, derived from the workspace URL.
129
- *
130
- * Derived rather than configured: a second setting for the socket address is
131
- * a second thing that can point at the wrong server, and the failure would be
132
- * a job running against somebody else's workspace. */
133
- /**
134
- * A pass for this job's stream, from the one service.
135
- *
136
- * The job is authorized THERE, where everything else in the product is
137
- * authorized, and this returns only permission to open the stream. Null when
138
- * the service refused or could not be reached, and the caller then reports
139
- * the service's own words rather than guessing at them.
140
- */
141
- async pass(request) {
142
- const reply = await (0, gateway_1.ask)({
143
- intent: "job_start",
144
- prompt: request,
145
- ...(this.opts.resumeJobId ? { resumeJobId: this.opts.resumeJobId } : {}),
146
- });
147
- // An OLDER WORKSPACE that has never heard of this question is not a
148
- // refusal. Its own credential path is alive and works, so the job falls
149
- // back to it rather than stopping. This is the one place in the design
150
- // where a second path is permitted, it is temporary, and it is deleted in
151
- // the release after every workspace is known to be current.
152
- if (reply.served === false) {
153
- // Not a refusal. The workspace's own credential path is alive and works,
154
- // so the job proceeds on it rather than stopping. This is the one place
155
- // in the design where a second path is permitted, it is temporary, and it
156
- // goes in the release after every workspace is known to be current.
157
- this.olderWorkspace = true;
158
- return null;
159
- }
160
- if (!reply.ok || !reply.job?.ticket) {
161
- // A real refusal, in the service's own words: a plan that does not
162
- // include coding and an allowance that has been spent have different
163
- // fixes, and a caller told only "refused" looks in the wrong place.
164
- this.refusal = reply.message || "your organization could not be reached";
165
- // The reason word, for the exit number (Appendix B): the service's own
166
- // when it answered, else what the missing answer means.
167
- this.refusalReason = reply.reason
168
- ?? (reply.httpStatus === 401 ? "signed_out"
169
- : reply.ok || reply.httpStatus ? "incomplete" : "unreachable");
170
- this.refusalResult = reply.result ?? undefined;
171
- this.refusalTable = reply.exit_status ?? undefined;
172
- return null;
173
- }
174
- this.jobId = reply.job.job_id;
175
- if (process.env.COMPRISM_JOB_LOG && this.jobId)
176
- (0, jobs_1.notePointer)(this.jobId, process.env.COMPRISM_JOB_LOG);
177
- return { ticket: reply.job.ticket, jobId: reply.job.job_id };
178
- }
179
- /** Where the stream lives, derived from the workspace URL.
180
- *
181
- * Derived rather than configured: a second setting for the stream address is
182
- * a second thing that can point at the wrong server, and the failure would be
183
- * a job running against somebody else's workspace.
184
- *
185
- * The credential still travels because the pass is redeemed against the
186
- * tenant it was issued in, and the pass is what actually authorizes the job.
187
- * Without a pass this falls back to the old behavior, which is what a
188
- * workspace running an older build still understands. */
189
- socketUrl(ticket) {
190
- const url = new URL(this.opts.baseUrl);
191
- url.protocol = url.protocol === "https:" ? "wss:" : "ws:";
192
- url.pathname = "/api/v1/agent/ws";
193
- url.search = `?token=${encodeURIComponent(this.opts.credential)}`
194
- + (ticket ? `&ticket=${encodeURIComponent(ticket)}` : "");
195
- return url.toString();
196
- }
197
- /** The name the map is held under: the folder's own, which is exactly what
198
- * the run frame already sends as the workspace. One expression, so the map
199
- * and the job record can never be about two different projects. */
200
- project() {
201
- return this.opts.root.split("/").filter(Boolean).pop() || this.opts.root;
202
- }
203
- /** Connections lost during this job, so reconnecting gives up in the end. */
204
- drops = 0;
205
- /** Why the one service would not start this job, in its own words. */
206
- refusal = null;
207
- refusalReason;
208
- refusalResult;
209
- refusalTable;
210
- /** The workspace does not carry the permission question yet, so fall back. */
211
- olderWorkspace = false;
212
- /** Set while one is actually running, so two never overlap. */
213
- remapping = false;
214
- /**
215
- * The agent just changed something on disk. Bring the map back in step.
216
- *
217
- * Only for actions that can change a file. A read or a search leaves the
218
- * project exactly as it was, and re-reading it would be a round trip bought
219
- * for nothing on the most common actions there are.
220
- *
221
- * The refresh itself is the ordinary one: it compares the files against what
222
- * the service holds and sends back only what moved, which after one edit is
223
- * one file. Debounced by a short wait, because an agent that writes four
224
- * files in one step should pay for one update, not four.
225
- */
226
- async noteChanged(tool, input) {
227
- if (this.opts.withoutMap)
228
- return;
229
- // A named file changed, so exactly that file is put back into the map and
230
- // the result waits for it. One round trip, and the agent can ask about what
231
- // it just wrote in the very same step.
232
- const NAMES_ITS_FILE = new Set([
233
- "write_file", "edit_file", "multi_edit", "delete_file", "move_file",
234
- "write_bytes", "create_dir",
235
- ]);
236
- if (NAMES_ITS_FILE.has(tool)) {
237
- const a = (input ?? {});
238
- const paths = [a.path, a.file_path, a.from, a.to, a.destination]
239
- .filter((p) => typeof p === "string" && p.length > 0);
240
- const edits = Array.isArray(a.edits) ? a.edits : [];
241
- for (const e of edits) {
242
- const one = e?.path;
243
- if (typeof one === "string")
244
- paths.push(one);
245
- }
246
- if (paths.length) {
247
- const { pushFile } = await Promise.resolve().then(() => __importStar(require("../graph/sync")));
248
- await pushFile(this.opts.root, this.project(), [...new Set(paths)]);
249
- return;
250
- }
251
- }
252
- // A command, a patch or an install can change anything: a formatter, a code
253
- // generator, a package manager writing a lockfile. Nothing here knows what
254
- // it touched, so the whole project is re-checked rather than one file. That
255
- // is the comparison that costs milliseconds, and only the files that
256
- // actually moved are read.
257
- const CHANGES_SOMETHING = new Set([
258
- "apply_patch", "run_command", "run_background", "install_dependency",
259
- "run_tests", "git_branch", "git_commit",
260
- ]);
261
- if (CHANGES_SOMETHING.has(tool))
262
- await this.remap();
263
- }
264
- /**
265
- * Put the files this job changed back into the map.
266
- *
267
- * Runs after the job, without being waited on: the person has their answer
268
- * and a re-read of three files must not hold up their prompt. A failure here
269
- * costs nothing, because the next job checks the files anyway and would read
270
- * them then.
271
- */
272
- async remap() {
273
- if (this.opts.withoutMap || this.remapping)
274
- return;
275
- this.remapping = true;
276
- try {
277
- const { refresh } = await Promise.resolve().then(() => __importStar(require("../graph/sync")));
278
- await refresh(this.opts.root, this.project());
279
- }
280
- catch {
281
- /* the next check picks the files up anyway */
282
- }
283
- finally {
284
- this.remapping = false;
285
- }
286
- }
287
- /** Run one request to its end. Resolves with how it went. */
288
- async run(request) {
289
- const result = {
290
- outcome: "failed", steps: 0, actions: 0, totalUsd: 0, savedUsd: null,
291
- receipt: "", models: [], text: "", todos: [], lateNotes: [],
292
- };
293
- // ── the map of this project, brought up to date first ──────────────────
294
- //
295
- // Before the job, not after it, because the whole saving is the agent
296
- // knowing the shape of the codebase instead of reading forty files to work
297
- // it out. A map read afterwards would have cost the money it exists to
298
- // save.
299
- //
300
- // Only what MOVED is read. An unchanged project costs about ten
301
- // milliseconds here, which is the check itself; a few changed files cost a
302
- // fraction of a second. Nothing about this can stop the job: a service that
303
- // cannot be reached, a company that has switched the map off, and a machine
304
- // with no parser all end the same way, with the agent reading files the
305
- // way every other coding tool does all of the time.
306
- if (!this.opts.withoutMap) {
307
- try {
308
- const { refresh, status } = await Promise.resolve().then(() => __importStar(require("../graph/sync")));
309
- const now = await status(this.opts.root, this.project());
310
- if (now.enabled && !now.hasMap) {
311
- // FIRST TIME IN THIS PROJECT: read it, but do not make anybody wait.
312
- //
313
- // A first read of a large project is minutes, because every file has
314
- // to be parsed and its structure sent. Waiting for that before the
315
- // job starts would make somebody's first experience of the product a
316
- // long pause for a feature they did not ask for, to save money on a
317
- // job they have not started. So the job runs now, reading files the
318
- // ordinary way, and the second job in this project has the map.
319
- this.out(ui.dim(" reading a map of this workspace in the background;"
320
- + " your next job here will use it\n"));
321
- void refresh(this.opts.root, this.project()).catch(() => undefined);
322
- }
323
- else if (now.enabled && !now.fresh) {
324
- // A map already exists and some files moved. Only those are read,
325
- // which is a fraction of a second, and it is worth waiting for:
326
- // answering this job from a map that is behind the files is the one
327
- // failure this whole feature has to avoid.
328
- const done = await refresh(this.opts.root, this.project());
329
- if (done.filesRead)
330
- this.out(ui.dim(` code map: ${done.message}\n`));
331
- }
332
- }
333
- catch {
334
- /* the map is an optimization; never a reason a job does not start */
335
- }
336
- }
337
- // Permission first, from the one service. The stream opens only once the
338
- // job has been authorized there, so this socket carries no decision of its
339
- // own and the workspace credential is no longer the thing that opens it.
340
- // Joined to VS Code when run in its terminal (VS Code manual 9.12): the
341
- // window's selection goes with the request, and proposed changes open in
342
- // its diff view. CompletionPrism's own connection; no other tool's.
343
- if (!this.opts.headless) {
344
- const { findEditor, selectionText } = await Promise.resolve().then(() => __importStar(require("../lib/ide")));
345
- this.editor = findEditor(this.opts.root);
346
- if (this.editor) {
347
- this.out(ui.dim(" Connected to VS Code\n"));
348
- request += selectionText(await this.editor.context());
349
- }
350
- }
351
- // Working from the moment the request leaves, not from the moment the
352
- // model starts. The pass, the stream and the service's own preparation
353
- // take several seconds before the first step, and a blank screen for that
354
- // long reads as nothing happening. The service's words replace this as
355
- // soon as its first step starts.
356
- this.workFrom = null;
357
- this.startWorking("thinking");
358
- const granted = await this.pass(request);
359
- if (this.olderWorkspace) {
360
- // Straight on to the stream with the credential, silently. A person does
361
- // not need to be told their workspace is a release behind when the thing
362
- // they asked for is about to happen anyway.
363
- this.refusal = null;
364
- }
365
- else if (!granted && this.refusal) {
366
- // A refusal is an ANSWER, not a failure to connect. It carries the
367
- // service's own wording, because a plan that does not include coding and
368
- // an allowance that has been spent have different fixes.
369
- result.detail = this.refusal;
370
- result.refusalReason = this.refusalReason;
371
- if (this.refusalResult)
372
- result.result = this.refusalResult;
373
- if (this.refusalTable)
374
- result.exitStatus = this.refusalTable;
375
- this.out(ui.red(` ${this.refusal}\n`));
376
- return result;
377
- }
378
- // What this machine did for the job, by action id: received, then done
379
- // with its result. Sent back after a dropped connection so the service can
380
- // match it, which is how nothing is ever done twice (manual 8.9).
381
- const journal = new Map();
382
- let finished = false;
383
- await new Promise((resolve, reject) => {
384
- const open = (ticket, first) => {
385
- const socket = new WebSocket(this.socketUrl(ticket));
386
- this.socket = socket;
387
- let ready = false;
388
- socket.onopen = () => {
389
- socket.send(JSON.stringify({
390
- type: "hello",
391
- client: this.opts.headless ? "cli-headless" : "cli",
392
- // `ask_user` says a person is here to answer questions (manual
393
- // 4.3). Unattended, it is left out and the service tells the agent to
394
- // choose the safest option instead.
395
- // `reattach`: this tool reconnects after a drop, so the service
396
- // holds the job for it rather than ending it (manual 8.9).
397
- capabilities: this.opts.headless
398
- ? [...this.executor.capabilities, "reattach"]
399
- : [...this.executor.capabilities, "ask_user", "reattach"],
400
- }));
401
- };
402
- socket.onmessage = async (event) => {
403
- let frame;
404
- try {
405
- frame = JSON.parse(String(event.data));
406
- }
407
- catch {
408
- return;
409
- }
410
- if (frame.type === "ready" && !ready) {
411
- ready = true;
412
- if (!first) {
413
- // Back after a drop: what this machine did, for the service to match.
414
- socket.send(JSON.stringify({
415
- type: "reattach", job_id: this.jobId, journal: [...journal.values()],
416
- }));
417
- return;
418
- }
419
- this.announce(frame);
420
- socket.send(JSON.stringify({
421
- type: this.opts.resumeJobId ? "resume" : "run",
422
- job_id: this.opts.resumeJobId,
423
- continues_job: this.opts.continuesJob,
424
- conversation_id: this.opts.conversationId,
425
- request,
426
- workspace: this.opts.root.split("/").pop(),
427
- workspace_source: "local",
428
- workspace_root: this.opts.root,
429
- ...(this.opts.project ? (0, project_1.asWire)(this.opts.project) : {}),
430
- client: process.env.COMPRISM_BACKGROUND === "1" ? "cli-background"
431
- : this.opts.headless ? "cli-headless" : "cli",
432
- // Absent when not chosen: the service takes it from the settings.
433
- permission_mode: this.opts.permissionMode,
434
- plan_only: Boolean(this.opts.planOnly),
435
- plan_approved: Boolean(this.opts.planApproved),
436
- model: this.opts.model,
437
- pin_model: Boolean(this.opts.pinModel),
438
- max_spend_usd: this.opts.maxSpendUsd,
439
- ...(this.opts.maxSteps ? { max_steps: this.opts.maxSteps } : {}),
440
- ...(this.opts.maxMinutes ? { max_minutes: this.opts.maxMinutes } : {}),
441
- ...(this.opts.effort ? { effort: this.opts.effort } : {}),
442
- sandbox: Boolean(this.opts.sandbox),
443
- // Which sandbox this machine can offer, so the service can turn it
444
- // on from settings too, or refuse when it cannot (manual 4.12).
445
- sandbox_system: this.sandboxSystem(),
446
- command_timeout_s: this.opts.commandTimeoutS,
447
- ...(this.opts.issue ? { issue: this.opts.issue } : {}),
448
- ...(this.opts.team ? { team: this.opts.team } : {}),
449
- ...(this.opts.review ? { review: this.opts.review } : {}),
450
- approved_commands: this.opts.approvedCommands ?? [],
451
- attachments: this.opts.attachmentIds ?? [],
452
- left_out: this.opts.leftOut ?? [],
453
- without_graph: Boolean(this.opts.withoutMap),
454
- ...(this.opts.answerSchema ? { answer_schema: this.opts.answerSchema } : {}),
455
- ...(this.opts.settingsConfig ? { settings_config: this.opts.settingsConfig } : {}),
456
- ...(this.opts.noPersonal ? { no_personal: true } : {}),
457
- ...(this.opts.queuedJob ? { queued_job: this.opts.queuedJob } : {}),
458
- // Files already changed before the job, so they are never counted
459
- // as the agent's (manual 7.1).
460
- dirty_files: dirtyFiles(this.opts.root),
461
- // Which system runs the commands, so the agent writes for its shell
462
- // (manual 1.2): PowerShell on Windows.
463
- machine_os: process.platform,
464
- }));
465
- return;
466
- }
467
- if (frame.type === "tool_call") {
468
- const id = String(frame.id);
469
- const seen = journal.get(id);
470
- if (seen?.state === "done") {
471
- // Sent again after a drop, but already carried out here: the
472
- // result is sent, the action is not repeated.
473
- this.socket?.send(JSON.stringify({ type: "tool_result", id, ...seen.result }));
474
- return;
475
- }
476
- if (seen)
477
- return;
478
- const input = frame.input ?? {};
479
- const target = String(input.path ?? input.file_path ?? input.command ?? "");
480
- // An approved action is checked against what the person approved
481
- // immediately before it runs: the same action, the same arguments,
482
- // the same folder (manual 4.8). Anything changed does not run.
483
- const approved = this.approvedCalls.get(id);
484
- if (approved !== undefined && approved !== this.fingerprint(String(frame.name), input)) {
485
- const refused = {
486
- content: "This action changed after it was approved (a different command, "
487
- + "argument or folder), so it did not run. Ask again for the new one.",
488
- is_error: true, summary: "changed after approval; not run",
489
- };
490
- this.socket?.send(JSON.stringify({ type: "tool_result", id, ...refused }));
491
- return;
492
- }
493
- journal.set(id, { id, name: String(frame.name), target, state: "running" });
494
- // The hooks the service named for this action (manual 10.9).
495
- const plan = frame.hooks && typeof frame.hooks === "object"
496
- ? frame.hooks : undefined;
497
- const r = await this.executor.execute(String(frame.name), input, plan);
498
- // THE MAP IS CAUGHT UP BEFORE THE RESULT GOES BACK.
499
- //
500
- // Before, not after, and that ordering is the whole of it. The server
501
- // runs a step's actions one after another, so an agent that writes a
502
- // file and then asks the map about it does both inside one step. A
503
- // refresh started after this result is sent has not finished when the
504
- // question runs, and the agent is told the thing it just wrote does
505
- // not exist. Measured on a real job before this line existed.
506
- if (!r.isError)
507
- await this.noteChanged(String(frame.name), frame.input);
508
- const answer = {
509
- content: r.content, is_error: Boolean(r.isError), summary: r.summary,
510
- facts: r.facts,
511
- };
512
- journal.set(id, { id, name: String(frame.name), target, state: "done", result: answer });
513
- // On whichever connection is open now. If none is, the journal holds
514
- // the result until the service asks for it.
515
- if (this.socket?.readyState === WebSocket.OPEN) {
516
- this.socket.send(JSON.stringify({ type: "tool_result", id, ...answer }));
517
- }
518
- return;
519
- }
520
- if (frame.type === "approval_ask") {
521
- const callId = String(frame.call_id ?? frame.action_id ?? "");
522
- this.asked.add(callId);
523
- const input = frame.input ?? {};
524
- // Answered in the browser while this terminal waits (web manual 6.15):
525
- // the service already has the answer, so none is sent from here.
526
- const remote = new Promise((resolve) => {
527
- this.answeredElsewhere.set(String(frame.id), () => resolve("remote"));
528
- });
529
- if (this.editor && ["write_file", "edit_file", "multi_edit"].includes(String(frame.name))) {
530
- void this.editor.diff(String(frame.name), input);
531
- }
532
- const local = this.ask(String(frame.name), input, String(frame.prompt ?? ""));
533
- const first = await Promise.race([local, remote]);
534
- this.answeredElsewhere.delete(String(frame.id));
535
- if (first === "remote")
536
- return;
537
- const answer = first;
538
- // The words go to the service, which decides what they mean (4.7 to
539
- // 4.9). `granted` is kept for a service that reads only yes or no.
540
- const word = (answer ?? "").trim().toLowerCase();
541
- const granted = word === "y" || word === "yes" || word === "a";
542
- if (granted)
543
- this.approvedCalls.set(callId, this.fingerprint(String(frame.name), input));
544
- this.socket?.send(JSON.stringify(answer === null
545
- ? { type: "approval_reply", id: frame.id, granted: false, cancelled: true } // american-english-allowed: the service's field name
546
- : { type: "approval_reply", id: frame.id, granted, answer,
547
- // Nobody at the keyboard: the service records it as an approval
548
- // nobody could give (manual 10.1, exit 4).
549
- ...(this.opts.headless ? { unattended: true } : {}) }));
550
- if (answer === null)
551
- this.cancel();
552
- return;
553
- }
554
- if (frame.type === "question") {
555
- const answer = await this.question(frame);
556
- this.socket?.send(JSON.stringify(answer === null
557
- ? { type: "question_reply", id: frame.id, cancelled: true } // american-english-allowed: the service's field name
558
- : { type: "question_reply", id: frame.id, answer }));
559
- if (answer === null)
560
- this.cancel();
561
- return;
562
- }
563
- if (frame.type === "event" && frame.kind === "approval_answered") {
564
- const done = this.answeredElsewhere.get(String(frame.id));
565
- if (done) {
566
- this.out(ui.dim(`\n ${String(frame.line ?? "answered in the browser")}\n`));
567
- done();
568
- }
569
- return;
570
- }
571
- if (frame.type === "event" && frame.kind === "sandbox") {
572
- // The service turned the sandbox on for this job: every command from
573
- // here runs inside it, with its allowed addresses (manual 4.12).
574
- const { Sandbox } = await Promise.resolve().then(() => __importStar(require("../machine/executor/sandbox")));
575
- const system = this.sandboxSystem();
576
- if (system) {
577
- const box = new Sandbox(system, this.opts.root, this.opts.project?.added ?? []);
578
- box.setAllowed(Array.isArray(frame.allow) ? frame.allow : []);
579
- await box.start();
580
- this.executor.sandbox = box;
581
- }
582
- this.out(ui.yellow(` ${String(frame.line ?? "")}`) + "\n");
583
- return;
584
- }
585
- if (frame.type === "event") {
586
- // The published stream lines the service attached (manual 10.4).
587
- if (this.opts.onStream && Array.isArray(frame.stream) && frame.stream.length) {
588
- this.opts.onStream(frame.stream);
589
- }
590
- // The session's name, pushed by the service as soon as it exists, is
591
- // shown as the terminal window's title, where it never interrupts
592
- // the answer being printed.
593
- if (frame.kind === "session_named" && typeof frame.title === "string"
594
- && frame.title && process.stdout.isTTY) {
595
- process.stdout.write(`\x1b]0;${frame.title.replace(/[\x00-\x1f\x7f]/g, "")}\x07`);
596
- }
597
- if (frame.kind === "job_opened" && frame.job_id) {
598
- this.jobId = String(frame.job_id);
599
- // A background job notes where its log is, for `jobs attach` (5.14).
600
- if (process.env.COMPRISM_JOB_LOG)
601
- (0, jobs_1.notePointer)(this.jobId, process.env.COMPRISM_JOB_LOG);
602
- }
603
- // The service recorded this action, so it is settled either way.
604
- if (frame.kind === "action_finished" && frame.id) {
605
- const j = journal.get(String(frame.id));
606
- if (j)
607
- j.confirmed = true;
608
- }
609
- if (frame.kind === "reconciled") {
610
- // The service's own report of what was matched (manual 8.9).
611
- for (const line of frame.lines ?? []) {
612
- this.out(` ${line}\n`);
613
- }
614
- this.out("\n");
615
- return;
616
- }
617
- this.narrate(frame);
618
- return;
619
- }
620
- if (frame.type === "done") {
621
- finished = true;
622
- if (this.opts.onStream && Array.isArray(frame.stream)) {
623
- this.opts.onStream(frame.stream);
624
- }
625
- result.outcome = String(frame.outcome ?? "failed");
626
- result.detail = frame.detail ?? null;
627
- result.jobId = frame.job_id;
628
- result.steps = Number(frame.steps ?? 0);
629
- result.actions = Number(frame.actions ?? 0);
630
- result.totalUsd = Number(frame.total_usd ?? 0);
631
- // The saving is the server's arithmetic, taken as it is sent. A
632
- // client that subtracted its own would disagree with the stored
633
- // receipt within a release, and the stored one is the record.
634
- {
635
- const economics = frame.economics;
636
- const saved = economics?.saved_usd;
637
- result.savedUsd = typeof saved === "number" ? saved : null;
638
- const rows = economics?.models;
639
- result.models = Array.isArray(rows) ? rows : [];
640
- }
641
- // The sentence the server wrote. Everything a reader is told about
642
- // cost and saving comes from here.
643
- result.receipt = String(frame.receipt ?? "");
644
- result.card = frame.card ?? null;
645
- result.nextSteps = Array.isArray(frame.next_steps_lines)
646
- ? frame.next_steps_lines.map(String) : [];
647
- exports.waitingNextSteps = Array.isArray(frame.next_steps) ? frame.next_steps.length : 0;
648
- result.reusedPct = ui.reusePct(0, frame.cached_tokens, Math.max(0, Number(frame.context_tokens ?? 0) - Number(frame.cached_tokens ?? 0)));
649
- result.text = String(frame.text ?? "");
650
- result.why = this.lastWhy;
651
- result.todos = Array.isArray(frame.todos)
652
- ? frame.todos : [];
653
- if (frame.result && typeof frame.result === "object") {
654
- result.result = frame.result;
655
- }
656
- if (frame.exit_status && typeof frame.exit_status === "object") {
657
- result.exitStatus = frame.exit_status;
658
- }
659
- result.lateNotes = Array.isArray(frame.late_notes)
660
- ? frame.late_notes.map(String) : [];
661
- {
662
- const ending = frame.ending;
663
- if (ending && typeof ending === "object") {
664
- result.ending = {
665
- line: typeof ending.line === "string" ? ending.line : null,
666
- proof: Array.isArray(ending.proof) ? ending.proof.map(String) : [],
667
- exit: typeof ending.exit === "number" ? ending.exit : null,
668
- ...(typeof ending.reason === "string" ? { reason: ending.reason } : {}),
669
- };
670
- result.testsPassed = typeof ending.tests_passed === "boolean"
671
- ? ending.tests_passed : undefined;
672
- }
673
- else {
674
- result.testsPassed = this.executor.lastTestsPassed;
675
- }
676
- }
677
- // What the agent itself changed goes back into the map before the
678
- // next job asks anything. Without this the second job of a session
679
- // works from a picture of the code as it was before the first job
680
- // edited it, which is the exact failure the freshness rule exists to
681
- // prevent, and the most likely one: the agent that made the map stale
682
- // is the agent about to trust it.
683
- void this.remap();
684
- socket.close();
685
- return;
686
- }
687
- if (frame.type === "error") {
688
- this.out(ui.red(`\n ${String(frame.message ?? "Something went wrong.")}\n`));
689
- }
690
- };
691
- socket.onerror = () => {
692
- // Say what actually failed.
693
- //
694
- // This used to read "Check you are signed in", on a screen that had
695
- // just printed the person's own email, their company and their plan,
696
- // all of which came from the very server it claimed it could not reach.
697
- // Being told to do the one thing you have visibly already done sends
698
- // somebody to sign in again, which fixes nothing and costs an evening.
699
- //
700
- // By the time this fires the credential has already been accepted: the
701
- // job was authorized and the server issued a pass for it. What failed
702
- // is the live connection that carries the work, and the wording names
703
- // that instead.
704
- if (!ready && first) {
705
- reject(new Error("The live connection to your organization could not be opened. "
706
- + "You are signed in; the work stream is what failed."));
707
- }
708
- };
709
- socket.onclose = () => {
710
- if (socket !== this.socket)
711
- return;
712
- this.stopWorking();
713
- if (finished || this.canceled || !this.jobId) {
714
- // One job on its own is its session, so what it started ends with it
715
- // and is listed (manual 5.13). Inside a session they carry on.
716
- if (!this.opts.keepProcesses)
717
- this.out(ui.stoppedLines((0, executor_1.stopEverything)()));
718
- // The job's browser closes with it (manual 10.16).
719
- this.executor.close();
720
- // Tool servers on this machine end with the job (manual 9.10).
721
- this.executor.toolServers.stopAll();
722
- resolve();
723
- return;
724
- }
725
- // Dropped mid job. Nothing running here is stopped: an action already
726
- // under way finishes and its result waits in the journal.
727
- this.drops += 1;
728
- if (first || ready)
729
- this.out(ui.yellow("\n The connection dropped. Reconnecting...\n"));
730
- void (this.drops > 6 ? Promise.resolve(null) : this.reconnect()).then((ticket) => {
731
- if (ticket !== null) {
732
- open(ticket, false);
733
- return;
734
- }
735
- // The service could not be reached again. What this machine knows,
736
- // said plainly; nothing is repeated (manual 8.9, exit 7).
737
- this.out(" The connection dropped and could not be restored.\n");
738
- for (const j of [...journal.values()].filter((e) => !e.confirmed)) {
739
- this.out(j.state === "done"
740
- ? ` done ${j.name} ${j.target} (done here; the service has not confirmed it)\n`
741
- : ` unknown ${j.name} ${j.target} (it may or may not have finished)\n`);
742
- }
743
- this.out(" Not repeated. Check the result, then tell the agent what happened.\n");
744
- result.outcome = "unknown";
745
- result.jobId = this.jobId;
746
- // Nobody can receive a result now, so a command still running here
747
- // is stopped rather than left to finish unseen.
748
- (0, executor_1.stopForeground)();
749
- (0, executor_1.stopEverything)();
750
- this.executor.toolServers.stopAll();
751
- resolve();
752
- });
753
- };
754
- };
755
- open(granted?.ticket, true);
756
- });
757
- this.report(result);
758
- return result;
759
- }
760
- /**
761
- * A pass to rejoin this job after a dropped connection, trying for about
762
- * half a minute, inside the service's window (manual 8.9). Null when the
763
- * service could not be reached again, or refused.
764
- */
765
- async reconnect() {
766
- for (const wait of [1000, 2000, 3000, 5000, 8000, 10000]) {
767
- await new Promise((r) => setTimeout(r, wait));
768
- if (this.canceled)
769
- return null;
770
- const reply = await (0, gateway_1.ask)({ intent: "job_start", prompt: "", resumeJobId: this.jobId });
771
- if (reply.served === false)
772
- return undefined;
773
- if (reply.ok && reply.job?.ticket)
774
- return reply.job.ticket;
775
- if (reply.ok && reply.granted === false)
776
- return null;
777
- }
778
- return null;
779
- }
780
- /** Stop the running job. Takes effect mid action, not at the end of the run:
781
- * a command already running on this machine is stopped too (manual 6.7). */
782
- cancel() {
783
- if (this.canceled)
784
- return;
785
- this.canceled = true;
786
- this.paused = false;
787
- this.out(ui.yellow("\n stopping...\n"));
788
- this.socket?.send(JSON.stringify({ type: "cancel" }));
789
- (0, executor_1.stopForeground)();
790
- }
791
- /** Something typed while it works. Joins the conversation at the next step;
792
- * the service says so in the `note` event it sends back (6.8). */
793
- steer(text) {
794
- this.socket?.send(JSON.stringify({ type: "steer", text }));
795
- }
796
- /** Esc: finish the current action, then wait (manual 6.7). */
797
- pause() {
798
- if (this.canceled || this.paused)
799
- return;
800
- this.paused = true;
801
- this.socket?.send(JSON.stringify({ type: "pause" }));
802
- }
803
- /** Carry on after Esc, with a correction or without one. */
804
- carryOn(text) {
805
- this.paused = false;
806
- this.socket?.send(JSON.stringify({ type: "carry_on", text }));
807
- }
808
- /** This job's id, once the service has issued it (`transcript`, 6.9). */
809
- jobId;
810
- /** Set from Esc until the job carries on or stops. */
811
- paused = false;
812
- /** Helpers running now, from the service's own events (manual 5.25). */
813
- helpers = new Map();
814
- /** `stop h2` (5.25): the service stops that one helper. */
815
- stopHelper(id) {
816
- this.socket?.send(JSON.stringify({ type: "stop_helper", helper: id }));
817
- }
818
- /** `queue` and `queue clear` (6.8): the service answers with the notes. */
819
- queue(clear) {
820
- this.socket?.send(JSON.stringify({ type: clear ? "queue_clear" : "queue" }));
821
- }
822
- /** Ctrl+O: each action's full input and output, or the short line (6.9). */
823
- full = false;
824
- announce(frame) {
825
- const allowance = frame.allowance;
826
- // The project, company and mode are the service's first line, printed when
827
- // it arrives (manual 2.2). The allowance follows it.
828
- if (allowance && allowance.included && !allowance.unlimited) {
829
- this.allowanceLine = ui.dim(` coding allowance left this month: ${ui.money(Number(allowance.remaining_usd))}\n`);
830
- }
831
- }
832
- /** The allowance and plan notes, printed under the first line so it stays first. */
833
- allowanceLine = "";
834
- /** A running command's output on screen (manual 5.12): the first lines as
835
- * they arrive, then held, and at the end either the rest or the last lines
836
- * with a count of what was left out. How many is the service's number. */
837
- screen = { limit: 0, edge: 0, shown: 0, held: [], partial: "" };
838
- stream(chunk) {
839
- const sc = this.screen;
840
- if (!sc.limit) {
841
- this.out(ui.gray(chunk));
842
- return;
843
- }
844
- const parts = (sc.partial + chunk).split("\n");
845
- sc.partial = parts.pop() ?? "";
846
- for (const line of parts) {
847
- if (sc.shown < sc.edge) {
848
- this.out(ui.gray(`${line}\n`));
849
- sc.shown += 1;
850
- }
851
- else
852
- sc.held.push(line);
853
- }
854
- }
855
- flushScreen() {
856
- const sc = this.screen;
857
- if (!sc.limit)
858
- return;
859
- if (sc.partial) {
860
- sc.held.push(sc.partial);
861
- sc.partial = "";
862
- }
863
- const room = sc.limit - sc.edge;
864
- const show = sc.held.length <= room ? sc.held : sc.held.slice(-sc.edge);
865
- const left = sc.held.length - show.length;
866
- if (left > 0)
867
- this.out(ui.dim(` ... ${left.toLocaleString()} lines not shown ...\n`));
868
- for (const line of show)
869
- this.out(ui.gray(`${line}\n`));
870
- this.screen = { limit: 0, edge: 0, shown: 0, held: [], partial: "" };
871
- }
872
- /** Changes already put in front of the person to approve, so they are not
873
- * shown twice. Every other change is shown as it is made (5.6 to 5.8). */
874
- asked = new Set();
875
- /** The sandbox this machine offers, worked out once (manual 4.12). */
876
- sandboxChecked;
877
- sandboxSystem() {
878
- if (this.sandboxChecked === undefined) {
879
- // eslint-disable-next-line @typescript-eslint/no-var-requires
880
- const { availability } = require("../machine/executor/sandbox");
881
- this.sandboxChecked = availability().system;
882
- }
883
- return (this.sandboxChecked ?? null);
884
- }
885
- /** The full reason for the last step, as the service wrote it (4.16). */
886
- lastWhy = [];
887
- /** An unattended run refused an action that needed approval (Appendix B, 4). */
888
- refusedUnattended = false;
889
- /** Approved actions by call, and what exactly was approved (manual 4.8). */
890
- approvedCalls = new Map();
891
- /** Approvals waiting here that the browser may answer first (web manual 6.15). */
892
- answeredElsewhere = new Map();
893
- /** An action as approved: its name, its arguments and the real folder it
894
- * runs in, so a changed argument or a moved folder is caught. */
895
- fingerprint(name, input) {
896
- const pathMod = path;
897
- const fsMod = fs;
898
- let folder = this.opts.root;
899
- if (typeof input.cwd === "string" && input.cwd)
900
- folder = pathMod.resolve(this.opts.root, input.cwd);
901
- try {
902
- folder = fsMod.realpathSync(folder);
903
- }
904
- catch { /* the folder is gone: still compared */ }
905
- const sorted = (v) => (v && typeof v === "object" && !Array.isArray(v)
906
- ? Object.fromEntries(Object.keys(v).sort().map((k) => [k, sorted(v[k])]))
907
- : v);
908
- return JSON.stringify([name, sorted(input), folder]);
909
- }
910
- /** Starts the working line with the service's own words. Only on a real
911
- * terminal: a piped or unattended run gets the answer and nothing else. */
912
- startWorking(line) {
913
- this.stopWorking();
914
- if (!line || this.opts.headless || !process.stdout.isTTY)
915
- return;
916
- // One count for one wait: the service's words taking over from the
917
- // request's own do not start the clock again.
918
- const started = this.workFrom ??= Date.now();
919
- const draw = () => this.write(`\r\x1b[2K ${ui.dim(`${line} ${ui.duration(Date.now() - started)}`)}`);
920
- draw();
921
- const timer = setInterval(draw, 1000);
922
- timer.unref?.();
923
- this.working = { timer };
924
- }
925
- stopWorking() {
926
- if (!this.working)
927
- return;
928
- clearInterval(this.working.timer);
929
- this.working = null;
930
- this.write("\r\x1b[2K");
931
- }
932
- narrate(frame) {
933
- switch (frame.kind) {
934
- // The model is working on a step. Shown at once, so the wait is visibly
935
- // work (the web app draws the same moment as its "thinking" row).
936
- case "step_started":
937
- this.startWorking(String(frame.line ?? ""));
938
- break;
939
- // Helpers, in the service's words (manual 5.23, 5.25).
940
- case "helper_started":
941
- this.helpers.set(String(frame.id), {
942
- id: String(frame.id), question: String(frame.question ?? ""),
943
- agent: frame.agent ?? null,
944
- });
945
- this.out(` ${ui.bold(String(frame.id))} ${String(frame.line ?? "")}\n`);
946
- break;
947
- case "helper_finished":
948
- this.helpers.delete(String(frame.id));
949
- this.out(ui.dim(` ${String(frame.line ?? "")}\n`));
950
- if (frame.used_line)
951
- this.out(ui.dim(` ${String(frame.used_line)}\n`));
952
- break;
953
- // A skill the job follows, in the service's words (manual 9.2, 9.5).
954
- case "skill_used":
955
- case "skill_file":
956
- if (frame.line)
957
- this.out((frame.ok === false ? ui.red : ui.dim)(` ${String(frame.line)}\n`));
958
- break;
959
- case "team":
960
- this.out((frame.ok === false ? ui.red : ui.bold)(` ${String(frame.line ?? "")}`) + "\n");
961
- break;
962
- case "helper_conflict":
963
- this.out(ui.red(` ${String(frame.line ?? "")}\n`));
964
- if (frame.diff)
965
- this.out(ui.dim(String(frame.diff).split("\n").map((l) => ` ${l}`).join("\n") + "\n"));
966
- break;
967
- case "helper_stopping":
968
- this.out(ui.dim(` ${String(frame.line ?? "")}\n`));
969
- break;
970
- case "action_started":
971
- this.flushScreen();
972
- if (typeof frame.screen_lines === "number" && typeof frame.screen_edge === "number") {
973
- this.screen = { limit: frame.screen_lines, edge: frame.screen_edge, shown: 0, held: [], partial: "" };
974
- }
975
- break;
976
- // The first line of the job, exactly as the service wrote it.
977
- case "project_line":
978
- this.out(`${ui.bold(String(frame.line ?? ""))}\n`);
979
- if (this.allowanceLine)
980
- this.out(this.allowanceLine);
981
- this.allowanceLine = "";
982
- // Still working: the first step has not started yet.
983
- this.startWorking("thinking");
984
- break;
985
- // Planning and plan approval, in the service's words (manual 4.1, 4.2).
986
- case "planning":
987
- this.out(ui.yellow(` ${String(frame.line ?? "")}`) + "\n");
988
- break;
989
- // A warning the service wants on screen, in its words (manual 4.13).
990
- case "notice":
991
- this.out(ui.yellow(` ${String(frame.line ?? "")}`) + "\n");
992
- break;
993
- case "plan_approved":
994
- this.out(ui.dim(` ${String(frame.reason ?? "")}\n`));
995
- break;
996
- case "step_finished": {
997
- this.workFrom = null;
998
- this.out(ui.step(Number(frame.index ?? 0), String(frame.model ?? ""), frame.usd, frame.latency_ms, ui.reusePct(frame.tokens_in, frame.cache_read_tokens, frame.cache_write_tokens), String(frame.reason ?? "")) + "\n");
999
- if (Array.isArray(frame.why_lines))
1000
- this.lastWhy = frame.why_lines;
1001
- const said = String(frame.text ?? "").trim();
1002
- // Markdown is for a browser. A terminal shows the asterisks.
1003
- if (said) {
1004
- // The plan is titled so it reads as the plan (manual 4.1).
1005
- const plan = ui.plain(said.replace(/^\s*(#+\s*)?\**plan\**:?\s*\n/i, ""));
1006
- this.out(frame.plan ? ` ${ui.bold("Plan")}\n${plan}\n` : `\n${ui.plain(said)}\n`);
1007
- this.lastSaid = said;
1008
- }
1009
- break;
1010
- }
1011
- case "action_finished":
1012
- this.flushScreen();
1013
- // A step that failed is the agent's to read and retry, not the
1014
- // person's: it is not printed, outside the full view (6.9) that a
1015
- // person turns on to see everything (owner, 7 October 2026).
1016
- if (frame.ok === false && !this.full)
1017
- break;
1018
- this.out(ui.action(String(frame.name ?? ""), this.targetOf(frame), frame.ok !== false, frame.latency_ms) + "\n");
1019
- // The change itself, as it is made, unless it was just shown for
1020
- // approval (manual 5.6 to 5.8). A change that changed nothing has
1021
- // nothing to show.
1022
- if (frame.ok !== false && !this.full && CHANGES.has(String(frame.name))
1023
- && !this.asked.has(String(frame.id)) && !/ no change$/.test(String(frame.target ?? ""))) {
1024
- this.out(ui.diff(String(frame.name), frame.input ?? {}, false));
1025
- }
1026
- // The full view: exactly what went in and what came back (6.9).
1027
- if (this.full) {
1028
- this.out(ui.dim(` input ${JSON.stringify(frame.input ?? {})}\n`));
1029
- const got = String(frame.output ?? frame.summary ?? "");
1030
- this.out(ui.dim(` output\n${got.split("\n").map((l) => ` ${l}`).join("\n")}\n`));
1031
- }
1032
- // A refused or failed action says why, with the path (manual 2.4).
1033
- if (frame.ok === false && frame.summary) {
1034
- this.out(ui.dim(` ${String(frame.summary).split("\n")[0]}\n`));
1035
- }
1036
- break;
1037
- case "action_refused":
1038
- // The same: the agent is told why and carries on. Only the full view
1039
- // shows it.
1040
- if (!this.full)
1041
- break;
1042
- this.out(ui.red(` refused ${String(frame.name ?? "")}`)
1043
- + ui.dim(` ${String(frame.reason ?? "")}\n`));
1044
- break;
1045
- case "todos": {
1046
- const rendered = ui.todos(frame.todos ?? []);
1047
- // Only when it has actually changed. A plan reprinted identically after
1048
- // every step is noise that buries the run.
1049
- if (rendered !== this.lastTodos) {
1050
- this.out(rendered);
1051
- this.lastTodos = rendered;
1052
- }
1053
- break;
1054
- }
1055
- // A file the agent produced, and where it went. Said here rather than
1056
- // left to the model's sentence: a terminal has no timeline to look at, and
1057
- // "ready to download" in a terminal is the same as producing nothing.
1058
- case "document_made": {
1059
- const saved = frame.saved_to ? String(frame.saved_to) : "";
1060
- const bytes = Number(frame.bytes ?? 0).toLocaleString();
1061
- const name = String(frame.filename ?? "a file");
1062
- if (saved) {
1063
- this.out(ui.savedFile(saved, path.resolve(this.opts.root, saved), bytes));
1064
- }
1065
- else {
1066
- // Not written here, so the stored copy is the only way to it.
1067
- const url = frame.url ? String(frame.url) : "";
1068
- this.out(ui.yellow(` made `) + (url ? ui.link(name, url) : name)
1069
- + ui.dim(` ${bytes} bytes, not saved here${url ? ", click to download" : ""}\n`));
1070
- }
1071
- break;
1072
- }
1073
- case "compacting":
1074
- this.out(ui.dim(" summarizing the conversation so far to keep it affordable\n"));
1075
- break;
1076
- // Notes, pausing and the queue, in the service's words (6.7, 6.8).
1077
- case "steered":
1078
- case "note":
1079
- case "pausing":
1080
- case "paused":
1081
- case "resumed":
1082
- case "queue":
1083
- case "queue_clear":
1084
- if (frame.kind === "paused")
1085
- this.paused = true;
1086
- if (frame.kind === "resumed")
1087
- this.paused = false;
1088
- if (frame.line)
1089
- this.out(ui.dim(` ${String(frame.line)}\n`));
1090
- if (frame.kind === "queue" && Array.isArray(frame.notes)) {
1091
- for (const n of frame.notes)
1092
- this.out(ui.dim(` ${String(n.text ?? "")}\n`));
1093
- }
1094
- break;
1095
- default:
1096
- break;
1097
- }
1098
- }
1099
- targetOf(frame) {
1100
- // The service's words when it sent them (manual 5.2 to 5.4); an older
1101
- // service sends none and the path or pattern is shown as before.
1102
- if (typeof frame.target === "string")
1103
- return frame.target;
1104
- const input = frame.input ?? {};
1105
- return String(input.path ?? input.pattern ?? input.command ?? input.to ?? "");
1106
- }
1107
- /** Put a change in front of the person and wait.
1108
- *
1109
- * Three cases, in order. A caller that owns the keyboard lent us one, so the
1110
- * question goes there. Nobody lent one and somebody is watching, so we open
1111
- * our own reader. Nobody is watching, so it is refused.
1112
- *
1113
- * In headless mode there is nobody to ask, so it is refused rather than
1114
- * assumed. Treating silence as consent would let a script approve changes
1115
- * nobody ever saw, which is the opposite of what a permission mode is for:
1116
- * a script that needs to change files says so by choosing a mode that allows
1117
- * it, up front. */
1118
- async ask(name, input, prompt = "") {
1119
- if (this.opts.headless) {
1120
- // Name what was refused. A refusal that does not say WHICH command it
1121
- // turned down cannot be acted on: the operator's only remedy is to
1122
- // pre-approve it with --allow, and they cannot approve a string they were
1123
- // never shown. Found while running the same job unattended five ways and
1124
- // watching every arm stall on a command none of them would name.
1125
- const what = this.targetOf({ input });
1126
- this.out(ui.yellow(` ${name} needs approval and nobody is watching, so it was refused. `)
1127
- + (what ? ui.dim(`Refused: ${what}\n `) : "")
1128
- + ui.dim("Re-run with --allow \"<that exact command>\", or choose a permission mode that allows it.\n"));
1129
- this.refusedUnattended = true;
1130
- return "n";
1131
- }
1132
- this.out(ui.diff(name, input));
1133
- // A command shows the folder it will run in (manual 4.7).
1134
- if (typeof input.command === "string") {
1135
- const pathMod = path;
1136
- const folder = typeof input.cwd === "string" && input.cwd
1137
- ? pathMod.resolve(this.opts.root, input.cwd) : this.opts.root;
1138
- const home = process.env.HOME || process.env.USERPROFILE || "";
1139
- this.out(ui.dim(` in ${home && folder.startsWith(home) ? `~${folder.slice(home.length)}` : folder}\n`));
1140
- }
1141
- const question = prompt ? ui.bold(prompt) : `${ui.bold("Apply this?")} ${ui.dim("[y/N]")}`;
1142
- let answer;
1143
- if (this.opts.prompt) {
1144
- answer = await this.opts.prompt(question);
1145
- }
1146
- else if (this.opts.confirm) {
1147
- answer = (await this.opts.confirm(question)) ? "y" : "n";
1148
- }
1149
- else {
1150
- const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
1151
- try {
1152
- answer = await new Promise((resolve) => {
1153
- rl.on("SIGINT", () => { this.out("\n"); resolve(null); });
1154
- rl.question(` ${question} `, (a) => resolve(a));
1155
- });
1156
- }
1157
- finally {
1158
- rl.close();
1159
- }
1160
- }
1161
- const word = (answer ?? "").trim().toLowerCase();
1162
- if (answer === null)
1163
- return null;
1164
- if (word === "y" || word === "yes")
1165
- this.out(ui.green(" applied\n"));
1166
- else if (word === "a")
1167
- this.out(ui.green(" applied, and yes to exactly this for the rest of the session\n"));
1168
- else if (word === "" || word === "n" || word === "no")
1169
- this.out(ui.dim(" skipped\n"));
1170
- else
1171
- this.out(ui.dim(" not applied; your words go to the agent\n"));
1172
- return answer;
1173
- }
1174
- /** The plan question or one of the agent's questions (manual 4.2, 4.3).
1175
- * Returns what the person typed, or null for Ctrl+C. The meaning of the
1176
- * answer (y, n, a number, words) is decided by the service. */
1177
- async question(frame) {
1178
- const kind = String(frame.kind ?? "question");
1179
- const options = Array.isArray(frame.options) ? frame.options : [];
1180
- // The trust question lists the project's allow rules as they are (4.10).
1181
- if (kind === "trust")
1182
- this.out(`\n ${String(frame.question ?? "").split("\n").join("\n ")}\n`);
1183
- else if (kind !== "plan")
1184
- this.out(ui.question(String(frame.question ?? ""), options));
1185
- const label = String(frame.prompt ?? "");
1186
- const shown = kind === "plan" ? `${ui.bold(label)}` : label;
1187
- if (this.opts.prompt)
1188
- return this.opts.prompt(shown);
1189
- const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
1190
- try {
1191
- return await new Promise((resolve) => {
1192
- // Ctrl+C at a question stops the job, as it does anywhere else.
1193
- rl.on("SIGINT", () => { this.out("\n"); resolve(null); });
1194
- rl.question(` ${shown} `, (a) => resolve(a));
1195
- });
1196
- }
1197
- finally {
1198
- rl.close();
1199
- }
1200
- }
1201
- report(r) {
1202
- // Only if it has not already been said. On a one step job the closing text
1203
- // IS the step's text, and printing it again read as a stutter.
1204
- if (r.text && r.text.trim() !== this.lastSaid)
1205
- this.out(`\n${ui.plain(r.text)}\n`);
1206
- // An item the agent could not finish stays on screen, unticked (4.4).
1207
- if (r.todos.some((t) => t.status !== "completed"))
1208
- this.out(ui.todos(r.todos));
1209
- if (r.ending?.line) {
1210
- // The service's own words, decided from what ran (manual 5.15).
1211
- this.out(ui.ending(r.ending.line, r.detail));
1212
- for (const line of r.ending.proof)
1213
- this.out(ui.dim(` ${line}\n`));
1214
- this.out(ui.receipt(r.receipt, r.models, undefined, r.card));
1215
- }
1216
- else {
1217
- this.out(ui.outcome(r.outcome, r.detail));
1218
- for (const line of r.ending?.proof ?? [])
1219
- this.out(ui.dim(` ${line}\n`));
1220
- this.out(ui.receipt(r.receipt, r.models, r.ending ? undefined : r.testsPassed, r.card));
1221
- }
1222
- // What would finish the request, worded by the service (web manual 13.4).
1223
- for (const line of r.nextSteps ?? [])
1224
- this.out(`${line}\n`);
1225
- if (r.jobId) {
1226
- // The job's own reference, so a person can quote it. The link to the
1227
- // account sits in the receipt above, where the server put it.
1228
- this.out(ui.dim(` job ${r.jobId}\n`));
1229
- }
1230
- }
1231
- }
1232
- exports.TerminalSession = TerminalSession;