@andorra-labs/code 0.1.10 → 0.1.12

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 (238) hide show
  1. package/README.md +31 -205
  2. package/THIRD_PARTY_NOTICES.md +30 -0
  3. package/dist/src/agent-execution.js +50 -2
  4. package/dist/src/agent-mcp.js +5 -0
  5. package/dist/src/app-server/protocol.d.ts +9 -1
  6. package/dist/src/app-server/protocol.js +1 -1
  7. package/dist/src/app-server.d.ts +49 -1
  8. package/dist/src/app-server.js +353 -64
  9. package/dist/src/automation-service.js +1 -1
  10. package/dist/src/browser-panel-tool.d.ts +24 -3
  11. package/dist/src/browser-panel-tool.js +80 -6
  12. package/dist/src/browser-runner.js +3 -1
  13. package/dist/src/browser-session.d.ts +8 -0
  14. package/dist/src/browser-session.js +27 -1
  15. package/dist/src/browser-ui/app.js +237 -15
  16. package/dist/src/browser-ui/index.html +5 -5
  17. package/dist/src/browser-ui/style.css +110 -65
  18. package/dist/src/browser-ui/tokens.css +27 -26
  19. package/dist/src/browser-view.d.ts +16 -0
  20. package/dist/src/browser-view.js +38 -2
  21. package/dist/src/claude-provider.js +15 -2
  22. package/dist/src/cli.d.ts +2 -1
  23. package/dist/src/cli.js +175 -43
  24. package/dist/src/code-intelligence/CodeIntelligenceManager.js +1 -1
  25. package/dist/src/codex-provider.js +6 -3
  26. package/dist/src/coding-tools.d.ts +26 -1
  27. package/dist/src/coding-tools.js +104 -33
  28. package/dist/src/command-screens.js +1 -1
  29. package/dist/src/commands.js +1 -1
  30. package/dist/src/completion-gates.d.ts +42 -7
  31. package/dist/src/completion-gates.js +55 -9
  32. package/dist/src/completion.d.ts +51 -1
  33. package/dist/src/completion.js +164 -5
  34. package/dist/src/config.d.ts +1 -0
  35. package/dist/src/config.js +2 -0
  36. package/dist/src/dashboard-view.js +2 -2
  37. package/dist/src/deadline.js +4 -0
  38. package/dist/src/decision/PreparedSteps.js +1 -1
  39. package/dist/src/delegation-changes.js +19 -2
  40. package/dist/src/diff-preview.d.ts +1 -0
  41. package/dist/src/diff-preview.js +12 -3
  42. package/dist/src/engine-streams.d.ts +22 -0
  43. package/dist/src/engine-streams.js +16 -0
  44. package/dist/src/extensions.js +17 -6
  45. package/dist/src/file-read-key.d.ts +8 -0
  46. package/dist/src/file-read-key.js +12 -0
  47. package/dist/src/graph-editor-session.js +2 -1
  48. package/dist/src/graph-health.d.ts +21 -0
  49. package/dist/src/graph-health.js +46 -0
  50. package/dist/src/graph-manager-chat.d.ts +52 -3
  51. package/dist/src/graph-manager-chat.js +62 -17
  52. package/dist/src/graph-runner.js +62 -5
  53. package/dist/src/graph-server.d.ts +1 -1
  54. package/dist/src/graph-server.js +48 -27
  55. package/dist/src/graph-sync.d.ts +8 -0
  56. package/dist/src/graph-sync.js +54 -3
  57. package/dist/src/graph-tool.js +1 -1
  58. package/dist/src/graph-ui/app.js +362 -123
  59. package/dist/src/graph-ui/controls.css +95 -22
  60. package/dist/src/graph-ui/controls.js +31 -1
  61. package/dist/src/graph-ui/embed.js +62 -13
  62. package/dist/src/graph-ui/icons.js +7 -0
  63. package/dist/src/graph-ui/index.html +4 -4
  64. package/dist/src/graph-ui/manager-state.js +143 -5
  65. package/dist/src/graph-ui/manager.css +21 -20
  66. package/dist/src/graph-ui/manager.js +337 -75
  67. package/dist/src/graph-ui/model-picker.js +279 -0
  68. package/dist/src/graph-ui/provider-glyphs/alibaba-cloud.png +0 -0
  69. package/dist/src/graph-ui/provider-glyphs/anthropic.png +0 -0
  70. package/dist/src/graph-ui/provider-glyphs/aws-bedrock.png +0 -0
  71. package/dist/src/graph-ui/provider-glyphs/claude.png +0 -0
  72. package/dist/src/graph-ui/provider-glyphs/deepseek.png +0 -0
  73. package/dist/src/graph-ui/provider-glyphs/fireworks.png +0 -0
  74. package/dist/src/graph-ui/provider-glyphs/kimi.png +0 -0
  75. package/dist/src/graph-ui/provider-glyphs/minimax.png +0 -0
  76. package/dist/src/graph-ui/provider-glyphs/openai.png +0 -0
  77. package/dist/src/graph-ui/provider-glyphs/opencode.png +0 -0
  78. package/dist/src/graph-ui/provider-glyphs/openrouter.png +0 -0
  79. package/dist/src/graph-ui/provider-glyphs/xai.png +0 -0
  80. package/dist/src/graph-ui/provider-glyphs/xiaomi-mimo.png +0 -0
  81. package/dist/src/graph-ui/provider-glyphs/zai.png +0 -0
  82. package/dist/src/graph-ui/skill-picker.js +1 -1
  83. package/dist/src/graph-ui/studio-canvas.js +8 -8
  84. package/dist/src/graph-ui/studio.css +18 -15
  85. package/dist/src/graph-ui/studio.js +92 -35
  86. package/dist/src/graph-ui/style.css +122 -79
  87. package/dist/src/graph-ui/theme.js +2 -2
  88. package/dist/src/graph-ui/tokens.css +33 -29
  89. package/dist/src/graphs.d.ts +5 -2
  90. package/dist/src/graphs.js +10 -9
  91. package/dist/src/mcp.d.ts +52 -14
  92. package/dist/src/mcp.js +285 -128
  93. package/dist/src/membership-errors.d.ts +7 -1
  94. package/dist/src/membership-errors.js +9 -3
  95. package/dist/src/memory/ProjectMemory.d.ts +77 -0
  96. package/dist/src/memory/ProjectMemory.js +310 -0
  97. package/dist/src/memory/index.d.ts +1 -0
  98. package/dist/src/memory/index.js +1 -0
  99. package/dist/src/opencode-provider.js +5 -6
  100. package/dist/src/package-name.d.ts +3 -0
  101. package/dist/src/package-name.js +3 -0
  102. package/dist/src/provider-engine.js +2 -2
  103. package/dist/src/pull-requests.d.ts +42 -6
  104. package/dist/src/pull-requests.js +11 -3
  105. package/dist/src/qa/runtime/PtyManager.js +2 -1
  106. package/dist/src/react-runtime.js +137 -22
  107. package/dist/src/read-document-doc.d.ts +20 -0
  108. package/dist/src/read-document-doc.js +524 -0
  109. package/dist/src/read-document-docx.d.ts +21 -0
  110. package/dist/src/read-document-docx.js +584 -0
  111. package/dist/src/read-document-text.d.ts +29 -0
  112. package/dist/src/read-document-text.js +67 -0
  113. package/dist/src/read-document-tool.d.ts +48 -0
  114. package/dist/src/read-document-tool.js +162 -0
  115. package/dist/src/read-document.d.ts +78 -0
  116. package/dist/src/read-document.js +353 -0
  117. package/dist/src/read-image.d.ts +29 -2
  118. package/dist/src/read-image.js +42 -17
  119. package/dist/src/remote/cert.d.ts +1 -1
  120. package/dist/src/remote/cert.js +2 -7
  121. package/dist/src/remote/client.js +1 -1
  122. package/dist/src/remote/pem.d.ts +6 -0
  123. package/dist/src/remote/pem.js +11 -0
  124. package/dist/src/run-records.js +49 -10
  125. package/dist/src/runtime.d.ts +21 -0
  126. package/dist/src/runtime.js +10 -1
  127. package/dist/src/session-changes.d.ts +6 -1
  128. package/dist/src/session-changes.js +13 -5
  129. package/dist/src/sessions.d.ts +3 -1
  130. package/dist/src/sessions.js +5 -3
  131. package/dist/src/side-panel.d.ts +6 -1
  132. package/dist/src/side-panel.js +12 -10
  133. package/dist/src/sign-in-detection.d.ts +82 -0
  134. package/dist/src/sign-in-detection.js +197 -0
  135. package/dist/src/sign-in-offer.d.ts +35 -0
  136. package/dist/src/sign-in-offer.js +116 -0
  137. package/dist/src/skills/bundled/create-skill/SKILL.md +1 -1
  138. package/dist/src/skills/bundled/diagram/SKILL.md +1 -1
  139. package/dist/src/skills/bundled/graph-manager/SKILL.md +59 -7
  140. package/dist/src/skills/bundled/graph-manager/patterns.md +27 -0
  141. package/dist/src/skills/bundled/provenance.json +4 -4
  142. package/dist/src/skills/runtime-skills.d.ts +6 -0
  143. package/dist/src/skills/runtime-skills.js +16 -3
  144. package/dist/src/stall-recovery.d.ts +6 -2
  145. package/dist/src/stall-recovery.js +7 -2
  146. package/dist/src/stray-files.d.ts +14 -0
  147. package/dist/src/stray-files.js +81 -0
  148. package/dist/src/subagent-run.js +6 -1
  149. package/dist/src/terminal-ui.d.ts +1 -1
  150. package/dist/src/terminal-ui.js +11 -5
  151. package/dist/src/time-limit.d.ts +53 -0
  152. package/dist/src/time-limit.js +79 -0
  153. package/dist/src/tool-activity.js +1 -1
  154. package/dist/src/tool-schema-compatibility.d.ts +7 -2
  155. package/dist/src/tool-schema-compatibility.js +8 -4
  156. package/dist/src/tools.js +92 -7
  157. package/dist/src/transcript.d.ts +5 -0
  158. package/dist/src/transcript.js +12 -4
  159. package/dist/src/types.d.ts +8 -0
  160. package/dist/src/untracked-file-removal.d.ts +3 -0
  161. package/dist/src/untracked-file-removal.js +125 -0
  162. package/dist/src/update-check.js +1 -1
  163. package/dist/src/update.d.ts +11 -1
  164. package/dist/src/update.js +27 -5
  165. package/dist/src/usage-analytics.d.ts +3 -1
  166. package/dist/src/usage-analytics.js +16 -2
  167. package/dist/src/workspace-git-metadata.d.ts +15 -0
  168. package/dist/src/workspace-git-metadata.js +50 -1
  169. package/dist/src/workspace-instructions.js +1 -1
  170. package/package.json +6 -26
  171. package/docs/README.md +0 -36
  172. package/docs/agents/README.md +0 -62
  173. package/docs/agents/install-for-agents.md +0 -56
  174. package/docs/agents/mcp-server.md +0 -212
  175. package/docs/agents/subagent-mode.md +0 -149
  176. package/docs/concepts/README.md +0 -47
  177. package/docs/concepts/jev-actionable-routing.md +0 -113
  178. package/docs/concepts/jev-decision-thresholds.md +0 -412
  179. package/docs/concepts/jev-efficiency.md +0 -217
  180. package/docs/concepts/jev-eval-2026-11-01.md +0 -78
  181. package/docs/concepts/limits.md +0 -52
  182. package/docs/concepts/memory.md +0 -10
  183. package/docs/concepts/security.md +0 -50
  184. package/docs/concepts/workspace-instructions.md +0 -29
  185. package/docs/getting-started/README.md +0 -82
  186. package/docs/getting-started/accounts.md +0 -78
  187. package/docs/getting-started/configure-providers.md +0 -132
  188. package/docs/guides/README.md +0 -13
  189. package/docs/guides/browser.md +0 -39
  190. package/docs/guides/desktop-app.md +0 -414
  191. package/docs/guides/extensions.md +0 -102
  192. package/docs/guides/graph-builder.md +0 -116
  193. package/docs/guides/headless.md +0 -46
  194. package/docs/guides/tui.md +0 -75
  195. package/docs/guides/update.md +0 -70
  196. package/docs/guides/web-search.md +0 -51
  197. package/docs/guides/windows-code-signing.md +0 -319
  198. package/docs/llms.txt +0 -45
  199. package/docs/reference/README.md +0 -7
  200. package/docs/reference/cli.md +0 -76
  201. package/docs/reference/config.md +0 -91
  202. package/docs/reference/slash-commands.md +0 -59
  203. package/docs/superpowers/plans/2026-11-01-claude-console-sign-in.md +0 -111
  204. package/docs/superpowers/plans/2026-11-01-jev-node-opt-in.md +0 -910
  205. package/docs/superpowers/plans/2026-11-02-workflow-pane.md +0 -398
  206. package/docs/superpowers/plans/2026-11-06-graph-soft-delete.md +0 -125
  207. package/docs/superpowers/plans/2026-11-09-orchestrator-delegation.md +0 -295
  208. package/docs/superpowers/plans/2026-11-13-graph-manager-chat.md +0 -203
  209. package/docs/superpowers/plans/2026-11-14-jev-fair-use-pricing.md +0 -79
  210. package/docs/superpowers/specs/2026-10-31-work-line-summary-design.md +0 -50
  211. package/docs/superpowers/specs/2026-11-01-claude-console-sign-in-design.md +0 -176
  212. package/docs/superpowers/specs/2026-11-01-jev-node-opt-in-design.md +0 -164
  213. package/docs/superpowers/specs/2026-11-01-pr-section-design.md +0 -111
  214. package/docs/superpowers/specs/2026-11-02-workflow-pane-design.md +0 -130
  215. package/docs/superpowers/specs/2026-11-06-bundled-skills-design.md +0 -206
  216. package/docs/superpowers/specs/2026-11-09-orchestrator-delegation-design.md +0 -291
  217. package/docs/superpowers/specs/2026-11-13-graph-manager-chat-design.md +0 -182
  218. package/docs/superpowers/specs/2026-11-14-jev-fair-use-pricing-design.md +0 -156
  219. package/scripts/jev-efficiency-eval.mjs +0 -187
  220. package/scripts/jev-efficiency-live.mjs +0 -193
  221. package/scripts/zcode-engine-replay.mjs +0 -223
  222. package/tests/agent-centric-mcp-test-plan.md +0 -208
  223. package/tests/analytics-settings-test-plan.md +0 -165
  224. package/tests/browser-cli-smoke.mjs +0 -276
  225. package/tests/browser-test-plan.md +0 -280
  226. package/tests/chat-side-panel-test-plan.md +0 -309
  227. package/tests/decision-engine-test-plan.md +0 -163
  228. package/tests/default-active-jev-test-plan.md +0 -85
  229. package/tests/harness-extensions-test-plan.md +0 -113
  230. package/tests/jev-all-decisions-test-plan.md +0 -156
  231. package/tests/jev-efficiency/criteria.json +0 -158
  232. package/tests/jev-efficiency/workloads.mjs +0 -242
  233. package/tests/jev-efficiency-test-plan.md +0 -198
  234. package/tests/permissions-sandbox-probe.mjs +0 -74
  235. package/tests/permissions-test-plan.md +0 -191
  236. package/tests/product-telemetry-test-plan.md +0 -536
  237. package/tests/thinking-stream-preview-test-plan.md +0 -136
  238. package/tests/zcode-react-engine-test-plan.md +0 -396
@@ -0,0 +1,67 @@
1
+ /**
2
+ * Text plumbing shared by the document readers behind Read.
3
+ *
4
+ * The Word readers (`read-document-docx.ts`, `read-document-doc.ts`) both reduce a document to the
5
+ * same few block shapes, and both the legacy `.doc` reader and the non-UTF-8 text path need
6
+ * Windows-1252. Keeping those here stops the two Word formats drifting apart in how a paragraph,
7
+ * a list item or a table row reads to the model.
8
+ */
9
+ /**
10
+ * 0x80-0x9F in Windows-1252. The five bytes the code page leaves undefined map to the C1 control
11
+ * with the same value, as browsers do, so decoding never fails and never shifts an offset.
12
+ *
13
+ * Node's `TextDecoder('windows-1252')` needs full ICU; a small-icu build only has UTF-8 and UTF-16,
14
+ * so the table is spelled out here rather than depending on how Node was compiled.
15
+ */
16
+ const WINDOWS_1252_HIGH = '€\u0081‚ƒ„…†‡ˆ‰Š‹Œ\u008DŽ\u008F'
17
+ + '\u0090‘’“”•–—˜™š›œ\u009DžŸ';
18
+ /** One UTF-16 code unit per input byte, which the `.doc` reader relies on to index text by character position. */
19
+ export function decodeWindows1252(bytes) {
20
+ const text = Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength).toString('latin1');
21
+ return /[\x80-\x9f]/.test(text) ? text.replace(/[\x80-\x9f]/g, char => WINDOWS_1252_HIGH[char.charCodeAt(0) - 0x80]) : text;
22
+ }
23
+ /** The marker both Word readers print where the author forced a new page. */
24
+ export const PAGE_BREAK_LINE = '--- page break ---';
25
+ export function headingBlock(level, text) {
26
+ return { kind: 'paragraph', text: `${'#'.repeat(Math.min(Math.max(level, 1), 6))} ${text}` };
27
+ }
28
+ export function listBlock(level, text) {
29
+ // Continuation lines of an item (manual line breaks) are indented under the marker so the item stays one item.
30
+ const indent = ' '.repeat(Math.min(Math.max(level, 0), 8));
31
+ return { kind: 'list', text: `${indent}- ${text.replace(/\n/g, `\n${indent} `)}` };
32
+ }
33
+ /** A table row on one line. Cell text is flattened because a line break inside a cell would split the row. */
34
+ export function rowBlock(cells) {
35
+ const flat = cells.map(cell => cell.replace(/\s*\n\s*/g, ' ').trim());
36
+ return flat.some(Boolean) ? { kind: 'row', text: flat.join(' | ') } : undefined;
37
+ }
38
+ /** Trailing whitespace per line and blank lines at either end carry nothing for a reader. */
39
+ export function tidyText(text) {
40
+ return text.replace(/\r\n?/g, '\n').replace(/[ \t ]+$/gm, '').replace(/^\n+|\n+$/g, '');
41
+ }
42
+ export function joinBlocks(blocks) {
43
+ let text = '';
44
+ let previous;
45
+ for (const block of blocks) {
46
+ // A break at the very start, or two in a row, would only print noise.
47
+ if (block.kind === 'break' && (!previous || previous.kind === 'break'))
48
+ continue;
49
+ const line = block.kind === 'break' ? PAGE_BREAK_LINE : block.text;
50
+ if (previous)
51
+ text += previous.kind === block.kind && (block.kind === 'list' || block.kind === 'row') ? '\n' : '\n\n';
52
+ text += line;
53
+ previous = block;
54
+ }
55
+ return tidyText(previous?.kind === 'break' ? text.slice(0, -PAGE_BREAK_LINE.length) : text);
56
+ }
57
+ /** "2, 5-7" for a sorted list of page numbers, so a note about many pages stays one short line. */
58
+ export function formatRanges(numbers) {
59
+ const parts = [];
60
+ for (let index = 0; index < numbers.length; index++) {
61
+ const start = numbers[index];
62
+ while (index + 1 < numbers.length && numbers[index + 1] === numbers[index] + 1)
63
+ index++;
64
+ parts.push(numbers[index] === start ? String(start) : `${start}-${numbers[index]}`);
65
+ }
66
+ return parts.join(', ');
67
+ }
@@ -0,0 +1,48 @@
1
+ import type { ToolContext } from './types.js';
2
+ /**
3
+ * Documents through Read: PDF, Word and text in an older encoding.
4
+ *
5
+ * Read used to answer "Binary files are not supported" for anything that was not UTF-8 text or an
6
+ * image. An agent given a task whose input was a PDF then spent its run installing a PDF library
7
+ * (often impossible in the task's environment) or writing its own rasteriser, and read the result
8
+ * wrong. Read now returns what such a file says: the extracted text, paged with the same offset
9
+ * and limit as a text file, and for a PDF the pages themselves as images when asked, which is the
10
+ * only way to read a scan, a figure or a score.
11
+ *
12
+ * What comes back is a rendering of the file, not its bytes, so it is never recorded as a text
13
+ * read: Edit and Write keep refusing a file they have only seen this way.
14
+ */
15
+ /** Largest document Read will open. The extracted text is paged, so this bounds memory, not output. */
16
+ export declare const READ_DOCUMENT_FILE_LIMIT: number;
17
+ /** PDF pages one Read call returns as images; the response's image budget still applies across calls. */
18
+ export declare const READ_PDF_RENDER_PAGES = 4;
19
+ export interface DocumentReadOptions {
20
+ /** 1-based first line of the extracted text; 0 and undefined mean the first line. */
21
+ offset?: number;
22
+ /** Lines to return at most. */
23
+ limit: number;
24
+ /** PDF pages to read, such as "3", "2-5" or "1,4,7-9". */
25
+ pages?: string;
26
+ /** Return the selected PDF pages as images instead of their text. */
27
+ render?: boolean;
28
+ /** The runtime's cap on one tool result; the page stops on the last whole line that fits. */
29
+ maxOutput: number;
30
+ /** A longer line is truncated, so one unbroken line cannot fill the window. */
31
+ maxLineChars: number;
32
+ }
33
+ /**
34
+ * The 1-based pages a `pages` argument names, in the order given and without repeats.
35
+ * Accepts single pages and ranges separated by commas: "3", "2-5", "1,4,7-9".
36
+ */
37
+ export declare function parsePageSelection(spec: string, pageCount: number): number[];
38
+ /**
39
+ * The observation for a PDF or Word file, or undefined when the bytes are not a document Read
40
+ * understands (an ordinary zip, a spreadsheet's compound file), so the caller reports it as it
41
+ * always has.
42
+ */
43
+ export declare function readDocumentObservation(context: ToolContext, shownPath: string, bytes: Buffer, options: DocumentReadOptions): Promise<string | undefined>;
44
+ /** The observation for a text file in an older encoding, decoded for reading only. */
45
+ export declare function legacyTextObservation(shownPath: string, decoded: {
46
+ text: string;
47
+ encoding: string;
48
+ }, options: DocumentReadOptions): string;
@@ -0,0 +1,162 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { extractDocument, renderPdfPages } from './read-document.js';
3
+ import { READ_IMAGE_MAX_EDGE, holdReadImages, prepareReadImage } from './read-image.js';
4
+ import { formatBytes } from './attachments.js';
5
+ /**
6
+ * Documents through Read: PDF, Word and text in an older encoding.
7
+ *
8
+ * Read used to answer "Binary files are not supported" for anything that was not UTF-8 text or an
9
+ * image. An agent given a task whose input was a PDF then spent its run installing a PDF library
10
+ * (often impossible in the task's environment) or writing its own rasteriser, and read the result
11
+ * wrong. Read now returns what such a file says: the extracted text, paged with the same offset
12
+ * and limit as a text file, and for a PDF the pages themselves as images when asked, which is the
13
+ * only way to read a scan, a figure or a score.
14
+ *
15
+ * What comes back is a rendering of the file, not its bytes, so it is never recorded as a text
16
+ * read: Edit and Write keep refusing a file they have only seen this way.
17
+ */
18
+ /** Largest document Read will open. The extracted text is paged, so this bounds memory, not output. */
19
+ export const READ_DOCUMENT_FILE_LIMIT = 64 * 1024 * 1024;
20
+ /** PDF pages one Read call returns as images; the response's image budget still applies across calls. */
21
+ export const READ_PDF_RENDER_PAGES = 4;
22
+ /** Extracted documents kept between calls, so paging through one does not parse it again per page. */
23
+ const CACHE_LIMIT = 3;
24
+ const LABEL = { pdf: 'PDF', docx: 'Word document', doc: 'Word 97-2003 document' };
25
+ const cache = new Map();
26
+ /**
27
+ * The 1-based pages a `pages` argument names, in the order given and without repeats.
28
+ * Accepts single pages and ranges separated by commas: "3", "2-5", "1,4,7-9".
29
+ */
30
+ export function parsePageSelection(spec, pageCount) {
31
+ const selected = [];
32
+ const parts = spec.split(',').map(part => part.trim()).filter(Boolean);
33
+ if (!parts.length)
34
+ throw new Error('pages must name at least one page, such as "3" or "2-5"');
35
+ for (const part of parts) {
36
+ const match = /^(\d+)(?:\s*-\s*(\d+))?$/.exec(part);
37
+ if (!match)
38
+ throw new Error(`pages must be page numbers and ranges such as "3", "2-5" or "1,4,7-9"; got "${part}"`);
39
+ const first = Number(match[1]), last = match[2] === undefined ? first : Number(match[2]);
40
+ if (first < 1 || last < first)
41
+ throw new Error(`pages "${part}" is not a valid range; pages are numbered from 1`);
42
+ if (first > pageCount)
43
+ throw new Error(`pages "${part}" is beyond the end of the document (${pageCount} ${pageCount === 1 ? 'page' : 'pages'})`);
44
+ for (let page = first; page <= Math.min(last, pageCount); page++)
45
+ if (!selected.includes(page))
46
+ selected.push(page);
47
+ }
48
+ return selected;
49
+ }
50
+ /** One page of numbered lines under a header, shaped like a text Read so `offset` continues it. */
51
+ function pageOfLines(header, lines, options, what) {
52
+ while (lines.length && !lines.at(-1).trim())
53
+ lines.pop();
54
+ if (!lines.length)
55
+ return `${header}\n[No text]`;
56
+ const first = Math.max(1, options.offset ?? 1);
57
+ if (first > lines.length)
58
+ throw new Error(`Offset ${first} is beyond the end of ${what} (${lines.length} lines total)`);
59
+ const lastRequested = Math.min(lines.length, first + options.limit - 1);
60
+ const budget = options.maxOutput - 200 - header.length;
61
+ let rendered = '', emittedLast = first - 1;
62
+ for (let line = first; line <= lastRequested; line++) {
63
+ const body = lines[line - 1] ?? '';
64
+ const shown = body.length > options.maxLineChars ? `${body.slice(0, options.maxLineChars)}... (line truncated to ${options.maxLineChars} chars)` : body;
65
+ const next = `${line}\t${shown}${line < lastRequested ? '\n' : ''}`;
66
+ if (rendered.length + next.length > budget)
67
+ break;
68
+ rendered += next;
69
+ emittedLast = line;
70
+ }
71
+ if (emittedLast < first) {
72
+ rendered = `${first}\t${(lines[first - 1] ?? '').slice(0, Math.max(0, Math.min(options.maxLineChars, budget - 16)))}`;
73
+ emittedLast = first;
74
+ }
75
+ const more = emittedLast < lines.length ? `\n[Showing lines ${first}-${emittedLast} of ${lines.length} of ${what}. Use offset=${emittedLast + 1} to continue.]` : '';
76
+ return `${header}\n${rendered.replace(/\n$/, '')}${more}`;
77
+ }
78
+ async function extracted(bytes, signal) {
79
+ const key = createHash('sha1').update(bytes).digest('hex');
80
+ const known = cache.get(key);
81
+ if (known)
82
+ return known;
83
+ const document = await extractDocument(bytes, signal);
84
+ if (document) {
85
+ cache.set(key, document);
86
+ while (cache.size > CACHE_LIMIT)
87
+ cache.delete(cache.keys().next().value);
88
+ }
89
+ return document;
90
+ }
91
+ /**
92
+ * The observation for a PDF or Word file, or undefined when the bytes are not a document Read
93
+ * understands (an ordinary zip, a spreadsheet's compound file), so the caller reports it as it
94
+ * always has.
95
+ */
96
+ export async function readDocumentObservation(context, shownPath, bytes, options) {
97
+ const document = await extracted(bytes, context.signal);
98
+ if (!document)
99
+ return undefined;
100
+ context.signal.throwIfAborted();
101
+ const size = formatBytes(bytes.length);
102
+ const notes = document.notes.length ? ` ${document.notes.join(' ')}` : '';
103
+ if (document.kind !== 'pdf') {
104
+ if (options.pages !== undefined || options.render)
105
+ throw new Error('pages and render apply to PDF files only; page through this document with offset and limit.');
106
+ const header = `[${LABEL[document.kind]} ${shownPath} (${size}): its text follows. This is extracted text, not the file itself, so Edit and Write cannot change the document.${notes}]`;
107
+ return pageOfLines(header, document.text.split('\n'), options, 'the extracted text');
108
+ }
109
+ const pages = document.pages ?? [];
110
+ const count = document.pageCount ?? pages.length;
111
+ const selected = options.pages === undefined ? pages.map(page => page.page) : parsePageSelection(options.pages, count);
112
+ if (options.render) {
113
+ if (selected.length > READ_PDF_RENDER_PAGES) {
114
+ throw new Error(options.pages === undefined
115
+ ? `render returns at most ${READ_PDF_RENDER_PAGES} pages per call and this PDF has ${count}; name them, such as pages="1-${READ_PDF_RENDER_PAGES}".`
116
+ : `render returns at most ${READ_PDF_RENDER_PAGES} pages per call; pages="${options.pages}" names ${selected.length}. Ask for fewer and continue in further calls.`);
117
+ }
118
+ const rendered = await renderPdfPages(bytes, selected, { maxEdge: READ_IMAGE_MAX_EDGE, signal: context.signal });
119
+ const images = [], shown = [];
120
+ const prepared = [];
121
+ try {
122
+ for (const page of rendered) {
123
+ const ready = await prepareReadImage(context, { mimeType: page.mimeType, bytes: page.data });
124
+ prepared.push(ready);
125
+ images.push(ready.image);
126
+ shown.push(`page ${page.page} (${ready.width}x${ready.height})`);
127
+ }
128
+ }
129
+ catch (error) {
130
+ // The call returns all of its pages or none. A page that did not fit the response's image
131
+ // budget fails the call, and the pages prepared before it are never delivered, so the room
132
+ // they took is given back for the other reads in the batch.
133
+ for (const ready of prepared)
134
+ ready.release();
135
+ throw error;
136
+ }
137
+ const output = `PDF ${shownPath} (${count} ${count === 1 ? 'page' : 'pages'}, ${size}): ${shown.join(', ')} ${images.length === 1 ? 'is attached to this result as an image' : 'are attached to this result as images, in that order'}.`;
138
+ holdReadImages(output, images);
139
+ return output;
140
+ }
141
+ const lines = [];
142
+ for (const number of selected) {
143
+ const text = pages[number - 1]?.text ?? '';
144
+ lines.push(`--- Page ${number} of ${count} ---`);
145
+ if (text.trim())
146
+ lines.push(...text.split('\n'));
147
+ else
148
+ lines.push(`[No extractable text on this page: it is a scan or a drawing. Read it with pages="${number}" and render=true to see it as an image.]`);
149
+ lines.push('');
150
+ }
151
+ const scope = options.pages === undefined ? '' : `, pages ${options.pages}`;
152
+ const header = `[PDF ${shownPath} (${count} ${count === 1 ? 'page' : 'pages'}, ${size})${scope}: its text follows. To see a page as an image (figures, tables, scans, scores) add pages="N" and render=true. This is extracted text, so Edit and Write cannot change the document.${notes}]`;
153
+ return pageOfLines(header, lines, options, 'the extracted text');
154
+ }
155
+ /** The observation for a text file in an older encoding, decoded for reading only. */
156
+ export function legacyTextObservation(shownPath, decoded, options) {
157
+ if (options.pages !== undefined || options.render)
158
+ throw new Error('pages and render apply to PDF files only; page through this file with offset and limit.');
159
+ const header = `[${shownPath} is not UTF-8; it is shown decoded as ${decoded.encoding}. Edit and Write cannot change it in this encoding: convert it to UTF-8 with a script first if it has to be edited.]`;
160
+ const lines = decoded.text.replace(/\r\n?/g, '\n').split('\n');
161
+ return pageOfLines(header, lines, options, 'the file');
162
+ }
@@ -0,0 +1,78 @@
1
+ /**
2
+ * Documents through Read: PDF, Word (`.docx` and legacy `.doc`) and text that is not UTF-8.
3
+ *
4
+ * Read used to answer "binary files are not supported" for all of these, and an agent handed a PDF
5
+ * then spent its run writing a rasteriser by hand. This module turns a document into what a model
6
+ * can use directly: the text, page by page for a PDF, and PDF pages as PNG images so a vision
7
+ * model can look at a scanned page, a figure or a score that has no text layer at all.
8
+ *
9
+ * It only converts bytes. Deciding what to read, how much of it to show and which pages to render
10
+ * is the Read tool's job, so nothing here touches the file system or the tool context.
11
+ *
12
+ * PDF goes through PDFium compiled to WebAssembly (`@hyzyla/pdfium`): the one engine that both
13
+ * extracts text and rasterises without a native addon or a system package, so it behaves the same
14
+ * in a bare container and on every desktop platform. The Word formats and legacy text are read by
15
+ * the small parsers in `read-document-docx.ts`, `read-document-doc.ts` and `read-document-text.ts`.
16
+ */
17
+ export type DocumentKind = 'pdf' | 'docx' | 'doc';
18
+ export interface DocumentPage {
19
+ page: number;
20
+ text: string;
21
+ }
22
+ export interface ExtractedDocument {
23
+ kind: DocumentKind;
24
+ /** PDF only. */
25
+ pageCount?: number;
26
+ /** PDF only: every page, in order, 1-based. `text` is '' for a page with no text layer. */
27
+ pages?: DocumentPage[];
28
+ /** `.docx` and `.doc`: the whole document as plain text with light markdown. '' for a PDF. */
29
+ text: string;
30
+ /** Facts the reader should be told, such as pages without text or content that was left out. */
31
+ notes: string[];
32
+ }
33
+ export interface RenderedPage {
34
+ page: number;
35
+ mimeType: 'image/png';
36
+ data: Buffer;
37
+ width: number;
38
+ height: number;
39
+ }
40
+ /**
41
+ * By leading bytes only. `'zip'` and `'cfb'` are containers that may or may not hold a Word
42
+ * document; `extractDocument` decides.
43
+ *
44
+ * The PDF signature must open the file (after at most a byte-order mark and white space). PDF
45
+ * viewers also accept it anywhere in the first kilobyte, but so would any source file or note that
46
+ * mentions the signature near its top, and those must keep reading as text.
47
+ */
48
+ export declare function sniffDocument(head: Uint8Array): 'pdf' | 'zip' | 'cfb' | undefined;
49
+ /**
50
+ * Text and structure of a document.
51
+ *
52
+ * Resolves undefined when the bytes are not a supported document (a ZIP that is not a `.docx`, a
53
+ * compound file that is not a Word document), so the caller can fall back to its binary-file
54
+ * error. Rejects when the bytes are a supported document that cannot be read (encrypted, damaged,
55
+ * too large once inflated); the message is written for the model and says what to do instead.
56
+ */
57
+ export declare function extractDocument(bytes: Buffer, signal?: AbortSignal): Promise<ExtractedDocument | undefined>;
58
+ /**
59
+ * Rasterise the given 1-based pages on a white background, longest edge `options.maxEdge` pixels.
60
+ * Pages come back in the order asked for. Rejects for a page number the document does not have.
61
+ */
62
+ export declare function renderPdfPages(bytes: Buffer, pages: number[], options: {
63
+ maxEdge: number;
64
+ signal?: AbortSignal;
65
+ }): Promise<RenderedPage[]>;
66
+ /**
67
+ * Text that is not valid UTF-8: UTF-16 (marked by a byte-order mark, or recognisable without one),
68
+ * else Windows-1252 when the bytes look like text. Undefined for binary data.
69
+ *
70
+ * Call it only after UTF-8 decoding has failed: valid UTF-8 would be accepted here as Windows-1252
71
+ * and come back as mojibake. Windows-1252 is the fallback because it is what Windows tools wrote
72
+ * for decades and it assigns a character to every byte, so text in another 8-bit code page still
73
+ * comes through with its ASCII intact rather than being refused as binary.
74
+ */
75
+ export declare function decodeLegacyText(bytes: Buffer): {
76
+ text: string;
77
+ encoding: 'utf-16le' | 'utf-16be' | 'windows-1252';
78
+ } | undefined;