@andorra-labs/code 0.1.10 → 0.1.11

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 (155) hide show
  1. package/README.md +28 -208
  2. package/THIRD_PARTY_NOTICES.md +15 -0
  3. package/dist/src/agent-execution.js +36 -0
  4. package/dist/src/app-server/protocol.d.ts +1 -0
  5. package/dist/src/app-server.d.ts +34 -1
  6. package/dist/src/app-server.js +264 -54
  7. package/dist/src/automation-service.js +1 -1
  8. package/dist/src/browser-session.d.ts +8 -0
  9. package/dist/src/browser-session.js +27 -1
  10. package/dist/src/browser-ui/app.js +237 -15
  11. package/dist/src/browser-ui/index.html +5 -5
  12. package/dist/src/browser-ui/style.css +110 -65
  13. package/dist/src/browser-ui/tokens.css +27 -26
  14. package/dist/src/coding-tools.d.ts +24 -0
  15. package/dist/src/coding-tools.js +71 -8
  16. package/dist/src/command-screens.js +1 -1
  17. package/dist/src/commands.js +1 -1
  18. package/dist/src/completion-gates.d.ts +42 -7
  19. package/dist/src/completion-gates.js +55 -9
  20. package/dist/src/completion.d.ts +8 -0
  21. package/dist/src/completion.js +19 -1
  22. package/dist/src/dashboard-view.js +2 -2
  23. package/dist/src/deadline.js +4 -0
  24. package/dist/src/graph-manager-chat.js +13 -13
  25. package/dist/src/graph-runner.js +39 -2
  26. package/dist/src/graph-server.js +9 -9
  27. package/dist/src/graph-sync.d.ts +8 -0
  28. package/dist/src/graph-sync.js +54 -3
  29. package/dist/src/graph-tool.js +1 -1
  30. package/dist/src/graph-ui/app.js +262 -93
  31. package/dist/src/graph-ui/controls.css +43 -22
  32. package/dist/src/graph-ui/controls.js +31 -1
  33. package/dist/src/graph-ui/embed.js +62 -13
  34. package/dist/src/graph-ui/icons.js +4 -0
  35. package/dist/src/graph-ui/index.html +3 -3
  36. package/dist/src/graph-ui/manager-state.js +2 -2
  37. package/dist/src/graph-ui/manager.css +19 -18
  38. package/dist/src/graph-ui/manager.js +11 -11
  39. package/dist/src/graph-ui/skill-picker.js +1 -1
  40. package/dist/src/graph-ui/studio-canvas.js +8 -8
  41. package/dist/src/graph-ui/studio.css +18 -15
  42. package/dist/src/graph-ui/studio.js +92 -35
  43. package/dist/src/graph-ui/style.css +122 -79
  44. package/dist/src/graph-ui/theme.js +2 -2
  45. package/dist/src/graph-ui/tokens.css +33 -29
  46. package/dist/src/graphs.d.ts +3 -2
  47. package/dist/src/graphs.js +3 -2
  48. package/dist/src/membership-errors.d.ts +7 -1
  49. package/dist/src/membership-errors.js +9 -3
  50. package/dist/src/pull-requests.d.ts +42 -6
  51. package/dist/src/pull-requests.js +11 -3
  52. package/dist/src/react-runtime.js +121 -14
  53. package/dist/src/read-document-doc.d.ts +20 -0
  54. package/dist/src/read-document-doc.js +524 -0
  55. package/dist/src/read-document-docx.d.ts +21 -0
  56. package/dist/src/read-document-docx.js +584 -0
  57. package/dist/src/read-document-text.d.ts +29 -0
  58. package/dist/src/read-document-text.js +67 -0
  59. package/dist/src/read-document-tool.d.ts +48 -0
  60. package/dist/src/read-document-tool.js +162 -0
  61. package/dist/src/read-document.d.ts +78 -0
  62. package/dist/src/read-document.js +353 -0
  63. package/dist/src/read-image.d.ts +29 -2
  64. package/dist/src/read-image.js +42 -17
  65. package/dist/src/runtime.d.ts +19 -0
  66. package/dist/src/runtime.js +10 -1
  67. package/dist/src/session-changes.d.ts +6 -1
  68. package/dist/src/session-changes.js +13 -5
  69. package/dist/src/side-panel.d.ts +6 -1
  70. package/dist/src/side-panel.js +12 -10
  71. package/dist/src/skills/bundled/create-skill/SKILL.md +1 -1
  72. package/dist/src/skills/bundled/diagram/SKILL.md +1 -1
  73. package/dist/src/skills/bundled/graph-manager/SKILL.md +37 -3
  74. package/dist/src/skills/bundled/graph-manager/patterns.md +27 -0
  75. package/dist/src/skills/bundled/provenance.json +4 -4
  76. package/dist/src/skills/runtime-skills.js +3 -3
  77. package/dist/src/stall-recovery.d.ts +6 -2
  78. package/dist/src/stall-recovery.js +7 -2
  79. package/dist/src/terminal-ui.js +2 -2
  80. package/dist/src/time-limit.d.ts +53 -0
  81. package/dist/src/time-limit.js +79 -0
  82. package/dist/src/tools.js +92 -7
  83. package/dist/src/transcript.js +1 -1
  84. package/dist/src/types.d.ts +6 -0
  85. package/dist/src/usage-analytics.d.ts +3 -1
  86. package/dist/src/usage-analytics.js +16 -2
  87. package/package.json +6 -26
  88. package/docs/README.md +0 -36
  89. package/docs/agents/README.md +0 -62
  90. package/docs/agents/install-for-agents.md +0 -56
  91. package/docs/agents/mcp-server.md +0 -212
  92. package/docs/agents/subagent-mode.md +0 -149
  93. package/docs/concepts/README.md +0 -47
  94. package/docs/concepts/jev-actionable-routing.md +0 -113
  95. package/docs/concepts/jev-decision-thresholds.md +0 -412
  96. package/docs/concepts/jev-efficiency.md +0 -217
  97. package/docs/concepts/jev-eval-2026-11-01.md +0 -78
  98. package/docs/concepts/limits.md +0 -52
  99. package/docs/concepts/memory.md +0 -10
  100. package/docs/concepts/security.md +0 -50
  101. package/docs/concepts/workspace-instructions.md +0 -29
  102. package/docs/getting-started/README.md +0 -82
  103. package/docs/getting-started/accounts.md +0 -78
  104. package/docs/getting-started/configure-providers.md +0 -132
  105. package/docs/guides/README.md +0 -13
  106. package/docs/guides/browser.md +0 -39
  107. package/docs/guides/desktop-app.md +0 -414
  108. package/docs/guides/extensions.md +0 -102
  109. package/docs/guides/graph-builder.md +0 -116
  110. package/docs/guides/headless.md +0 -46
  111. package/docs/guides/tui.md +0 -75
  112. package/docs/guides/update.md +0 -70
  113. package/docs/guides/web-search.md +0 -51
  114. package/docs/guides/windows-code-signing.md +0 -319
  115. package/docs/llms.txt +0 -45
  116. package/docs/reference/README.md +0 -7
  117. package/docs/reference/cli.md +0 -76
  118. package/docs/reference/config.md +0 -91
  119. package/docs/reference/slash-commands.md +0 -59
  120. package/docs/superpowers/plans/2026-11-01-claude-console-sign-in.md +0 -111
  121. package/docs/superpowers/plans/2026-11-01-jev-node-opt-in.md +0 -910
  122. package/docs/superpowers/plans/2026-11-02-workflow-pane.md +0 -398
  123. package/docs/superpowers/plans/2026-11-06-graph-soft-delete.md +0 -125
  124. package/docs/superpowers/plans/2026-11-09-orchestrator-delegation.md +0 -295
  125. package/docs/superpowers/plans/2026-11-13-graph-manager-chat.md +0 -203
  126. package/docs/superpowers/plans/2026-11-14-jev-fair-use-pricing.md +0 -79
  127. package/docs/superpowers/specs/2026-10-31-work-line-summary-design.md +0 -50
  128. package/docs/superpowers/specs/2026-11-01-claude-console-sign-in-design.md +0 -176
  129. package/docs/superpowers/specs/2026-11-01-jev-node-opt-in-design.md +0 -164
  130. package/docs/superpowers/specs/2026-11-01-pr-section-design.md +0 -111
  131. package/docs/superpowers/specs/2026-11-02-workflow-pane-design.md +0 -130
  132. package/docs/superpowers/specs/2026-11-06-bundled-skills-design.md +0 -206
  133. package/docs/superpowers/specs/2026-11-09-orchestrator-delegation-design.md +0 -291
  134. package/docs/superpowers/specs/2026-11-13-graph-manager-chat-design.md +0 -182
  135. package/docs/superpowers/specs/2026-11-14-jev-fair-use-pricing-design.md +0 -156
  136. package/scripts/jev-efficiency-eval.mjs +0 -187
  137. package/scripts/jev-efficiency-live.mjs +0 -193
  138. package/scripts/zcode-engine-replay.mjs +0 -223
  139. package/tests/agent-centric-mcp-test-plan.md +0 -208
  140. package/tests/analytics-settings-test-plan.md +0 -165
  141. package/tests/browser-cli-smoke.mjs +0 -276
  142. package/tests/browser-test-plan.md +0 -280
  143. package/tests/chat-side-panel-test-plan.md +0 -309
  144. package/tests/decision-engine-test-plan.md +0 -163
  145. package/tests/default-active-jev-test-plan.md +0 -85
  146. package/tests/harness-extensions-test-plan.md +0 -113
  147. package/tests/jev-all-decisions-test-plan.md +0 -156
  148. package/tests/jev-efficiency/criteria.json +0 -158
  149. package/tests/jev-efficiency/workloads.mjs +0 -242
  150. package/tests/jev-efficiency-test-plan.md +0 -198
  151. package/tests/permissions-sandbox-probe.mjs +0 -74
  152. package/tests/permissions-test-plan.md +0 -191
  153. package/tests/product-telemetry-test-plan.md +0 -536
  154. package/tests/thinking-stream-preview-test-plan.md +0 -136
  155. package/tests/zcode-react-engine-test-plan.md +0 -396
@@ -0,0 +1,353 @@
1
+ import { promisify } from 'node:util';
2
+ import { crc32, deflate, deflateSync } from 'node:zlib';
3
+ import { extractDoc } from './read-document-doc.js';
4
+ import { extractDocx } from './read-document-docx.js';
5
+ import { decodeWindows1252, formatRanges } from './read-document-text.js';
6
+ /** PDFium copies the file into a 2 GiB WebAssembly heap; past this the copy cannot be relied on to fit. */
7
+ const PDF_FILE_LIMIT = 512 * 1024 * 1024;
8
+ /** Longest edge `renderPdfPages` accepts: a 4096 x 4096 bitmap is already 64 MiB before encoding. */
9
+ const RENDER_EDGE_LIMIT = 4096;
10
+ /** Longest stretch of synchronous PDFium work before the event loop gets a turn, in milliseconds. */
11
+ const YIELD_AFTER_MS = 20;
12
+ const startsWith = (head, offset, signature) => signature.every((byte, index) => head[offset + index] === byte);
13
+ /**
14
+ * By leading bytes only. `'zip'` and `'cfb'` are containers that may or may not hold a Word
15
+ * document; `extractDocument` decides.
16
+ *
17
+ * The PDF signature must open the file (after at most a byte-order mark and white space). PDF
18
+ * viewers also accept it anywhere in the first kilobyte, but so would any source file or note that
19
+ * mentions the signature near its top, and those must keep reading as text.
20
+ */
21
+ export function sniffDocument(head) {
22
+ let start = startsWith(head, 0, [0xef, 0xbb, 0xbf]) ? 3 : 0;
23
+ while (start < 16 && (head[start] === 0x20 || head[start] === 0x09 || head[start] === 0x0a || head[start] === 0x0d))
24
+ start++;
25
+ if (startsWith(head, start, [0x25, 0x50, 0x44, 0x46, 0x2d]))
26
+ return 'pdf';
27
+ if (startsWith(head, 0, [0x50, 0x4b, 0x03, 0x04]))
28
+ return 'zip';
29
+ if (startsWith(head, 0, [0xd0, 0xcf, 0x11, 0xe0, 0xa1, 0xb1, 0x1a, 0xe1]))
30
+ return 'cfb';
31
+ return undefined;
32
+ }
33
+ /**
34
+ * Text and structure of a document.
35
+ *
36
+ * Resolves undefined when the bytes are not a supported document (a ZIP that is not a `.docx`, a
37
+ * compound file that is not a Word document), so the caller can fall back to its binary-file
38
+ * error. Rejects when the bytes are a supported document that cannot be read (encrypted, damaged,
39
+ * too large once inflated); the message is written for the model and says what to do instead.
40
+ */
41
+ export async function extractDocument(bytes, signal) {
42
+ signal?.throwIfAborted();
43
+ const container = sniffDocument(bytes.subarray(0, 4100));
44
+ if (container === 'pdf')
45
+ return extractPdf(bytes, signal);
46
+ if (container === 'zip') {
47
+ const document = await extractDocx(bytes, signal);
48
+ return document && { kind: 'docx', ...document };
49
+ }
50
+ if (container === 'cfb') {
51
+ const document = extractDoc(bytes);
52
+ signal?.throwIfAborted();
53
+ return document && { kind: 'doc', ...document };
54
+ }
55
+ return undefined;
56
+ }
57
+ let pdfium;
58
+ /**
59
+ * One PDFium instance for the life of the process. The import is deferred to the first PDF so a
60
+ * CLI start that never reads one does not load or compile the five-megabyte module.
61
+ */
62
+ function loadPdfium() {
63
+ pdfium ??= import('@hyzyla/pdfium').then(module => module.PDFiumLibrary.init()).catch((error) => {
64
+ // A failed load is not cached: the next read gets a fresh attempt.
65
+ pdfium = undefined;
66
+ throw new Error(`PDF support could not be loaded (${error instanceof Error ? error.message : String(error)}). Read cannot open PDF files in this installation.`);
67
+ });
68
+ return pdfium;
69
+ }
70
+ /** A WebAssembly trap leaves the module aborted for good, so the next PDF must start a new instance. */
71
+ function discardAfterTrap(error) {
72
+ if (error instanceof WebAssembly.RuntimeError)
73
+ pdfium = undefined;
74
+ }
75
+ function pdfOpenError(error) {
76
+ const reason = error instanceof Error ? error.message : String(error);
77
+ if (/password/i.test(reason)) {
78
+ return new Error('This PDF is encrypted and needs a password to open, so Read cannot show it. Ask the user for an unlocked copy, or decrypt it first with the password (for example `qpdf --password=PASSWORD --decrypt in.pdf out.pdf`).');
79
+ }
80
+ if (/security/i.test(reason))
81
+ return new Error('This PDF is encrypted with a scheme Read does not support. Ask the user for an unlocked copy.');
82
+ return new Error(`This PDF could not be parsed: it is damaged, cut short or not a PDF at all (${reason}). Download or export it again, or inspect the bytes with a script.`);
83
+ }
84
+ /** Open the PDF, run `use`, and always give the document's memory back: the engine is a long-lived process. */
85
+ async function withPdf(bytes, signal, use) {
86
+ signal?.throwIfAborted();
87
+ if (bytes.length > PDF_FILE_LIMIT)
88
+ throw new Error(`This PDF is larger than ${PDF_FILE_LIMIT / 1024 / 1024} MiB, which Read will not load. Split it first (for example with qpdf) and read the parts.`);
89
+ const library = await loadPdfium();
90
+ signal?.throwIfAborted();
91
+ let document;
92
+ try {
93
+ document = await library.loadDocument(bytes);
94
+ }
95
+ catch (error) {
96
+ discardAfterTrap(error);
97
+ throw pdfOpenError(error);
98
+ }
99
+ try {
100
+ return await use(document);
101
+ }
102
+ catch (error) {
103
+ discardAfterTrap(error);
104
+ throw error;
105
+ }
106
+ finally {
107
+ // After a trap the module is gone and so is its memory; there is nothing left to free.
108
+ try {
109
+ document.destroy();
110
+ }
111
+ catch { /* aborted module */ }
112
+ }
113
+ }
114
+ /**
115
+ * PDFium calls are synchronous. Yielding between pages keeps a long document from freezing the
116
+ * engine, and it is also what lets an abort arrive at all: a signal cannot fire while the loop
117
+ * never returns to the event loop.
118
+ */
119
+ function pacer() {
120
+ let last = performance.now();
121
+ return async () => {
122
+ if (performance.now() - last < YIELD_AFTER_MS)
123
+ return;
124
+ await new Promise(resolve => setImmediate(resolve));
125
+ last = performance.now();
126
+ };
127
+ }
128
+ function pageText(raw) {
129
+ // PDFium separates lines with CRLF and marks some line-end hyphens with control characters.
130
+ return raw.replace(/\r\n?/g, '\n').replace(/[\u0000-\u0008\u000b-\u001f￾￿]/g, '').replace(/[ \t ]+$/gm, '').replace(/^\n+|\n+$/g, '');
131
+ }
132
+ async function extractPdf(bytes, signal) {
133
+ return withPdf(bytes, signal, async (document) => {
134
+ const pageCount = document.getPageCount();
135
+ if (pageCount < 1)
136
+ throw new Error('This PDF has no pages Read can find: it is damaged or cut short. Download or export it again.');
137
+ const pages = [];
138
+ const empty = [];
139
+ const unreadable = [];
140
+ const pause = pacer();
141
+ for (let index = 0; index < pageCount; index++) {
142
+ signal?.throwIfAborted();
143
+ const page = document.getPage(index);
144
+ let text = '';
145
+ try {
146
+ text = pageText(page.getText());
147
+ if (!text)
148
+ empty.push(index + 1);
149
+ }
150
+ catch (error) {
151
+ if (error instanceof WebAssembly.RuntimeError)
152
+ throw error;
153
+ // One broken page object should not cost the reader the rest of the document.
154
+ unreadable.push(index + 1);
155
+ }
156
+ finally {
157
+ page.close();
158
+ }
159
+ pages.push({ page: index + 1, text });
160
+ await pause();
161
+ }
162
+ const notes = [];
163
+ if (empty.length === pageCount)
164
+ notes.push(pageCount === 1 ? 'the page has no extractable text' : `none of the ${pageCount} pages has extractable text`);
165
+ else if (empty.length)
166
+ notes.push(`${empty.length} of ${pageCount} pages have no extractable text (${empty.length === 1 ? 'page' : 'pages'} ${formatRanges(empty)})`);
167
+ if (unreadable.length)
168
+ notes.push(`${unreadable.length === 1 ? 'page' : 'pages'} ${formatRanges(unreadable)} could not be parsed`);
169
+ return { kind: 'pdf', pageCount, pages, text: '', notes };
170
+ });
171
+ }
172
+ /**
173
+ * Rasterise the given 1-based pages on a white background, longest edge `options.maxEdge` pixels.
174
+ * Pages come back in the order asked for. Rejects for a page number the document does not have.
175
+ */
176
+ export async function renderPdfPages(bytes, pages, options) {
177
+ const { maxEdge, signal } = options;
178
+ if (!Number.isInteger(maxEdge) || maxEdge < 16 || maxEdge > RENDER_EDGE_LIMIT)
179
+ throw new RangeError(`maxEdge must be a whole number from 16 to ${RENDER_EDGE_LIMIT}.`);
180
+ return withPdf(bytes, signal, async (document) => {
181
+ const pageCount = document.getPageCount();
182
+ for (const number of pages) {
183
+ if (!Number.isInteger(number) || number < 1 || number > pageCount)
184
+ throw new Error(`Page ${number} does not exist: this PDF has ${pageCount} ${pageCount === 1 ? 'page' : 'pages'}.`);
185
+ }
186
+ const rendered = [];
187
+ for (const number of pages) {
188
+ signal?.throwIfAborted();
189
+ const page = document.getPage(number - 1);
190
+ let bitmap;
191
+ try {
192
+ const { originalWidth, originalHeight } = page.getOriginalSize();
193
+ if (!(originalWidth > 0 && originalHeight > 0))
194
+ throw new Error(`Page ${number} of this PDF could not be rendered: it is damaged.`);
195
+ const scale = maxEdge / Math.max(originalWidth, originalHeight);
196
+ // Explicit pixel sizes, because the library floors a scaled size and would miss the edge by one.
197
+ bitmap = await page.render({
198
+ render: 'bitmap', scale: 1,
199
+ width: Math.max(1, Math.round(originalWidth * scale)), height: Math.max(1, Math.round(originalHeight * scale)),
200
+ });
201
+ }
202
+ finally {
203
+ page.close();
204
+ }
205
+ // The bitmap is already copied out of PDFium's heap, so the abort check can come before the slow encode.
206
+ await new Promise(resolve => setImmediate(resolve));
207
+ signal?.throwIfAborted();
208
+ rendered.push({ page: number, mimeType: 'image/png', data: await encodePng(bitmap.data, bitmap.width, bitmap.height), width: bitmap.width, height: bitmap.height });
209
+ }
210
+ return rendered;
211
+ });
212
+ }
213
+ const deflateAsync = promisify(deflate);
214
+ /**
215
+ * Opaque RGBA to PNG. A page is usually black on white, so it is written as 8-bit greyscale when
216
+ * every pixel is grey (a third of the bytes to compress) and as RGB otherwise; alpha is dropped
217
+ * because the page was drawn on white.
218
+ */
219
+ async function encodePng(rgba, width, height) {
220
+ let grey = true;
221
+ for (let offset = 0; offset < rgba.length; offset += 4) {
222
+ if (rgba[offset] !== rgba[offset + 1] || rgba[offset] !== rgba[offset + 2]) {
223
+ grey = false;
224
+ break;
225
+ }
226
+ }
227
+ const stride = width * (grey ? 1 : 3);
228
+ const pixels = Buffer.allocUnsafe(stride * height);
229
+ if (grey)
230
+ for (let source = 0, target = 0; target < pixels.length; source += 4)
231
+ pixels[target++] = rgba[source];
232
+ else {
233
+ for (let source = 0, target = 0; target < pixels.length; source += 4) {
234
+ pixels[target++] = rgba[source];
235
+ pixels[target++] = rgba[source + 1];
236
+ pixels[target++] = rgba[source + 2];
237
+ }
238
+ }
239
+ // PNG filter 2 (Up): each byte as its difference from the byte above, wrapping modulo 256.
240
+ const writeUp = (y, out, at) => {
241
+ const row = y * stride;
242
+ if (!y) {
243
+ pixels.copy(out, at, 0, stride);
244
+ return;
245
+ }
246
+ for (let x = 0; x < stride; x++)
247
+ out[at + x] = pixels[row + x] - pixels[row + x - stride];
248
+ };
249
+ // Which filter wins depends on the page: rendered text came out about a tenth smaller unfiltered
250
+ // and a noisy scan about a tenth smaller as row differences. The per-row heuristic PNG encoders
251
+ // use picked wrongly for text, so a sample of rows is compressed both ways and the smaller decides.
252
+ const sampled = Math.min(height, 64);
253
+ const plain = Buffer.allocUnsafe(sampled * stride);
254
+ const delta = Buffer.allocUnsafe(sampled * stride);
255
+ for (let index = 0; index < sampled; index++) {
256
+ const y = Math.floor(index * height / sampled);
257
+ pixels.copy(plain, index * stride, y * stride, (y + 1) * stride);
258
+ writeUp(y, delta, index * stride);
259
+ }
260
+ const up = deflateSync(delta, { level: 1 }).length < deflateSync(plain, { level: 1 }).length;
261
+ const raw = Buffer.allocUnsafe((stride + 1) * height);
262
+ for (let y = 0, target = 0; y < height; y++, target += stride + 1) {
263
+ raw[target] = up && y ? 2 : 0;
264
+ if (up)
265
+ writeUp(y, raw, target + 1);
266
+ else
267
+ pixels.copy(raw, target + 1, y * stride, (y + 1) * stride);
268
+ }
269
+ const chunk = (type, data) => {
270
+ const body = Buffer.concat([Buffer.from(type, 'ascii'), data]);
271
+ const frame = Buffer.alloc(8);
272
+ frame.writeUInt32BE(data.length, 0);
273
+ frame.writeUInt32BE(crc32(body), 4);
274
+ return Buffer.concat([frame.subarray(0, 4), body, frame.subarray(4)]);
275
+ };
276
+ const header = Buffer.alloc(13);
277
+ header.writeUInt32BE(width, 0);
278
+ header.writeUInt32BE(height, 4);
279
+ header[8] = 8;
280
+ header[9] = grey ? 0 : 2;
281
+ // Deflate runs on the thread pool, so a large page does not hold the event loop while it compresses.
282
+ const compressed = await deflateAsync(raw);
283
+ return Buffer.concat([Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]), chunk('IHDR', header), chunk('IDAT', compressed), chunk('IEND', Buffer.alloc(0))]);
284
+ }
285
+ /** Control bytes that ordinary text does not contain: everything below space except tab, newline, form feed, return and escape. */
286
+ const isStrayControl = (code) => code === 0x7f || (code < 0x20 && code !== 0x09 && code !== 0x0a && code !== 0x0c && code !== 0x0d && code !== 0x1b);
287
+ /** Text reads as text when it has no NUL and at most one stray control character per hundred. */
288
+ function looksLikeText(length, codeAt) {
289
+ let stray = 0;
290
+ for (let index = 0; index < length; index++) {
291
+ const code = codeAt(index);
292
+ if (code === 0)
293
+ return false;
294
+ if (isStrayControl(code))
295
+ stray++;
296
+ }
297
+ return stray * 100 <= length;
298
+ }
299
+ /** UTF-16 without a byte-order mark shows itself in mostly-Latin text: every other byte is NUL. */
300
+ function guessUtf16(bytes) {
301
+ if (bytes.length < 4 || bytes.length % 2)
302
+ return undefined;
303
+ const pairs = Math.min(bytes.length, 65536) / 2;
304
+ let evenZero = 0;
305
+ let oddZero = 0;
306
+ for (let index = 0; index < pairs; index++) {
307
+ if (bytes[index * 2] === 0)
308
+ evenZero++;
309
+ if (bytes[index * 2 + 1] === 0)
310
+ oddZero++;
311
+ }
312
+ if (oddZero * 10 >= pairs * 6 && evenZero * 20 <= pairs)
313
+ return 'utf-16le';
314
+ if (evenZero * 10 >= pairs * 6 && oddZero * 20 <= pairs)
315
+ return 'utf-16be';
316
+ return undefined;
317
+ }
318
+ /**
319
+ * Text that is not valid UTF-8: UTF-16 (marked by a byte-order mark, or recognisable without one),
320
+ * else Windows-1252 when the bytes look like text. Undefined for binary data.
321
+ *
322
+ * Call it only after UTF-8 decoding has failed: valid UTF-8 would be accepted here as Windows-1252
323
+ * and come back as mojibake. Windows-1252 is the fallback because it is what Windows tools wrote
324
+ * for decades and it assigns a character to every byte, so text in another 8-bit code page still
325
+ * comes through with its ASCII intact rather than being refused as binary.
326
+ */
327
+ export function decodeLegacyText(bytes) {
328
+ if (!bytes.length)
329
+ return undefined;
330
+ const marked = bytes[0] === 0xff && bytes[1] === 0xfe ? 'utf-16le' : bytes[0] === 0xfe && bytes[1] === 0xff ? 'utf-16be' : undefined;
331
+ // FF FE 00 00 is the UTF-32 mark; nothing here reads UTF-32.
332
+ if (marked === 'utf-16le' && bytes[2] === 0 && bytes[3] === 0)
333
+ return undefined;
334
+ const encoding = marked ?? guessUtf16(bytes);
335
+ if (encoding) {
336
+ const body = bytes.subarray(marked ? 2 : 0);
337
+ // A trailing odd byte is a cut-off file; the complete characters before it are still text.
338
+ const even = body.subarray(0, body.length & ~1);
339
+ let text;
340
+ try {
341
+ // `fatal` rejects unpaired surrogates, which real text never has and binary data soon does.
342
+ text = new TextDecoder('utf-16le', { fatal: true }).decode(encoding === 'utf-16be' ? Buffer.from(even).swap16() : even);
343
+ }
344
+ catch {
345
+ return undefined;
346
+ }
347
+ // A file that is only a byte-order mark is an empty text file, not a binary one.
348
+ return (marked || text.length) && looksLikeText(text.length, index => text.charCodeAt(index)) ? { text, encoding } : undefined;
349
+ }
350
+ if (!looksLikeText(bytes.length, index => bytes[index]))
351
+ return undefined;
352
+ return { text: decodeWindows1252(bytes), encoding: 'windows-1252' };
353
+ }
@@ -5,6 +5,7 @@ import type { ToolContext, ToolImage } from './types.js';
5
5
  * A model can only judge a rendered frame, a plot or a screenshot by looking at it. Read hands a
6
6
  * supported image file to the model as a native image through the same `resultImages` channel
7
7
  * browser screenshots use, so retention, pruning and the provider boundary treat both alike.
8
+ * Rendered PDF pages (read-document-tool.ts) travel the same way, several to one Read call.
8
9
  */
9
10
  /** Largest image file Read will decode. */
10
11
  export declare const READ_IMAGE_FILE_LIMIT: number;
@@ -16,10 +17,36 @@ export declare const READ_IMAGE_MAX_BYTES: number;
16
17
  export declare const READ_IMAGE_BATCH_LIMIT = 6;
17
18
  export declare const READ_IMAGE_BATCH_BYTES: number;
18
19
  /**
19
- * Hand over the image a Read observation carries. Identical observations (the same file read
20
- * twice in one batch) queue under one key, so each claim receives exactly one image.
20
+ * Hand over the images a Read observation carries: one for an image file, one per page for
21
+ * rendered PDF pages. Identical observations (the same file read twice in one batch) queue under
22
+ * one key, so each claim receives exactly one call's images.
21
23
  */
22
24
  export declare function claimReadImages(output: string): ToolImage[] | undefined;
25
+ /** Stage the images of one Read call; `claimReadImages` releases them with that exact text. */
26
+ export declare function holdReadImages(output: string, images: ToolImage[]): void;
27
+ /** One image made ready to send, with what the observation needs to say about it. */
28
+ export interface PreparedReadImage {
29
+ image: ToolImage;
30
+ width: number;
31
+ height: number;
32
+ originalWidth: number;
33
+ originalHeight: number;
34
+ wasResized: boolean;
35
+ /**
36
+ * Hand this image's place in the response's budget back. For a caller that prepared several
37
+ * images for one result and cannot deliver them: an image that is never staged must not cost
38
+ * the other reads in the batch their allowance. Safe to call more than once.
39
+ */
40
+ release(): void;
41
+ }
42
+ /**
43
+ * Decode and downscale one image under the response's image budget. The caller stages the result
44
+ * with `holdReadImages`; an image that could not be prepared hands its place in the budget back.
45
+ */
46
+ export declare function prepareReadImage(context: ToolContext, file: {
47
+ mimeType: string;
48
+ bytes: Buffer;
49
+ }): Promise<PreparedReadImage>;
23
50
  /**
24
51
  * Decode, downscale and stage one image file, returning the text observation that names it.
25
52
  * The staged image is released by `claimReadImages` with that exact text.
@@ -7,6 +7,7 @@ import { formatBytes } from './attachments.js';
7
7
  * A model can only judge a rendered frame, a plot or a screenshot by looking at it. Read hands a
8
8
  * supported image file to the model as a native image through the same `resultImages` channel
9
9
  * browser screenshots use, so retention, pruning and the provider boundary treat both alike.
10
+ * Rendered PDF pages (read-document-tool.ts) travel the same way, several to one Read call.
10
11
  */
11
12
  /** Largest image file Read will decode. */
12
13
  export const READ_IMAGE_FILE_LIMIT = 20 * 1024 * 1024;
@@ -17,35 +18,38 @@ export const READ_IMAGE_MAX_BYTES = 512 * 1024;
17
18
  /** Images one model response's tool batch may read, across parallel Read calls. */
18
19
  export const READ_IMAGE_BATCH_LIMIT = 6;
19
20
  export const READ_IMAGE_BATCH_BYTES = 2 * 1024 * 1024;
20
- /** Unclaimed images kept for `resultImages`; a caller that never claims cannot grow this. */
21
+ /** Unclaimed observations kept for `resultImages`; a caller that never claims cannot grow this. */
21
22
  const PENDING_LIMIT = 16;
22
23
  const budgets = new WeakMap();
24
+ /** Per observation text, the image groups waiting to be claimed: one group per Read call. */
23
25
  const pending = new Map();
24
26
  /**
25
- * Hand over the image a Read observation carries. Identical observations (the same file read
26
- * twice in one batch) queue under one key, so each claim receives exactly one image.
27
+ * Hand over the images a Read observation carries: one for an image file, one per page for
28
+ * rendered PDF pages. Identical observations (the same file read twice in one batch) queue under
29
+ * one key, so each claim receives exactly one call's images.
27
30
  */
28
31
  export function claimReadImages(output) {
29
32
  const queue = pending.get(output);
30
- const image = queue?.shift();
33
+ const images = queue?.shift();
31
34
  if (queue && !queue.length)
32
35
  pending.delete(output);
33
- return image ? [image] : undefined;
36
+ return images?.length ? images : undefined;
34
37
  }
35
- function hold(output, image) {
38
+ /** Stage the images of one Read call; `claimReadImages` releases them with that exact text. */
39
+ export function holdReadImages(output, images) {
36
40
  const queue = pending.get(output);
37
41
  if (queue)
38
- queue.push(image);
42
+ queue.push(images);
39
43
  else
40
- pending.set(output, [image]);
44
+ pending.set(output, [images]);
41
45
  while (pending.size > PENDING_LIMIT)
42
46
  pending.delete(pending.keys().next().value);
43
47
  }
44
48
  /**
45
- * Decode, downscale and stage one image file, returning the text observation that names it.
46
- * The staged image is released by `claimReadImages` with that exact text.
49
+ * Decode and downscale one image under the response's image budget. The caller stages the result
50
+ * with `holdReadImages`; an image that could not be prepared hands its place in the budget back.
47
51
  */
48
- export async function readImageObservation(context, shownPath, file) {
52
+ export async function prepareReadImage(context, file) {
49
53
  // Embedders without a batch marker run unbudgeted: there is no response boundary to reset on.
50
54
  const batch = context.browserToolBatch;
51
55
  let budget;
@@ -81,13 +85,21 @@ export async function readImageObservation(context, shownPath, file) {
81
85
  throw new Error(`Image read budget reached (${formatBytes(READ_IMAGE_BATCH_BYTES)} of images per response); Read further images in a later turn.`);
82
86
  if (budget)
83
87
  budget.bytes += sentBytes;
84
- const lines = [`Image file ${shownPath} (${file.mimeType}, ${resized.originalWidth}x${resized.originalHeight}, ${formatBytes(file.bytes.length)}) is attached to this result as an image.`];
85
- if (resized.wasResized)
86
- lines.push(`[Shown at ${resized.width}x${resized.height}; multiply coordinates by ${(resized.originalWidth / resized.width).toFixed(2)} to map them to the original.]`);
87
- const output = lines.join('\n');
88
- hold(output, { mimeType: resized.mimeType, data: resized.data });
89
88
  staged = true;
90
- return output;
89
+ let released = false;
90
+ return {
91
+ image: { mimeType: resized.mimeType, data: resized.data },
92
+ width: resized.width, height: resized.height,
93
+ originalWidth: resized.originalWidth, originalHeight: resized.originalHeight,
94
+ wasResized: resized.wasResized,
95
+ release: () => {
96
+ if (released || !budget)
97
+ return;
98
+ released = true;
99
+ budget.count--;
100
+ budget.bytes -= sentBytes;
101
+ },
102
+ };
91
103
  }
92
104
  finally {
93
105
  // A read that produced no image hands its place back; bytes were never added for it.
@@ -95,3 +107,16 @@ export async function readImageObservation(context, shownPath, file) {
95
107
  budget.count--;
96
108
  }
97
109
  }
110
+ /**
111
+ * Decode, downscale and stage one image file, returning the text observation that names it.
112
+ * The staged image is released by `claimReadImages` with that exact text.
113
+ */
114
+ export async function readImageObservation(context, shownPath, file) {
115
+ const prepared = await prepareReadImage(context, file);
116
+ const lines = [`Image file ${shownPath} (${file.mimeType}, ${prepared.originalWidth}x${prepared.originalHeight}, ${formatBytes(file.bytes.length)}) is attached to this result as an image.`];
117
+ if (prepared.wasResized)
118
+ lines.push(`[Shown at ${prepared.width}x${prepared.height}; multiply coordinates by ${(prepared.originalWidth / prepared.width).toFixed(2)} to map them to the original.]`);
119
+ const output = lines.join('\n');
120
+ holdReadImages(output, [prepared.image]);
121
+ return output;
122
+ }
@@ -34,6 +34,13 @@ export interface Completion {
34
34
  outcome?: string;
35
35
  output?: Record<string, unknown>;
36
36
  artifacts?: ArtifactRef[];
37
+ /**
38
+ * What the task still lacks, as the agent itself listed it in the completion that ends a run.
39
+ * Absent when it claimed everything was done. A run-ending completion that carries entries is
40
+ * sent back to keep working (completion-gates.ts); one that is accepted anyway keeps them, so a
41
+ * client can show that the run ended unfinished without reading the summary's wording.
42
+ */
43
+ remaining?: string[];
37
44
  /**
38
45
  * How an attempt ended, carried on the summary a stopped attempt leaves behind.
39
46
  *
@@ -158,6 +165,11 @@ export interface AgentContinuationState {
158
165
  export declare function timerReminderText(prompt: string): string;
159
166
  /** What delivered a retained turn's message instead of the user, as `ConversationTurn.wake` records it. */
160
167
  type RetainedWake = 'timer' | 'auto-fix';
168
+ /**
169
+ * The words a node reads for a message a wake delivered: the agent's own reminder, or the review comments Auto-fix
170
+ * brought, each marked as not coming from the user. A message no wake delivered is the user's, unchanged.
171
+ */
172
+ export declare function wakeMessageText(wake: RetainedWake | undefined, message: string): string;
161
173
  export declare function turnModelTask(turn: {
162
174
  task: string;
163
175
  direction?: string;
@@ -399,6 +411,13 @@ export interface GraphRunOptions extends RunOptions {
399
411
  * conversation already holds it, and every later activation keeps its own policy.
400
412
  */
401
413
  entryHistory?: boolean;
414
+ /**
415
+ * The node a fresh run starts at instead of the graph's entry, when it names a node of the graph that can start
416
+ * without inputs from a predecessor. Set when a wake is addressed to a node (an Auto-fix prompt goes to the node that
417
+ * switched Auto-fix on). Ignored by a resumed run, whose frontier says where it continues, and when it names no
418
+ * such node, in which case the run starts at the entry as usual.
419
+ */
420
+ startNode?: string;
402
421
  /** The configured providers' ids and model lists, for validating adaptive-routing tiers. */
403
422
  configuredModels?: {
404
423
  id: string;
@@ -36,10 +36,19 @@ export { DEFAULT_LIMITS, LIMIT_KEYS, isUnlimited, isUnlimitedAlias, resolveLimit
36
36
  export function timerReminderText(prompt) {
37
37
  return `[Timer] A reminder you set for yourself with set_timer (not a message from the user): ${prompt}`;
38
38
  }
39
+ /**
40
+ * The words a node reads for a message a wake delivered: the agent's own reminder, or the review comments Auto-fix
41
+ * brought, each marked as not coming from the user. A message no wake delivered is the user's, unchanged.
42
+ */
43
+ export function wakeMessageText(wake, message) {
44
+ if (wake === 'auto-fix')
45
+ return `Delivered by Auto-fix (not a message from the user): ${message}`;
46
+ return wake === 'timer' ? timerReminderText(message) : message;
47
+ }
39
48
  export function turnModelTask(turn) {
40
49
  // A wake's message keeps its provenance in every later request: the agent's own reminder (or the comments an
41
50
  // Auto-fix wake brought) must not be replayed as something the user asked for.
42
- const woken = (message) => turn.wake === 'auto-fix' ? `Delivered by Auto-fix (not a message from the user): ${message}` : timerReminderText(message);
51
+ const woken = (message) => wakeMessageText(turn.wake ?? 'timer', message);
43
52
  const text = turn.direction === undefined
44
53
  ? (turn.wake === undefined ? turn.task : woken(turn.task))
45
54
  : `${turn.task}\n\n${turn.wake === undefined ? `Direction given when the attempt continued: ${turn.direction}` : `Delivered when the attempt continued: ${woken(turn.direction)}`}`;
@@ -78,8 +78,13 @@ export declare class SessionChangeStore {
78
78
  * The recorder a run's tools report their writes to. Only files inside `root` (the run's workspace folder)
79
79
  * are tracked: a delegated subagent writes in a worktree of its own, and its change reaches the workspace
80
80
  * through the landing, which reports the files it lands.
81
+ *
82
+ * `review` answers, as a write lands, whether the person reviews this run's writes. A run that does not
83
+ * ask (Full Access) adds no file to the pending set: its writes are kept as they land, and nothing waits
84
+ * on a Keep. A file already pending from a reviewed write stays tracked, so its entry and its Undo still
85
+ * describe what is on disk.
81
86
  */
82
- recorder(sessionId: string, workspace: string, onChange: (changes: AppServerSessionChanges) => void, onError?: (error: unknown) => void): FileChangeRecorder;
87
+ recorder(sessionId: string, workspace: string, onChange: (changes: AppServerSessionChanges) => void, onError?: (error: unknown) => void, review?: () => boolean): FileChangeRecorder;
83
88
  /** Records what a landed write left, for each file it wrote. The caller holds the session's lock. */
84
89
  private recordWrites;
85
90
  /** Updates one file's entry in `state`; answers whether the pending set changed. */
@@ -370,8 +370,13 @@ export class SessionChangeStore {
370
370
  * The recorder a run's tools report their writes to. Only files inside `root` (the run's workspace folder)
371
371
  * are tracked: a delegated subagent writes in a worktree of its own, and its change reaches the workspace
372
372
  * through the landing, which reports the files it lands.
373
+ *
374
+ * `review` answers, as a write lands, whether the person reviews this run's writes. A run that does not
375
+ * ask (Full Access) adds no file to the pending set: its writes are kept as they land, and nothing waits
376
+ * on a Keep. A file already pending from a reviewed write stays tracked, so its entry and its Undo still
377
+ * describe what is on disk.
373
378
  */
374
- recorder(sessionId, workspace, onChange, onError) {
379
+ recorder(sessionId, workspace, onChange, onError, review = () => true) {
375
380
  sessionChangesId(sessionId);
376
381
  let rootPromise;
377
382
  const root = () => rootPromise ??= realpath(workspace).catch(() => path.resolve(workspace));
@@ -451,7 +456,7 @@ export class SessionChangeStore {
451
456
  return;
452
457
  try {
453
458
  if (before.length) {
454
- const changes = await this.recordWrites(sessionId, canonicalRoot, tracked.map((entry, index) => ({ ...entry, before: before[index] })), spilled);
459
+ const changes = await this.recordWrites(sessionId, canonicalRoot, tracked.map((entry, index) => ({ ...entry, before: before[index] })), spilled, review());
455
460
  if (changes)
456
461
  onChange(changes);
457
462
  }
@@ -479,11 +484,11 @@ export class SessionChangeStore {
479
484
  };
480
485
  }
481
486
  /** Records what a landed write left, for each file it wrote. The caller holds the session's lock. */
482
- async recordWrites(sessionId, root, files, spilled = false) {
487
+ async recordWrites(sessionId, root, files, spilled = false, review = true) {
483
488
  const state = await readState(this.home, sessionId);
484
489
  let changed = false;
485
490
  for (const file of files)
486
- changed = await this.recordWrite(sessionId, state, root, file.relative, file.before, file.created) || changed;
491
+ changed = await this.recordWrite(sessionId, state, root, file.relative, file.before, file.created, review) || changed;
487
492
  if (!changed) {
488
493
  // Originals stored while the write began, for files it left as they were, are referenced by nothing.
489
494
  if (spilled)
@@ -496,10 +501,13 @@ export class SessionChangeStore {
496
501
  return snapshot(sessionId, state);
497
502
  }
498
503
  /** Updates one file's entry in `state`; answers whether the pending set changed. */
499
- async recordWrite(sessionId, state, root, relative, before, created) {
504
+ async recordWrite(sessionId, state, root, relative, before, created, review = true) {
500
505
  const target = path.join(root, ...relative.split('/'));
501
506
  if (before.kind === 'other')
502
507
  return false;
508
+ // A write nobody reviews starts no entry; one for a file already pending is still recorded.
509
+ if (!review && !state.changes.some(change => keyOf(change.root, change.path) === keyOf(root, relative)))
510
+ return false;
503
511
  const after = await observe(target, this.baselineLimit);
504
512
  if (after.kind === 'other')
505
513
  return false;
@@ -13,6 +13,11 @@ import type { TodoItem } from './todos.js';
13
13
  * A row carries styled segments rather than one color so a single row can pair a label with
14
14
  * a value in a semantic color (`+120` green beside `-8` red) the way the reference panel
15
15
  * does. Callers that only care about the text use {@link panelRowText}.
16
+ *
17
+ * Hue means state here as in the window: green for lines added (and a clean tree), red for lines
18
+ * removed and failures, and only where there is something to report - a zero count is gray.
19
+ * Progress, a step that was visited and a terminal that is running are neutral: the accent for
20
+ * what is live, a quiet gray for what is done.
16
21
  */
17
22
  /** The working-tree summary the Git section reports. Produced by `git-summary.ts`. */
18
23
  export interface PanelChanges {
@@ -132,7 +137,7 @@ export declare function panelDuration(milliseconds: number): string;
132
137
  /**
133
138
  * The panel's rows, top to bottom, for a terminal of `columns` x `height`.
134
139
  *
135
- * Sections are anchored: Git tools, Node, Progress and the plan read from the top, while the
140
+ * Sections are anchored: Git tools, Step, Progress and the plan read from the top, while the
136
141
  * terminal list and the graph zoom are held against the bottom - the reader asked for the graph
137
142
  * section to be at the bottom of the panel - with whatever rows the top sections leave as blank
138
143
  * space between them, so a tall terminal does not park the zoom in the middle of the screen.