@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.
- package/README.md +31 -205
- package/THIRD_PARTY_NOTICES.md +30 -0
- package/dist/src/agent-execution.js +50 -2
- package/dist/src/agent-mcp.js +5 -0
- package/dist/src/app-server/protocol.d.ts +9 -1
- package/dist/src/app-server/protocol.js +1 -1
- package/dist/src/app-server.d.ts +49 -1
- package/dist/src/app-server.js +353 -64
- package/dist/src/automation-service.js +1 -1
- package/dist/src/browser-panel-tool.d.ts +24 -3
- package/dist/src/browser-panel-tool.js +80 -6
- package/dist/src/browser-runner.js +3 -1
- package/dist/src/browser-session.d.ts +8 -0
- package/dist/src/browser-session.js +27 -1
- package/dist/src/browser-ui/app.js +237 -15
- package/dist/src/browser-ui/index.html +5 -5
- package/dist/src/browser-ui/style.css +110 -65
- package/dist/src/browser-ui/tokens.css +27 -26
- package/dist/src/browser-view.d.ts +16 -0
- package/dist/src/browser-view.js +38 -2
- package/dist/src/claude-provider.js +15 -2
- package/dist/src/cli.d.ts +2 -1
- package/dist/src/cli.js +175 -43
- package/dist/src/code-intelligence/CodeIntelligenceManager.js +1 -1
- package/dist/src/codex-provider.js +6 -3
- package/dist/src/coding-tools.d.ts +26 -1
- package/dist/src/coding-tools.js +104 -33
- package/dist/src/command-screens.js +1 -1
- package/dist/src/commands.js +1 -1
- package/dist/src/completion-gates.d.ts +42 -7
- package/dist/src/completion-gates.js +55 -9
- package/dist/src/completion.d.ts +51 -1
- package/dist/src/completion.js +164 -5
- package/dist/src/config.d.ts +1 -0
- package/dist/src/config.js +2 -0
- package/dist/src/dashboard-view.js +2 -2
- package/dist/src/deadline.js +4 -0
- package/dist/src/decision/PreparedSteps.js +1 -1
- package/dist/src/delegation-changes.js +19 -2
- package/dist/src/diff-preview.d.ts +1 -0
- package/dist/src/diff-preview.js +12 -3
- package/dist/src/engine-streams.d.ts +22 -0
- package/dist/src/engine-streams.js +16 -0
- package/dist/src/extensions.js +17 -6
- package/dist/src/file-read-key.d.ts +8 -0
- package/dist/src/file-read-key.js +12 -0
- package/dist/src/graph-editor-session.js +2 -1
- package/dist/src/graph-health.d.ts +21 -0
- package/dist/src/graph-health.js +46 -0
- package/dist/src/graph-manager-chat.d.ts +52 -3
- package/dist/src/graph-manager-chat.js +62 -17
- package/dist/src/graph-runner.js +62 -5
- package/dist/src/graph-server.d.ts +1 -1
- package/dist/src/graph-server.js +48 -27
- package/dist/src/graph-sync.d.ts +8 -0
- package/dist/src/graph-sync.js +54 -3
- package/dist/src/graph-tool.js +1 -1
- package/dist/src/graph-ui/app.js +362 -123
- package/dist/src/graph-ui/controls.css +95 -22
- package/dist/src/graph-ui/controls.js +31 -1
- package/dist/src/graph-ui/embed.js +62 -13
- package/dist/src/graph-ui/icons.js +7 -0
- package/dist/src/graph-ui/index.html +4 -4
- package/dist/src/graph-ui/manager-state.js +143 -5
- package/dist/src/graph-ui/manager.css +21 -20
- package/dist/src/graph-ui/manager.js +337 -75
- package/dist/src/graph-ui/model-picker.js +279 -0
- package/dist/src/graph-ui/provider-glyphs/alibaba-cloud.png +0 -0
- package/dist/src/graph-ui/provider-glyphs/anthropic.png +0 -0
- package/dist/src/graph-ui/provider-glyphs/aws-bedrock.png +0 -0
- package/dist/src/graph-ui/provider-glyphs/claude.png +0 -0
- package/dist/src/graph-ui/provider-glyphs/deepseek.png +0 -0
- package/dist/src/graph-ui/provider-glyphs/fireworks.png +0 -0
- package/dist/src/graph-ui/provider-glyphs/kimi.png +0 -0
- package/dist/src/graph-ui/provider-glyphs/minimax.png +0 -0
- package/dist/src/graph-ui/provider-glyphs/openai.png +0 -0
- package/dist/src/graph-ui/provider-glyphs/opencode.png +0 -0
- package/dist/src/graph-ui/provider-glyphs/openrouter.png +0 -0
- package/dist/src/graph-ui/provider-glyphs/xai.png +0 -0
- package/dist/src/graph-ui/provider-glyphs/xiaomi-mimo.png +0 -0
- package/dist/src/graph-ui/provider-glyphs/zai.png +0 -0
- package/dist/src/graph-ui/skill-picker.js +1 -1
- package/dist/src/graph-ui/studio-canvas.js +8 -8
- package/dist/src/graph-ui/studio.css +18 -15
- package/dist/src/graph-ui/studio.js +92 -35
- package/dist/src/graph-ui/style.css +122 -79
- package/dist/src/graph-ui/theme.js +2 -2
- package/dist/src/graph-ui/tokens.css +33 -29
- package/dist/src/graphs.d.ts +5 -2
- package/dist/src/graphs.js +10 -9
- package/dist/src/mcp.d.ts +52 -14
- package/dist/src/mcp.js +285 -128
- package/dist/src/membership-errors.d.ts +7 -1
- package/dist/src/membership-errors.js +9 -3
- package/dist/src/memory/ProjectMemory.d.ts +77 -0
- package/dist/src/memory/ProjectMemory.js +310 -0
- package/dist/src/memory/index.d.ts +1 -0
- package/dist/src/memory/index.js +1 -0
- package/dist/src/opencode-provider.js +5 -6
- package/dist/src/package-name.d.ts +3 -0
- package/dist/src/package-name.js +3 -0
- package/dist/src/provider-engine.js +2 -2
- package/dist/src/pull-requests.d.ts +42 -6
- package/dist/src/pull-requests.js +11 -3
- package/dist/src/qa/runtime/PtyManager.js +2 -1
- package/dist/src/react-runtime.js +137 -22
- package/dist/src/read-document-doc.d.ts +20 -0
- package/dist/src/read-document-doc.js +524 -0
- package/dist/src/read-document-docx.d.ts +21 -0
- package/dist/src/read-document-docx.js +584 -0
- package/dist/src/read-document-text.d.ts +29 -0
- package/dist/src/read-document-text.js +67 -0
- package/dist/src/read-document-tool.d.ts +48 -0
- package/dist/src/read-document-tool.js +162 -0
- package/dist/src/read-document.d.ts +78 -0
- package/dist/src/read-document.js +353 -0
- package/dist/src/read-image.d.ts +29 -2
- package/dist/src/read-image.js +42 -17
- package/dist/src/remote/cert.d.ts +1 -1
- package/dist/src/remote/cert.js +2 -7
- package/dist/src/remote/client.js +1 -1
- package/dist/src/remote/pem.d.ts +6 -0
- package/dist/src/remote/pem.js +11 -0
- package/dist/src/run-records.js +49 -10
- package/dist/src/runtime.d.ts +21 -0
- package/dist/src/runtime.js +10 -1
- package/dist/src/session-changes.d.ts +6 -1
- package/dist/src/session-changes.js +13 -5
- package/dist/src/sessions.d.ts +3 -1
- package/dist/src/sessions.js +5 -3
- package/dist/src/side-panel.d.ts +6 -1
- package/dist/src/side-panel.js +12 -10
- package/dist/src/sign-in-detection.d.ts +82 -0
- package/dist/src/sign-in-detection.js +197 -0
- package/dist/src/sign-in-offer.d.ts +35 -0
- package/dist/src/sign-in-offer.js +116 -0
- package/dist/src/skills/bundled/create-skill/SKILL.md +1 -1
- package/dist/src/skills/bundled/diagram/SKILL.md +1 -1
- package/dist/src/skills/bundled/graph-manager/SKILL.md +59 -7
- package/dist/src/skills/bundled/graph-manager/patterns.md +27 -0
- package/dist/src/skills/bundled/provenance.json +4 -4
- package/dist/src/skills/runtime-skills.d.ts +6 -0
- package/dist/src/skills/runtime-skills.js +16 -3
- package/dist/src/stall-recovery.d.ts +6 -2
- package/dist/src/stall-recovery.js +7 -2
- package/dist/src/stray-files.d.ts +14 -0
- package/dist/src/stray-files.js +81 -0
- package/dist/src/subagent-run.js +6 -1
- package/dist/src/terminal-ui.d.ts +1 -1
- package/dist/src/terminal-ui.js +11 -5
- package/dist/src/time-limit.d.ts +53 -0
- package/dist/src/time-limit.js +79 -0
- package/dist/src/tool-activity.js +1 -1
- package/dist/src/tool-schema-compatibility.d.ts +7 -2
- package/dist/src/tool-schema-compatibility.js +8 -4
- package/dist/src/tools.js +92 -7
- package/dist/src/transcript.d.ts +5 -0
- package/dist/src/transcript.js +12 -4
- package/dist/src/types.d.ts +8 -0
- package/dist/src/untracked-file-removal.d.ts +3 -0
- package/dist/src/untracked-file-removal.js +125 -0
- package/dist/src/update-check.js +1 -1
- package/dist/src/update.d.ts +11 -1
- package/dist/src/update.js +27 -5
- package/dist/src/usage-analytics.d.ts +3 -1
- package/dist/src/usage-analytics.js +16 -2
- package/dist/src/workspace-git-metadata.d.ts +15 -0
- package/dist/src/workspace-git-metadata.js +50 -1
- package/dist/src/workspace-instructions.js +1 -1
- package/package.json +6 -26
- package/docs/README.md +0 -36
- package/docs/agents/README.md +0 -62
- package/docs/agents/install-for-agents.md +0 -56
- package/docs/agents/mcp-server.md +0 -212
- package/docs/agents/subagent-mode.md +0 -149
- package/docs/concepts/README.md +0 -47
- package/docs/concepts/jev-actionable-routing.md +0 -113
- package/docs/concepts/jev-decision-thresholds.md +0 -412
- package/docs/concepts/jev-efficiency.md +0 -217
- package/docs/concepts/jev-eval-2026-11-01.md +0 -78
- package/docs/concepts/limits.md +0 -52
- package/docs/concepts/memory.md +0 -10
- package/docs/concepts/security.md +0 -50
- package/docs/concepts/workspace-instructions.md +0 -29
- package/docs/getting-started/README.md +0 -82
- package/docs/getting-started/accounts.md +0 -78
- package/docs/getting-started/configure-providers.md +0 -132
- package/docs/guides/README.md +0 -13
- package/docs/guides/browser.md +0 -39
- package/docs/guides/desktop-app.md +0 -414
- package/docs/guides/extensions.md +0 -102
- package/docs/guides/graph-builder.md +0 -116
- package/docs/guides/headless.md +0 -46
- package/docs/guides/tui.md +0 -75
- package/docs/guides/update.md +0 -70
- package/docs/guides/web-search.md +0 -51
- package/docs/guides/windows-code-signing.md +0 -319
- package/docs/llms.txt +0 -45
- package/docs/reference/README.md +0 -7
- package/docs/reference/cli.md +0 -76
- package/docs/reference/config.md +0 -91
- package/docs/reference/slash-commands.md +0 -59
- package/docs/superpowers/plans/2026-11-01-claude-console-sign-in.md +0 -111
- package/docs/superpowers/plans/2026-11-01-jev-node-opt-in.md +0 -910
- package/docs/superpowers/plans/2026-11-02-workflow-pane.md +0 -398
- package/docs/superpowers/plans/2026-11-06-graph-soft-delete.md +0 -125
- package/docs/superpowers/plans/2026-11-09-orchestrator-delegation.md +0 -295
- package/docs/superpowers/plans/2026-11-13-graph-manager-chat.md +0 -203
- package/docs/superpowers/plans/2026-11-14-jev-fair-use-pricing.md +0 -79
- package/docs/superpowers/specs/2026-10-31-work-line-summary-design.md +0 -50
- package/docs/superpowers/specs/2026-11-01-claude-console-sign-in-design.md +0 -176
- package/docs/superpowers/specs/2026-11-01-jev-node-opt-in-design.md +0 -164
- package/docs/superpowers/specs/2026-11-01-pr-section-design.md +0 -111
- package/docs/superpowers/specs/2026-11-02-workflow-pane-design.md +0 -130
- package/docs/superpowers/specs/2026-11-06-bundled-skills-design.md +0 -206
- package/docs/superpowers/specs/2026-11-09-orchestrator-delegation-design.md +0 -291
- package/docs/superpowers/specs/2026-11-13-graph-manager-chat-design.md +0 -182
- package/docs/superpowers/specs/2026-11-14-jev-fair-use-pricing-design.md +0 -156
- package/scripts/jev-efficiency-eval.mjs +0 -187
- package/scripts/jev-efficiency-live.mjs +0 -193
- package/scripts/zcode-engine-replay.mjs +0 -223
- package/tests/agent-centric-mcp-test-plan.md +0 -208
- package/tests/analytics-settings-test-plan.md +0 -165
- package/tests/browser-cli-smoke.mjs +0 -276
- package/tests/browser-test-plan.md +0 -280
- package/tests/chat-side-panel-test-plan.md +0 -309
- package/tests/decision-engine-test-plan.md +0 -163
- package/tests/default-active-jev-test-plan.md +0 -85
- package/tests/harness-extensions-test-plan.md +0 -113
- package/tests/jev-all-decisions-test-plan.md +0 -156
- package/tests/jev-efficiency/criteria.json +0 -158
- package/tests/jev-efficiency/workloads.mjs +0 -242
- package/tests/jev-efficiency-test-plan.md +0 -198
- package/tests/permissions-sandbox-probe.mjs +0 -74
- package/tests/permissions-test-plan.md +0 -191
- package/tests/product-telemetry-test-plan.md +0 -536
- package/tests/thinking-stream-preview-test-plan.md +0 -136
- 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
|
+
}
|
package/dist/src/read-image.d.ts
CHANGED
|
@@ -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
|
|
20
|
-
*
|
|
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.
|
package/dist/src/read-image.js
CHANGED
|
@@ -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
|
|
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
|
|
26
|
-
*
|
|
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
|
|
33
|
+
const images = queue?.shift();
|
|
31
34
|
if (queue && !queue.length)
|
|
32
35
|
pending.delete(output);
|
|
33
|
-
return
|
|
36
|
+
return images?.length ? images : undefined;
|
|
34
37
|
}
|
|
35
|
-
|
|
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(
|
|
42
|
+
queue.push(images);
|
|
39
43
|
else
|
|
40
|
-
pending.set(output, [
|
|
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
|
|
46
|
-
*
|
|
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
|
|
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
|
-
|
|
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
|
+
}
|
|
@@ -7,7 +7,7 @@ export interface RemoteTlsIdentity {
|
|
|
7
7
|
/** base64url of the SHA-256 over the certificate's DER — the value the pairing code carries. */
|
|
8
8
|
export declare function certificateFingerprint(certPem: string): string;
|
|
9
9
|
/** PEM from a TLS socket's DER, for the viewer to persist as its pinned trust anchor. */
|
|
10
|
-
export
|
|
10
|
+
export { pemFromDer } from './pem.js';
|
|
11
11
|
/**
|
|
12
12
|
* Produce the installation's TLS material, reusing the stored pair unless told to rotate.
|
|
13
13
|
*
|
package/dist/src/remote/cert.js
CHANGED
|
@@ -4,6 +4,7 @@ import { join } from 'node:path';
|
|
|
4
4
|
import 'reflect-metadata';
|
|
5
5
|
import * as x509 from '@peculiar/x509';
|
|
6
6
|
import { acquireSaveLock, SaveLockBusyError } from '../save-lock.js';
|
|
7
|
+
import { toPem } from './pem.js';
|
|
7
8
|
/**
|
|
8
9
|
* The installation's TLS identity: a P-256 self-signed certificate generated once and reused.
|
|
9
10
|
*
|
|
@@ -20,19 +21,13 @@ import { acquireSaveLock, SaveLockBusyError } from '../save-lock.js';
|
|
|
20
21
|
x509.cryptoProvider.set(webcrypto);
|
|
21
22
|
/** Ten years: long past any honest pairing's lifetime, short enough that a rotation is not forever. */
|
|
22
23
|
const CERTIFICATE_LIFETIME_MS = 10 * 365 * 24 * 60 * 60 * 1000;
|
|
23
|
-
function toPem(label, der) {
|
|
24
|
-
const body = Buffer.from(der).toString('base64').replace(/(.{64})/g, '$1\n');
|
|
25
|
-
return `-----BEGIN ${label}-----\n${body}\n-----END ${label}-----\n`;
|
|
26
|
-
}
|
|
27
24
|
/** base64url of the SHA-256 over the certificate's DER — the value the pairing code carries. */
|
|
28
25
|
export function certificateFingerprint(certPem) {
|
|
29
26
|
const der = new NodeX509Certificate(certPem).raw;
|
|
30
27
|
return createHash('sha256').update(der).digest('base64url');
|
|
31
28
|
}
|
|
32
29
|
/** PEM from a TLS socket's DER, for the viewer to persist as its pinned trust anchor. */
|
|
33
|
-
export
|
|
34
|
-
return toPem('CERTIFICATE', der);
|
|
35
|
-
}
|
|
30
|
+
export { pemFromDer } from './pem.js';
|
|
36
31
|
function storedPairUsable(certPem, keyPem) {
|
|
37
32
|
try {
|
|
38
33
|
const cert = new NodeX509Certificate(certPem);
|
|
@@ -5,7 +5,7 @@ import { hostname as osHostname } from 'node:os';
|
|
|
5
5
|
import { request as httpRequest } from 'node:http';
|
|
6
6
|
import { request as httpsRequest } from 'node:https';
|
|
7
7
|
import { RemotePeerError, InviteRejectedError } from './errors.js';
|
|
8
|
-
import { pemFromDer } from './
|
|
8
|
+
import { pemFromDer } from './pem.js';
|
|
9
9
|
import { resolvePeerAddress, resolvePeerAddresses } from './network.js';
|
|
10
10
|
const REQUEST_TIMEOUT_MS = 15_000;
|
|
11
11
|
const MAX_RESPONSE_BYTES = 2 * 1024 * 1024;
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* PEM encoding, kept apart from `cert.ts` so the remote client can encode a peer's certificate
|
|
3
|
+
* without loading `@peculiar/x509` and its ASN.1 stack, which only issuing a certificate needs.
|
|
4
|
+
*/
|
|
5
|
+
export declare function toPem(label: string, der: Uint8Array): string;
|
|
6
|
+
export declare function pemFromDer(der: Uint8Array): string;
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* PEM encoding, kept apart from `cert.ts` so the remote client can encode a peer's certificate
|
|
3
|
+
* without loading `@peculiar/x509` and its ASN.1 stack, which only issuing a certificate needs.
|
|
4
|
+
*/
|
|
5
|
+
export function toPem(label, der) {
|
|
6
|
+
const body = Buffer.from(der).toString('base64').replace(/(.{64})/g, '$1\n');
|
|
7
|
+
return `-----BEGIN ${label}-----\n${body}\n-----END ${label}-----\n`;
|
|
8
|
+
}
|
|
9
|
+
export function pemFromDer(der) {
|
|
10
|
+
return toPem('CERTIFICATE', der);
|
|
11
|
+
}
|
package/dist/src/run-records.js
CHANGED
|
@@ -203,6 +203,36 @@ async function processStartedAtFor(pid) {
|
|
|
203
203
|
/** How far a recorded start time may differ from the probed one and still be the same process. */
|
|
204
204
|
const PROCESS_START_TOLERANCE_MS = 5_000;
|
|
205
205
|
const validSessionFile = (id) => /^[a-f0-9-]{36}$/i.test(id);
|
|
206
|
+
/**
|
|
207
|
+
* Read many files at once and map each one's text through `pick`, in order; a file that cannot be
|
|
208
|
+
* read, or that `pick` maps to undefined, yields undefined.
|
|
209
|
+
*
|
|
210
|
+
* The startup recovery pass looks at every run result and every saved session, which on a long-used
|
|
211
|
+
* installation is well over a thousand files. Read one after another they kept the terminal from
|
|
212
|
+
* drawing for seconds — far longer on a cold disk, where each open waits on the device and on file
|
|
213
|
+
* scanning. A bounded number in flight overlaps those waits without exhausting file handles, and
|
|
214
|
+
* `pick` runs inside each worker, so a file's text is dropped as soon as it is read unless `pick`
|
|
215
|
+
* keeps it: memory stays bounded by the files in flight and what is kept, not by the whole history.
|
|
216
|
+
*/
|
|
217
|
+
async function scanFiles(paths, pick, concurrency = 32) {
|
|
218
|
+
const contents = new Array(paths.length).fill(undefined);
|
|
219
|
+
let next = 0;
|
|
220
|
+
const worker = async () => {
|
|
221
|
+
while (next < paths.length) {
|
|
222
|
+
const index = next++;
|
|
223
|
+
let text;
|
|
224
|
+
try {
|
|
225
|
+
text = await readFile(paths[index], 'utf8');
|
|
226
|
+
}
|
|
227
|
+
catch {
|
|
228
|
+
continue;
|
|
229
|
+
}
|
|
230
|
+
contents[index] = pick(text);
|
|
231
|
+
}
|
|
232
|
+
};
|
|
233
|
+
await Promise.all(Array.from({ length: Math.min(concurrency, paths.length) }, worker));
|
|
234
|
+
return contents;
|
|
235
|
+
}
|
|
206
236
|
/**
|
|
207
237
|
* Classify the runs and session turns a previous process left unfinished.
|
|
208
238
|
*
|
|
@@ -291,15 +321,20 @@ async function markOpenRunsInterrupted(directory, onlyRunIds, skipOwnProcess = f
|
|
|
291
321
|
const ids = [];
|
|
292
322
|
const live = [];
|
|
293
323
|
const records = [];
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
324
|
+
// Only result records: `.json` is the result's extension, and `.checkpoint.json` names only
|
|
325
|
+
// ever existed as a checkpoint before the suffix was shortened to keep it out of the scans.
|
|
326
|
+
const results = names.filter(name => name.endsWith('.json') && !name.endsWith('.checkpoint.json'));
|
|
327
|
+
// A record this pass acts on is `running`, or `interrupted` with `telemetryPending`; a file
|
|
328
|
+
// naming neither cannot be one, and skipping its parse is most of the pass on a large history.
|
|
329
|
+
const texts = await scanFiles(results.map(name => join(runs, name)), text => text.includes('running') || text.includes('telemetryPending') ? text : undefined);
|
|
330
|
+
for (const [index, name] of results.entries()) {
|
|
299
331
|
const path = join(runs, name);
|
|
332
|
+
const text = texts[index];
|
|
333
|
+
if (text === undefined)
|
|
334
|
+
continue;
|
|
300
335
|
let value;
|
|
301
336
|
try {
|
|
302
|
-
value = JSON.parse(
|
|
337
|
+
value = JSON.parse(text);
|
|
303
338
|
}
|
|
304
339
|
catch {
|
|
305
340
|
continue;
|
|
@@ -890,10 +925,14 @@ async function upgradeSessionMarkers(directory, only) {
|
|
|
890
925
|
throw error;
|
|
891
926
|
}
|
|
892
927
|
let markers = 0;
|
|
893
|
-
|
|
894
|
-
|
|
895
|
-
|
|
896
|
-
|
|
928
|
+
const candidates = names.filter(name => name.endsWith('.json') && (only === undefined || name === `${only}.json`));
|
|
929
|
+
// A marker turn's completion has status `running` or the running summary, and both contain the
|
|
930
|
+
// word; a session without it has nothing to repair. The scan only narrows the set: a candidate is
|
|
931
|
+
// read again below, so the repair never writes back a copy older than the file, and the scan
|
|
932
|
+
// keeps only the answer, not the text.
|
|
933
|
+
const mayHaveMarker = await scanFiles(candidates.map(name => join(sessions, name)), text => text.includes('running') || undefined);
|
|
934
|
+
for (const [index, name] of candidates.entries()) {
|
|
935
|
+
if (!mayHaveMarker[index])
|
|
897
936
|
continue;
|
|
898
937
|
try {
|
|
899
938
|
const session = JSON.parse(await readFile(join(sessions, name), 'utf8'));
|