@mcoda/mswarm 0.1.135-codali.41 → 0.1.135-codali.47

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 (135) hide show
  1. package/dist/vendor/codali/cli/TerminalCommand.js +2 -2
  2. package/dist/vendor/codali/cli/tui/TerminalPresentation.js +1 -1
  3. package/dist/vendor/codali/config/OrchestrationConfig.d.ts +1 -0
  4. package/dist/vendor/codali/config/OrchestrationConfig.d.ts.map +1 -1
  5. package/dist/vendor/codali/config/OrchestrationConfig.js +3 -1
  6. package/dist/vendor/codali/docdex/DocdexClient.d.ts +11 -0
  7. package/dist/vendor/codali/docdex/DocdexClient.d.ts.map +1 -1
  8. package/dist/vendor/codali/docdex/DocdexClient.js +55 -1
  9. package/dist/vendor/codali/eval/fixtures/ContractReviewProvider.d.ts +5 -0
  10. package/dist/vendor/codali/eval/fixtures/ContractReviewProvider.d.ts.map +1 -1
  11. package/dist/vendor/codali/eval/fixtures/ContractReviewProvider.js +63 -0
  12. package/dist/vendor/codali/eval/fixtures/MixedMediaRecoveryJourney.js +2 -2
  13. package/dist/vendor/codali/eval/fixtures/TerminalRecoveryJourney.js +2 -2
  14. package/dist/vendor/codali/permissions/PermissionGate.d.ts +7 -0
  15. package/dist/vendor/codali/permissions/PermissionGate.d.ts.map +1 -1
  16. package/dist/vendor/codali/permissions/PermissionGate.js +27 -1
  17. package/dist/vendor/codali/providers/ClaudeCliProvider.d.ts.map +1 -1
  18. package/dist/vendor/codali/providers/ClaudeCliProvider.js +1 -0
  19. package/dist/vendor/codali/providers/CodexCliProvider.d.ts.map +1 -1
  20. package/dist/vendor/codali/providers/CodexCliProvider.js +1 -0
  21. package/dist/vendor/codali/providers/ConfiguredProvider.d.ts +2 -0
  22. package/dist/vendor/codali/providers/ConfiguredProvider.d.ts.map +1 -1
  23. package/dist/vendor/codali/providers/ConfiguredProvider.js +29 -0
  24. package/dist/vendor/codali/providers/ModelServiceError.d.ts +16 -2
  25. package/dist/vendor/codali/providers/ModelServiceError.d.ts.map +1 -1
  26. package/dist/vendor/codali/providers/ModelServiceError.js +18 -1
  27. package/dist/vendor/codali/providers/OllamaRemoteProvider.d.ts.map +1 -1
  28. package/dist/vendor/codali/providers/OllamaRemoteProvider.js +1 -0
  29. package/dist/vendor/codali/providers/OpenAiCompatibleProvider.d.ts.map +1 -1
  30. package/dist/vendor/codali/providers/OpenAiCompatibleProvider.js +4 -0
  31. package/dist/vendor/codali/providers/ProviderTypes.d.ts +4 -0
  32. package/dist/vendor/codali/providers/ProviderTypes.d.ts.map +1 -1
  33. package/dist/vendor/codali/runtime/AnswerEdits.d.ts +39 -0
  34. package/dist/vendor/codali/runtime/AnswerEdits.d.ts.map +1 -0
  35. package/dist/vendor/codali/runtime/AnswerEdits.js +134 -0
  36. package/dist/vendor/codali/runtime/AnswerVerification.d.ts.map +1 -1
  37. package/dist/vendor/codali/runtime/AnswerVerification.js +4 -2
  38. package/dist/vendor/codali/runtime/AuditGuards.d.ts +41 -0
  39. package/dist/vendor/codali/runtime/AuditGuards.d.ts.map +1 -0
  40. package/dist/vendor/codali/runtime/AuditGuards.js +81 -0
  41. package/dist/vendor/codali/runtime/CompletionReport.d.ts +4 -2
  42. package/dist/vendor/codali/runtime/CompletionReport.d.ts.map +1 -1
  43. package/dist/vendor/codali/runtime/CompletionReport.js +8 -3
  44. package/dist/vendor/codali/runtime/ContextCompression.d.ts +5 -0
  45. package/dist/vendor/codali/runtime/ContextCompression.d.ts.map +1 -1
  46. package/dist/vendor/codali/runtime/ContextCompression.js +16 -4
  47. package/dist/vendor/codali/runtime/DeliveryDocs.d.ts +21 -0
  48. package/dist/vendor/codali/runtime/DeliveryDocs.d.ts.map +1 -0
  49. package/dist/vendor/codali/runtime/DeliveryDocs.js +148 -0
  50. package/dist/vendor/codali/runtime/FigureCheck.d.ts +61 -2
  51. package/dist/vendor/codali/runtime/FigureCheck.d.ts.map +1 -1
  52. package/dist/vendor/codali/runtime/FigureCheck.js +210 -14
  53. package/dist/vendor/codali/runtime/GatewayRequest.d.ts +13 -0
  54. package/dist/vendor/codali/runtime/GatewayRequest.d.ts.map +1 -1
  55. package/dist/vendor/codali/runtime/GatewayRequest.js +54 -1
  56. package/dist/vendor/codali/runtime/InspectionConvergence.d.ts +4 -0
  57. package/dist/vendor/codali/runtime/InspectionConvergence.d.ts.map +1 -1
  58. package/dist/vendor/codali/runtime/InspectionConvergence.js +24 -1
  59. package/dist/vendor/codali/runtime/InteractionContract.d.ts +15 -0
  60. package/dist/vendor/codali/runtime/InteractionContract.d.ts.map +1 -1
  61. package/dist/vendor/codali/runtime/InteractionContract.js +33 -0
  62. package/dist/vendor/codali/runtime/InteractionRouter.d.ts +3 -3
  63. package/dist/vendor/codali/runtime/InteractionRouter.d.ts.map +1 -1
  64. package/dist/vendor/codali/runtime/InteractionRouter.js +1 -1
  65. package/dist/vendor/codali/runtime/NumericProvenance.d.ts +102 -0
  66. package/dist/vendor/codali/runtime/NumericProvenance.d.ts.map +1 -0
  67. package/dist/vendor/codali/runtime/NumericProvenance.js +411 -0
  68. package/dist/vendor/codali/runtime/OutageWait.d.ts +46 -5
  69. package/dist/vendor/codali/runtime/OutageWait.d.ts.map +1 -1
  70. package/dist/vendor/codali/runtime/OutageWait.js +81 -8
  71. package/dist/vendor/codali/runtime/ResearchEvidence.d.ts +14 -0
  72. package/dist/vendor/codali/runtime/ResearchEvidence.d.ts.map +1 -1
  73. package/dist/vendor/codali/runtime/ResearchEvidence.js +139 -3
  74. package/dist/vendor/codali/runtime/ReviewCoordinator.d.ts +22 -0
  75. package/dist/vendor/codali/runtime/ReviewCoordinator.d.ts.map +1 -1
  76. package/dist/vendor/codali/runtime/ReviewCoordinator.js +203 -25
  77. package/dist/vendor/codali/runtime/ReviewSource.d.ts +5 -0
  78. package/dist/vendor/codali/runtime/ReviewSource.d.ts.map +1 -1
  79. package/dist/vendor/codali/runtime/ReviewSource.js +6 -1
  80. package/dist/vendor/codali/runtime/SessionController.d.ts +85 -10
  81. package/dist/vendor/codali/runtime/SessionController.d.ts.map +1 -1
  82. package/dist/vendor/codali/runtime/SessionController.js +996 -176
  83. package/dist/vendor/codali/runtime/StructuralEvidence.d.ts +10 -0
  84. package/dist/vendor/codali/runtime/StructuralEvidence.d.ts.map +1 -1
  85. package/dist/vendor/codali/runtime/StructuralEvidence.js +10 -0
  86. package/dist/vendor/codali/runtime/TaskReview.d.ts +10 -0
  87. package/dist/vendor/codali/runtime/TaskReview.d.ts.map +1 -1
  88. package/dist/vendor/codali/runtime/TaskReview.js +31 -3
  89. package/dist/vendor/codali/runtime/VerificationCommand.d.ts +8 -0
  90. package/dist/vendor/codali/runtime/VerificationCommand.d.ts.map +1 -1
  91. package/dist/vendor/codali/runtime/VerificationCommand.js +114 -0
  92. package/dist/vendor/codali/runtime/WorkingStyle.d.ts +20 -0
  93. package/dist/vendor/codali/runtime/WorkingStyle.d.ts.map +1 -0
  94. package/dist/vendor/codali/runtime/WorkingStyle.js +71 -0
  95. package/dist/vendor/codali/tools/ToolRegistry.d.ts.map +1 -1
  96. package/dist/vendor/codali/tools/ToolRegistry.js +30 -4
  97. package/dist/vendor/codali/tools/ToolTypes.d.ts +3 -0
  98. package/dist/vendor/codali/tools/ToolTypes.d.ts.map +1 -1
  99. package/dist/vendor/codali/tools/browser/BrowserTool.d.ts +23 -1
  100. package/dist/vendor/codali/tools/browser/BrowserTool.d.ts.map +1 -1
  101. package/dist/vendor/codali/tools/browser/BrowserTool.js +83 -4
  102. package/dist/vendor/codali/tools/browser/BrowserWorker.js +142 -2
  103. package/dist/vendor/codali/tools/browser/HttpFallback.d.ts +39 -0
  104. package/dist/vendor/codali/tools/browser/HttpFallback.d.ts.map +1 -0
  105. package/dist/vendor/codali/tools/browser/HttpFallback.js +240 -0
  106. package/dist/vendor/codali/tools/calculation/CalculatorTool.d.ts +16 -1
  107. package/dist/vendor/codali/tools/calculation/CalculatorTool.d.ts.map +1 -1
  108. package/dist/vendor/codali/tools/calculation/CalculatorTool.js +321 -26
  109. package/dist/vendor/codali/tools/deterministic/DeterministicTools.js +1 -1
  110. package/dist/vendor/codali/tools/deterministic/node-worker.cjs +10 -10
  111. package/dist/vendor/codali/tools/shell/AsyncProcess.d.ts +2 -0
  112. package/dist/vendor/codali/tools/shell/AsyncProcess.d.ts.map +1 -1
  113. package/dist/vendor/codali/tools/shell/AsyncProcess.js +38 -5
  114. package/dist/vendor/codali/tools/shell/IsolatedExecutor.d.ts +29 -1
  115. package/dist/vendor/codali/tools/shell/IsolatedExecutor.d.ts.map +1 -1
  116. package/dist/vendor/codali/tools/shell/IsolatedExecutor.js +179 -9
  117. package/dist/vendor/codali/tools/shell/ShellTool.d.ts +2 -0
  118. package/dist/vendor/codali/tools/shell/ShellTool.d.ts.map +1 -1
  119. package/dist/vendor/codali/tools/shell/ShellTool.js +33 -3
  120. package/dist/vendor/codali/tools/verification/CodeRunTool.d.ts +19 -0
  121. package/dist/vendor/codali/tools/verification/CodeRunTool.d.ts.map +1 -0
  122. package/dist/vendor/codali/tools/verification/CodeRunTool.js +104 -0
  123. package/dist/vendor/codali/tools/verification/JavaScriptVerificationTool.d.ts.map +1 -1
  124. package/dist/vendor/codali/tools/verification/JavaScriptVerificationTool.js +21 -10
  125. package/dist/vendor/codali/tools/verification/VitestTool.d.ts +27 -0
  126. package/dist/vendor/codali/tools/verification/VitestTool.d.ts.map +1 -1
  127. package/dist/vendor/codali/tools/verification/VitestTool.js +232 -18
  128. package/dist/vendor/config/deterministic/node-worker.mjs +15 -2
  129. package/dist/vendor/config/skills/code-implementation/SKILL.md +1 -1
  130. package/dist/vendor/config/skills/planning/SKILL.md +1 -1
  131. package/dist/vendor/config/skills/testing-and-verification/SKILL.md +5 -5
  132. package/dist/vendor/config/skills/ui-ux-design/SKILL.md +1 -1
  133. package/dist/vendor/config/skills/webapp-testing/SKILL.md +4 -0
  134. package/dist/vendor/config/skills/webapp-testing/journey-driver.mjs +186 -0
  135. package/package.json +3 -3
@@ -4,6 +4,7 @@ import path from "node:path";
4
4
  import { fork } from "node:child_process";
5
5
  import { chromium } from "playwright-core";
6
6
  import { ToolExecutionError } from "../ToolTypes.js";
7
+ import { browserRefused, decodeBody, fetchDirect, htmlToText, isPdf, pdfToText } from "./HttpFallback.js";
7
8
  export const browserUrl = (value) => {
8
9
  let url;
9
10
  try {
@@ -142,6 +143,48 @@ const MAX_SNAPSHOT_CHARS = 24000000;
142
143
  const SNAPSHOT_REUSE_MS = 30 * 60000;
143
144
  const isErrorSnapshot = (value) => value.httpStatus === null || value.httpStatus >= 400 || !value.content.trim();
144
145
  /** Short-lived, unauthenticated browser navigation; the model never supplies JS. */
146
+ const SOURCES = {
147
+ rendered_text: "isolated browser rendered-text snapshot (visual text; use page scope for accessibility-only labels)",
148
+ accessibility: "isolated browser accessibility snapshot",
149
+ http_text: "direct HTTP fetch without a browser: static HTML converted to text; anything the page adds with scripts is absent",
150
+ pdf_text: "PDF text extracted offline from a direct download; page headings mark page breaks, layout and tables are flattened",
151
+ };
152
+ /** The browser could not start or died, which says nothing about the page. */
153
+ const browserBroken = (message) => /Failed to launch|launchServer|Browser worker exited|Target page, context or browser has been closed|Browser closed|browser has disconnected|spawn .* (?:ENOENT|EACCES)|Chrome\/Chromium was not found/i.test(message);
154
+ /** When the machine has no network at all, say so plainly: the page may well
155
+ * exist, and the right move is to wait or work from evidence already held. */
156
+ const networkDown = (error, message) => {
157
+ const code = error?.cause?.code ?? error?.code;
158
+ if (!/ERR_INTERNET_DISCONNECTED|ERR_NETWORK_ACCESS_DENIED|ERR_ADDRESS_UNREACHABLE/.test(message) && !["ENETUNREACH", "ENETDOWN", "EAI_AGAIN"].includes(String(code)))
159
+ return error;
160
+ return new ToolExecutionError("tool_execution_failed", `The network is unreachable from this machine right now (${message.match(/ERR_[A-Z_]+/)?.[0] ?? code}). This says nothing about whether the page exists; try again shortly, or continue from evidence already gathered.`, { retryable: true });
161
+ };
162
+ /** Read a URL without the browser: a PDF as extracted text, HTML as static text. */
163
+ export async function captureDirect(url, scope, signal, deps = {}) {
164
+ const response = await fetchDirect(url, signal, deps.fetcher);
165
+ const base = { url: response.url, httpStatus: response.httpStatus, contentType: response.contentType };
166
+ // A PDF is recognised by its content, or by its declared type: a ".pdf"
167
+ // address that serves a web page (a viewer, a sign-in or an error) is read as that page.
168
+ const pdfBytes = response.body.subarray(0, 1024).indexOf("%PDF-") >= 0;
169
+ if (pdfBytes || /application\/(?:x-)?pdf/i.test(response.contentType ?? "") && !/^\s*<(?:!doctype|html)/i.test(response.body.subarray(0, 200).toString("latin1"))) {
170
+ const pdf = response.httpStatus < 400 ? await pdfToText(response.body, signal, { pythonRoot: deps.pythonRoot }) : undefined;
171
+ let name = new URL(response.url).pathname.split("/").pop() ?? "";
172
+ try {
173
+ name = decodeURIComponent(name);
174
+ }
175
+ catch { /* Keep the encoded name. */ }
176
+ return { ...base, title: name.slice(0, 200), scope: "page", format: "pdf_text",
177
+ content: pdf?.content ?? "", truncated: response.truncated || !!pdf?.truncated,
178
+ notice: pdf ? `${pdf.pages ?? "Unknown number of"} pages; text extracted with ${pdf.extractor}.${response.truncated ? " The download was cut at its size limit." : ""}`
179
+ : "No text could be extracted from this PDF: it may be scanned images, or no PDF text extractor is installed (codali tools install --documents). Look for an HTML version of the document." };
180
+ }
181
+ if (response.contentType && !/html|xml|^text\/|json/i.test(response.contentType)) {
182
+ return { ...base, title: "", scope: "page", format: "http_text", content: "", truncated: false, notice: `This URL returns ${response.contentType.slice(0, 80)}, which is not readable as text.` };
183
+ }
184
+ const text = decodeBody(response.body, response.contentType);
185
+ const converted = /html|xml/i.test(response.contentType ?? "") || /<html[\s>]/i.test(text.slice(0, 2000)) ? htmlToText(text, response.url, scope) : { title: "", content: text.trim(), scope: "page" };
186
+ return { ...base, title: converted.title.slice(0, 1000), scope: converted.scope, format: "http_text", content: converted.content.slice(0, 1000000), truncated: response.truncated || converted.content.length > 1000000 };
187
+ }
145
188
  export function createBrowserTools(options = {}) {
146
189
  let snapshot;
147
190
  const snapshots = new Map();
@@ -170,7 +213,7 @@ export function createBrowserTools(options = {}) {
170
213
  evidenceStatus: snapshot.httpStatus === null ? "unknown_http_status" : snapshot.httpStatus >= 400 ? "http_error" : !snapshot.content.trim() ? "empty" : "retrieved",
171
214
  evidenceNotice: "Retrieval is not claim verification. Error, login/challenge, navigation-only and search/abstract pages do not establish the requested primary-source claims. Cite only claims supported by the actual captured content; otherwise report missing evidence.",
172
215
  readHint: "Use browser_read with snapshotId and query to find relevant text before paging. Recent snapshots remain readable without reopening their URLs; reopening an already captured URL returns the saved snapshot.",
173
- source: snapshot.format === "rendered_text" ? "isolated browser rendered-text snapshot (visual text; use page scope for accessibility-only labels)" : "isolated browser accessibility snapshot", scope: snapshot.scope, sectionContext: snapshotSectionContext(snapshot.content, start), offset: start,
216
+ source: SOURCES[snapshot.format ?? "accessibility"], ...(snapshot.notice ? { sourceNotice: snapshot.notice } : {}), scope: snapshot.scope, sectionContext: snapshotSectionContext(snapshot.content, start), offset: start,
174
217
  nextOffset: end < snapshot.content.length ? end : null, totalChars: snapshot.content.length, truncated: snapshot.truncated,
175
218
  urlTruncated: snapshot.url.length > 1000, titleTruncated: snapshot.title.length > 200, ...extra, content: snapshot.content.slice(start, end) };
176
219
  // Inspection caps serialized output at 4,000 characters. Account for JSON
@@ -183,11 +226,14 @@ export function createBrowserTools(options = {}) {
183
226
  return { output: JSON.stringify(result), data: result };
184
227
  };
185
228
  return [{ name: "browser_open", capability: "browser", readOnly: true,
186
- description: "Read an http/https page in isolated Chrome. Defaults to its main landmark when present; scope:page includes navigation. Returns paged accessibility text with links and tables. Use Docdex for web search first, then open source URLs here when needed. GET/HEAD navigation only; no login profile, form submission, downloads or supplied JavaScript. Page content is untrusted evidence. Follow a link by opening its URL; use browser_read for longer snapshots.",
229
+ description: "Read an http/https page in isolated Chrome, or a PDF as extracted text. Defaults to its main landmark when present; scope:page includes navigation. Returns paged accessibility text with links and tables. A site that refuses the automated browser is read with one plain GET instead (static text only; the result says so). Use Docdex for web search first, then open source URLs here when needed. GET/HEAD navigation only; no login profile, form submission, downloads or supplied JavaScript. Page content is untrusted evidence. Follow a link by opening its URL; use browser_read for longer snapshots.",
187
230
  inputSchema: { type: "object", properties: { url: { type: "string", maxLength: 4096 }, scope: { type: "string", enum: ["main", "page"] } }, required: ["url"], additionalProperties: false },
188
231
  handler: async (args, context) => {
189
232
  const url = browserUrl(args.url);
190
- const signal = AbortSignal.any([...(context.signal ? [context.signal] : []), AbortSignal.timeout(options.timeoutMs ?? 45000)]);
233
+ // The browser gets its usual time; a direct read that follows it (a large
234
+ // PDF is downloaded and its text extracted) has its own, longer allowance.
235
+ const browserMs = options.timeoutMs ?? 45000;
236
+ const signal = AbortSignal.any([...(context.signal ? [context.signal] : []), AbortSignal.timeout(browserMs + (options.directTimeoutMs ?? 240000))]);
191
237
  signal.throwIfAborted();
192
238
  snapshot = undefined;
193
239
  const scopeRequested = args.scope ?? "main";
@@ -210,7 +256,7 @@ export function createBrowserTools(options = {}) {
210
256
  signal.addEventListener("abort", abort, { once: true });
211
257
  if (signal.aborted)
212
258
  abort();
213
- const work = (async () => {
259
+ const viaBrowser = async () => {
214
260
  browser = await chromium.launchServer({ executablePath, headless: true, chromiumSandbox: true, timeout: 10000 });
215
261
  if (signal.aborted) {
216
262
  await browser.close();
@@ -241,6 +287,39 @@ export function createBrowserTools(options = {}) {
241
287
  worker.send({ endpoint: browser.wsEndpoint(), url, scope: args.scope ?? "main" }, error => { if (error)
242
288
  reject(error); });
243
289
  });
290
+ return result;
291
+ };
292
+ let lastDirectError;
293
+ const work = (async () => {
294
+ const direct = () => captureDirect(url, scopeRequested === "page" ? "page" : "main", signal, options);
295
+ let result;
296
+ try {
297
+ let timer;
298
+ try {
299
+ result = await Promise.race([viaBrowser(), new Promise((_, reject) => { timer = setTimeout(() => reject(new Error(`Timeout ${browserMs}ms exceeded`)), browserMs); })]);
300
+ }
301
+ finally {
302
+ clearTimeout(timer);
303
+ }
304
+ // Chrome shows a PDF in a viewer with no readable text: twelve of
305
+ // twenty PDF sources came back empty in cycles 5 and 6.
306
+ if (!result.content.trim() && isPdf(result.contentType, result.url))
307
+ result = await direct().catch(() => result);
308
+ }
309
+ catch (error) {
310
+ const message = error instanceof Error ? error.message : String(error);
311
+ // The site refused the automated browser, the URL is a download, or the
312
+ // browser itself could not start or crashed (a broken install, a host
313
+ // out of memory): the page can still be read with one plain request.
314
+ if (signal.aborted || !browserRefused(message) && !browserBroken(message))
315
+ throw networkDown(error, message);
316
+ worker?.kill("SIGKILL");
317
+ await browser?.close().catch(() => undefined);
318
+ const fallback = await direct().catch(fetchError => { lastDirectError = fetchError; return undefined; });
319
+ if (!fallback || signal.aborted)
320
+ throw networkDown(lastDirectError ?? error, message);
321
+ result = { ...fallback, notice: [`The browser could not load this page (${message.match(/ERR_[A-Z0-9_]+|Timeout \d+ms exceeded|Download is starting/)?.[0] ?? "navigation failed"}); this is a plain HTTP read.`, fallback.notice].filter(Boolean).join(" ") };
322
+ }
244
323
  signal.throwIfAborted();
245
324
  snapshot = { ...result, id: `snap-${++snapshotCount}`, url: browserUrl(result.url), capturedAt: new Date().toISOString() };
246
325
  store(snapshot, captureKey);
@@ -1,6 +1,18 @@
1
1
  import { chromium } from "playwright-core";
2
2
  // This process runs in a private empty directory with an explicit environment.
3
3
  // browser-use reads .env at import time, so never import it in the CLI process.
4
+ /** Below this many characters of readable text the page may still be rendering. */
5
+ const RENDER_MIN_CHARS = 200;
6
+ /** Upper bound on waiting for a script-built page, from the end of navigation. */
7
+ const RENDER_WAIT_MS = 10000;
8
+ const RENDER_NETWORK_IDLE_MS = 6000;
9
+ /** Text unchanged this long counts as rendered. */
10
+ const RENDER_STABLE_MS = 1200;
11
+ const RENDER_POLL_MS = 250;
12
+ const COLLAPSED_MARKER = "[Collapsed section, expanded for reading]";
13
+ /** Bounds on text revealed from collapsed sections, per section and per page. */
14
+ const COLLAPSED_PANEL_MAX_CHARS = 20000;
15
+ const COLLAPSED_PAGE_MAX_CHARS = 100000;
4
16
  process.once("message", async (input) => {
5
17
  let browser;
6
18
  let session;
@@ -53,6 +65,131 @@ process.once("message", async (input) => {
53
65
  await new Promise(resolve => setTimeout(resolve, 1000));
54
66
  }
55
67
  }
68
+ // Single-page applications (legislation portals, gazettes) are an empty
69
+ // shell at DOMContentLoaded and fill in after fetching their data, so an
70
+ // immediate read returned "empty" for pages that do have text. When the
71
+ // readable region is still short, wait for the network to settle and the
72
+ // text to stop growing, within a fixed bound. Pages with text proceed at once.
73
+ const readableChars = () => tab.evaluate(() => {
74
+ const main = document.querySelector('main,[role="main"]');
75
+ return ((main?.innerText.trim() ? main : document.body)?.innerText ?? "").trim().length;
76
+ }).catch(() => 0);
77
+ const notices = [];
78
+ const renderStarted = Date.now();
79
+ const initialChars = await readableChars();
80
+ if (initialChars < RENDER_MIN_CHARS) {
81
+ const deadline = renderStarted + RENDER_WAIT_MS;
82
+ await tab.waitForLoadState("networkidle", { timeout: Math.min(RENDER_NETWORK_IDLE_MS, RENDER_WAIT_MS) }).catch(() => undefined);
83
+ let last = await readableChars(), stableSince = Date.now();
84
+ while (Date.now() < deadline && Date.now() - stableSince < RENDER_STABLE_MS) {
85
+ await tab.waitForTimeout(RENDER_POLL_MS);
86
+ const current = await readableChars();
87
+ if (current !== last) {
88
+ last = current;
89
+ stableSince = Date.now();
90
+ }
91
+ }
92
+ if (last > initialChars)
93
+ notices.push(`The page builds its content with scripts; it was read after waiting ${Math.round((Date.now() - renderStarted) / 100) / 10} s for it to render.`);
94
+ }
95
+ // Collapsed sections (closed <details>, accordion panels and inactive tabs
96
+ // tied to their toggle by aria-controls) are part of the page a reader can
97
+ // open, but rendered text omits them: a country update read as its heading
98
+ // only. Reveal them in this disposable DOM without clicking anything, and
99
+ // mark the text so it is not mistaken for what the page shows by default.
100
+ // Content hidden for other reasons stays hidden.
101
+ // Only a section the reader could open is revealed: its toggle (summary or
102
+ // aria-controls button) must itself be visible, sized and on the page, and
103
+ // the panel must render once opened. A hidden toggle wired to a hidden panel
104
+ // is hidden text like any other and stays hidden. Revealed text is capped per
105
+ // section and per page so a page cannot flood the snapshot this way.
106
+ const expansion = await tab.evaluate(({ marker, panelMaxChars, pageMaxChars }) => {
107
+ let count = 0, skipped = 0, budget = pageMaxChars;
108
+ const visible = (element) => {
109
+ const box = element;
110
+ if (typeof box.checkVisibility === "function" && !box.checkVisibility({ checkOpacity: true, checkVisibilityCSS: true, contentVisibilityAuto: true }))
111
+ return false;
112
+ // checkVisibility covers display/visibility/opacity on the element and its ancestors;
113
+ // also refuse zero-size and off-page placement and near-transparent ancestors.
114
+ const rect = box.getBoundingClientRect();
115
+ if (rect.width < 4 || rect.height < 4)
116
+ return false;
117
+ const left = rect.left + window.scrollX, top = rect.top + window.scrollY;
118
+ const doc = document.documentElement;
119
+ if (left + rect.width <= 0 || top + rect.height <= 0 || left >= Math.max(doc.scrollWidth, window.innerWidth) || top >= Math.max(doc.scrollHeight, window.innerHeight))
120
+ return false;
121
+ const own = getComputedStyle(box);
122
+ if (own.visibility !== "visible" || parseFloat(own.fontSize) < 4 && !box.getAttribute("aria-label"))
123
+ return false;
124
+ for (let node = box; node; node = node.parentElement)
125
+ if (Number(getComputedStyle(node).opacity) < 0.1)
126
+ return false;
127
+ return true;
128
+ };
129
+ const admit = (element) => {
130
+ const size = (element.textContent ?? "").length;
131
+ if (size > panelMaxChars || size > budget) {
132
+ skipped++;
133
+ return false;
134
+ }
135
+ budget -= size;
136
+ return true;
137
+ };
138
+ const mark = (element, after) => {
139
+ const note = document.createTextNode(`${marker} `);
140
+ if (after)
141
+ after.after(note);
142
+ else
143
+ element.prepend(note);
144
+ count++;
145
+ };
146
+ for (const details of Array.from(document.querySelectorAll("details:not([open])")).slice(0, 200)) {
147
+ const summary = details.querySelector(":scope > summary");
148
+ if (!visible(summary ?? details))
149
+ continue;
150
+ if (!admit(details))
151
+ continue;
152
+ details.setAttribute("open", "");
153
+ mark(details, summary);
154
+ }
155
+ const toggles = document.querySelectorAll('[aria-controls][aria-expanded="false"], [role="tab"][aria-controls][aria-selected="false"]');
156
+ for (const toggle of Array.from(toggles).slice(0, 200)) {
157
+ if (!visible(toggle))
158
+ continue;
159
+ for (const id of (toggle.getAttribute("aria-controls") ?? "").split(/\s+/).filter(Boolean).slice(0, 8)) {
160
+ const panel = document.getElementById(id);
161
+ if (!panel || panel.dataset.codaliExpanded)
162
+ continue;
163
+ if (!panel.hidden && getComputedStyle(panel).display !== "none")
164
+ continue;
165
+ if (!admit(panel))
166
+ continue;
167
+ const hiddenAttribute = panel.hasAttribute("hidden"), inlineDisplay = panel.style.getPropertyValue("display"), inlinePriority = panel.style.getPropertyPriority("display");
168
+ panel.removeAttribute("hidden");
169
+ if (getComputedStyle(panel).display === "none")
170
+ panel.style.setProperty("display", "block", "important");
171
+ panel.dataset.codaliExpanded = "1";
172
+ if (!visible(panel)) {
173
+ // Opened, it still would not render to a reader: put it back.
174
+ if (hiddenAttribute)
175
+ panel.setAttribute("hidden", "");
176
+ if (inlineDisplay)
177
+ panel.style.setProperty("display", inlineDisplay, inlinePriority);
178
+ else
179
+ panel.style.removeProperty("display");
180
+ budget += (panel.textContent ?? "").length;
181
+ continue;
182
+ }
183
+ mark(panel);
184
+ }
185
+ }
186
+ return { count, skipped };
187
+ }, { marker: COLLAPSED_MARKER, panelMaxChars: COLLAPSED_PANEL_MAX_CHARS, pageMaxChars: COLLAPSED_PAGE_MAX_CHARS }).catch(() => ({ count: 0, skipped: 0 }));
188
+ const expanded = expansion.count;
189
+ if (expanded)
190
+ notices.push(`${expanded} collapsed section${expanded === 1 ? " was" : "s were"} expanded for reading; ${expanded === 1 ? "its" : "their"} text starts with "${COLLAPSED_MARKER}".`);
191
+ if (expansion.skipped)
192
+ notices.push(`${expansion.skipped} collapsed section${expansion.skipped === 1 ? " was" : "s were"} left closed: over the size allowed for expanded text.`);
56
193
  // Accessibility snapshots otherwise flatten deleted/struck-through text
57
194
  // into apparently current prose. Mark revisions in this disposable DOM;
58
195
  // no page action, form submission or remote mutation is performed.
@@ -65,7 +202,10 @@ process.once("message", async (input) => {
65
202
  }
66
203
  });
67
204
  const main = tab.getByRole("main");
68
- const useMain = input.scope !== "page" && await main.count() > 0;
205
+ // A main landmark that stayed empty (the application renders elsewhere)
206
+ // would read as an empty page; read the body's rendered text instead.
207
+ const useMain = input.scope !== "page" && await main.count() > 0
208
+ && !!(await main.first().innerText({ timeout: 5000 }).catch(() => "")).trim();
69
209
  const root = useMain ? main.first() : tab.locator("body");
70
210
  let content;
71
211
  let format = "accessibility";
@@ -107,7 +247,7 @@ process.once("message", async (input) => {
107
247
  else
108
248
  content = await tab.ariaSnapshot({ mode: "default", depth: 20, timeout: 5000 });
109
249
  reply = { ok: true, value: { url: tab.url(), httpStatus, contentType, title: (await tab.title()).slice(0, 1000), scope: useMain ? "main" : "page",
110
- format, content: content.slice(0, 1000000), truncated: content.length > 1000000 } };
250
+ format, content: content.slice(0, 1000000), truncated: content.length > 1000000, ...(notices.length ? { notice: notices.join(" ") } : {}) } };
111
251
  }
112
252
  catch (error) {
113
253
  reply = { ok: false, message: error instanceof Error ? error.message : String(error) };
@@ -0,0 +1,39 @@
1
+ /** Navigation failures that say nothing about the page itself: the site
2
+ * refused or dropped the automated browser, or the URL started a download.
3
+ * In cycles 4-6 these hid official pages (court, regulator and archive sites)
4
+ * that a plain request reads without trouble. */
5
+ export declare const browserRefused: (message: string) => boolean;
6
+ export declare const isPdf: (contentType: string | null, url: string) => boolean;
7
+ export interface DirectResponse {
8
+ url: string;
9
+ httpStatus: number;
10
+ contentType: string | null;
11
+ body: Buffer;
12
+ truncated: boolean;
13
+ }
14
+ /** One unauthenticated GET from this process: no cookies, no credentials, no
15
+ * scripts. The body is read up to a fixed size and treated as untrusted text. */
16
+ export declare function fetchDirect(url: string, signal?: AbortSignal, fetcher?: typeof fetch): Promise<DirectResponse>;
17
+ export declare const decodeBody: (body: Buffer, contentType: string | null) => string;
18
+ /** Readable text of an HTML document without running it: headings keep the
19
+ * marker the snapshot reader navigates by, links are listed once at the end.
20
+ * Every pattern here is bounded or anchored on a single character class, so
21
+ * hostile markup costs time in proportion to its length, not its square. */
22
+ export declare function htmlToText(html: string, baseUrl: string, scope?: "main" | "page"): {
23
+ title: string;
24
+ content: string;
25
+ scope: "main" | "page";
26
+ };
27
+ export interface PdfText {
28
+ content: string;
29
+ pages: number | null;
30
+ extractor: string;
31
+ truncated: boolean;
32
+ }
33
+ /** Text of a PDF, extracted offline in the sandbox: the document runtime's
34
+ * pypdf when installed, otherwise pdftotext when the host has it. Undefined
35
+ * when neither is available or the file holds no text layer. */
36
+ export declare function pdfToText(bytes: Buffer, signal?: AbortSignal, options?: {
37
+ pythonRoot?: string;
38
+ }): Promise<PdfText | undefined>;
39
+ //# sourceMappingURL=HttpFallback.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"HttpFallback.d.ts","sourceRoot":"","sources":["../../../src/tools/browser/HttpFallback.ts"],"names":[],"mappings":"AAMA;;;iDAGiD;AACjD,eAAO,MAAM,cAAc,GAAI,SAAS,MAAM,KAAG,OACyK,CAAC;AAE3N,eAAO,MAAM,KAAK,GAAI,aAAa,MAAM,GAAG,IAAI,EAAE,KAAK,MAAM,KAAG,OACoB,CAAC;AAErF,MAAM,WAAW,cAAc;IAAG,GAAG,EAAE,MAAM,CAAC;IAAC,UAAU,EAAE,MAAM,CAAC;IAAC,WAAW,EAAE,MAAM,GAAG,IAAI,CAAC;IAAC,IAAI,EAAE,MAAM,CAAC;IAAC,SAAS,EAAE,OAAO,CAAA;CAAE;AAMjI;iFACiF;AACjF,wBAAsB,WAAW,CAAC,GAAG,EAAE,MAAM,EAAE,MAAM,CAAC,EAAE,WAAW,EAAE,OAAO,GAAE,OAAO,KAAa,GAAG,OAAO,CAAC,cAAc,CAAC,CA2B3H;AASD,eAAO,MAAM,UAAU,GAAI,MAAM,MAAM,EAAE,aAAa,MAAM,GAAG,IAAI,KAAG,MAGrE,CAAC;AAwCF;;;4EAG4E;AAC5E,wBAAgB,UAAU,CAAC,IAAI,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,EAAE,KAAK,GAAE,MAAM,GAAG,MAAe,GAAG;IAAE,KAAK,EAAE,MAAM,CAAC;IAAC,OAAO,EAAE,MAAM,CAAC;IAAC,KAAK,EAAE,MAAM,GAAG,MAAM,CAAA;CAAE,CAwCrJ;AAcD,MAAM,WAAW,OAAO;IAAG,OAAO,EAAE,MAAM,CAAC;IAAC,KAAK,EAAE,MAAM,GAAG,IAAI,CAAC;IAAC,SAAS,EAAE,MAAM,CAAC;IAAC,SAAS,EAAE,OAAO,CAAA;CAAE;AAEzG;;gEAEgE;AAChE,wBAAsB,SAAS,CAAC,KAAK,EAAE,MAAM,EAAE,MAAM,CAAC,EAAE,WAAW,EAAE,OAAO,GAAE;IAAE,UAAU,CAAC,EAAE,MAAM,CAAA;CAAO,GAAG,OAAO,CAAC,OAAO,GAAG,SAAS,CAAC,CA6BxI"}
@@ -0,0 +1,240 @@
1
+ import { promises as fs } from "node:fs";
2
+ import os from "node:os";
3
+ import path from "node:path";
4
+ import { createIsolatedExecutor } from "../shell/IsolatedExecutor.js";
5
+ import { defaultDocumentPythonRoot } from "../documents/DocumentTools.js";
6
+ /** Navigation failures that say nothing about the page itself: the site
7
+ * refused or dropped the automated browser, or the URL started a download.
8
+ * In cycles 4-6 these hid official pages (court, regulator and archive sites)
9
+ * that a plain request reads without trouble. */
10
+ export const browserRefused = (message) => /ERR_HTTP2_PROTOCOL_ERROR|ERR_CONNECTION_(?:REFUSED|RESET|CLOSED)|ERR_EMPTY_RESPONSE|ERR_ABORTED|ERR_TIMED_OUT|ERR_SSL_PROTOCOL_ERROR|ERR_QUIC_PROTOCOL_ERROR|Timeout \d+ms exceeded|Download is starting/.test(message);
11
+ export const isPdf = (contentType, url) => /application\/(?:x-)?pdf/i.test(contentType ?? "") || /\.pdf(?:$|[?#])/i.test(url);
12
+ // Official reports run large: a grid operator's final incident report was 50.8 MB.
13
+ const MAX_PDF_BYTES = 96 * 1024 * 1024;
14
+ const MAX_TEXT_BYTES = 6 * 1024 * 1024;
15
+ /** One unauthenticated GET from this process: no cookies, no credentials, no
16
+ * scripts. The body is read up to a fixed size and treated as untrusted text. */
17
+ export async function fetchDirect(url, signal, fetcher = fetch) {
18
+ // Twenty seconds for the server to answer, then up to three minutes for a large body.
19
+ const limiter = new AbortController();
20
+ let timer = setTimeout(() => limiter.abort(new Error("The server did not answer within 20 seconds")), 20000);
21
+ try {
22
+ const response = await fetcher(url, { method: "GET", redirect: "follow", credentials: "omit", signal: signal ? AbortSignal.any([signal, limiter.signal]) : limiter.signal,
23
+ headers: { "user-agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36",
24
+ accept: "text/html,application/xhtml+xml,application/pdf;q=0.9,text/plain;q=0.8,*/*;q=0.5", "accept-language": "en-US,en;q=0.9" } });
25
+ clearTimeout(timer);
26
+ timer = setTimeout(() => limiter.abort(new Error("The download did not finish within three minutes")), 180000);
27
+ const finalUrl = new URL(response.url || url);
28
+ if (!["http:", "https:"].includes(finalUrl.protocol) || finalUrl.username || finalUrl.password)
29
+ throw new Error("Redirected outside http/https");
30
+ const contentType = response.headers.get("content-type");
31
+ const max = isPdf(contentType, finalUrl.href) ? MAX_PDF_BYTES : MAX_TEXT_BYTES;
32
+ const chunks = [];
33
+ let bytes = 0, truncated = false;
34
+ if (response.body) {
35
+ const reader = response.body.getReader();
36
+ try {
37
+ for (;;) {
38
+ const part = await reader.read();
39
+ if (part.done)
40
+ break;
41
+ if (bytes + part.value.byteLength > max) {
42
+ chunks.push(Buffer.from(part.value.subarray(0, max - bytes)));
43
+ bytes = max;
44
+ truncated = true;
45
+ break;
46
+ }
47
+ chunks.push(Buffer.from(part.value));
48
+ bytes += part.value.byteLength;
49
+ }
50
+ }
51
+ finally {
52
+ await reader.cancel().catch(() => undefined);
53
+ }
54
+ }
55
+ return { url: finalUrl.href, httpStatus: response.status, contentType, body: Buffer.concat(chunks), truncated };
56
+ }
57
+ finally {
58
+ clearTimeout(timer);
59
+ }
60
+ }
61
+ const ENTITIES = { amp: "&", lt: "<", gt: ">", quot: '"', apos: "'", nbsp: " ", ndash: "–", mdash: "—", hellip: "…", rsquo: "’", lsquo: "‘", rdquo: "”", ldquo: "“", euro: "€", pound: "£", copy: "©", reg: "®", deg: "°", middot: "·", bull: "•", times: "×" };
62
+ const decodeEntities = (text) => text.replace(/&(#x[0-9a-f]{1,6}|#\d{1,7}|[a-z]{2,8});/gi, (whole, body) => {
63
+ if (body[0] !== "#")
64
+ return ENTITIES[body.toLowerCase()] ?? whole;
65
+ const code = body[1].toLowerCase() === "x" ? parseInt(body.slice(2), 16) : Number(body.slice(1));
66
+ return code > 0 && code <= 0x10ffff && !(code >= 0xd800 && code <= 0xdfff) ? String.fromCodePoint(code) : whole;
67
+ });
68
+ export const decodeBody = (body, contentType) => {
69
+ const declared = /charset=["']?([\w-]+)/i.exec(contentType ?? "")?.[1] ?? /<meta[^>]+charset=["']?([\w-]+)/i.exec(body.subarray(0, 2048).toString("latin1"))?.[1] ?? "utf-8";
70
+ try {
71
+ return new TextDecoder(declared).decode(body);
72
+ }
73
+ catch {
74
+ return new TextDecoder("utf-8").decode(body);
75
+ }
76
+ };
77
+ /** HTML beyond this is cut before conversion: the work below is linear, and no
78
+ * page worth reading needs more (the browser path keeps its own larger limit). */
79
+ const MAX_HTML_CHARS = 1500000;
80
+ /** Remove every `<tag ...>...</tag>` block for the given tags in one pass. An
81
+ * unclosed block is dropped to the end. Linear: each index is searched once,
82
+ * unlike a lazy regex, which rescans from every unclosed opening tag (a
83
+ * 400 KB page of unclosed tags held the process for 30 s). */
84
+ const stripBlocks = (html, tags) => {
85
+ const lower = html.toLowerCase();
86
+ let out = "", at = 0;
87
+ while (at < html.length) {
88
+ let open = -1, tag = "";
89
+ for (const name of tags) {
90
+ let found = lower.indexOf(`<${name}`, at);
91
+ // A longer tag name that merely starts the same way is not this tag.
92
+ while (found >= 0 && /[a-z0-9-]/.test(lower[found + name.length + 1] ?? ""))
93
+ found = lower.indexOf(`<${name}`, found + 1);
94
+ if (found >= 0 && (open < 0 || found < open)) {
95
+ open = found;
96
+ tag = name;
97
+ }
98
+ }
99
+ if (open < 0) {
100
+ out += html.slice(at);
101
+ break;
102
+ }
103
+ out += html.slice(at, open) + " ";
104
+ const close = lower.indexOf(`</${tag}`, open);
105
+ if (close < 0)
106
+ break;
107
+ const end = lower.indexOf(">", close);
108
+ if (end < 0)
109
+ break;
110
+ at = end + 1;
111
+ }
112
+ return out;
113
+ };
114
+ /** Inner HTML of the first `<tag>` block, found with two index searches. */
115
+ const firstBlock = (html, tag) => {
116
+ const lower = html.toLowerCase(), open = lower.search(new RegExp(`<${tag}[\\s>]`));
117
+ if (open < 0)
118
+ return undefined;
119
+ const start = lower.indexOf(">", open), close = lower.indexOf(`</${tag}`, open);
120
+ return start >= 0 && close > start ? html.slice(start + 1, close) : undefined;
121
+ };
122
+ /** Readable text of an HTML document without running it: headings keep the
123
+ * marker the snapshot reader navigates by, links are listed once at the end.
124
+ * Every pattern here is bounded or anchored on a single character class, so
125
+ * hostile markup costs time in proportion to its length, not its square. */
126
+ export function htmlToText(html, baseUrl, scope = "main") {
127
+ html = html.slice(0, MAX_HTML_CHARS);
128
+ const title = decodeEntities(/<title[^>]{0,200}>([^<]{0,500})/i.exec(html.slice(0, 20000))?.[1] ?? "").replace(/\s+/g, " ").trim();
129
+ let body = stripBlocks(html.replace(/<!--/g, "<codalicomment>").replace(/-->/g, "</codalicomment>"), ["codalicomment", "script", "style", "noscript", "svg", "template", "head", "iframe"]);
130
+ let used = "page";
131
+ if (scope === "main") {
132
+ const main = firstBlock(body, "main") ?? firstBlock(body, "article");
133
+ if (main && main.replace(/<[^>]*>/g, "").trim().length > 200) {
134
+ body = main;
135
+ used = "main";
136
+ }
137
+ else
138
+ body = stripBlocks(body, ["nav", "header", "footer"]);
139
+ }
140
+ const links = [], seen = new Set();
141
+ // An anchor's text is taken up to its close or 300 characters, whichever comes first.
142
+ for (const match of body.matchAll(/<a\s[^>]{0,2000}?href\s*=\s*(?:"([^"]{0,2000})"|'([^']{0,2000})')[^>]{0,2000}>([^<]{0,300})/gi)) {
143
+ if (links.length >= 128)
144
+ break;
145
+ try {
146
+ const target = new URL(decodeEntities(match[1] ?? match[2] ?? ""), baseUrl);
147
+ const label = decodeEntities(match[3]).replace(/\s+/g, " ").trim().slice(0, 160);
148
+ if (!["http:", "https:"].includes(target.protocol) || target.username || target.password || !label || seen.has(target.href))
149
+ continue;
150
+ seen.add(target.href);
151
+ links.push(`- link ${JSON.stringify(label)}\n - /url: ${target.href.slice(0, 1000)}`);
152
+ }
153
+ catch { /* Not a usable link. */ }
154
+ }
155
+ // The first 100 struck-through passages are marked, as the browser path does; the note is long.
156
+ const marked = [];
157
+ let marks = 0;
158
+ const struck = (opening) => {
159
+ if (opening) {
160
+ const mark = marks < 100;
161
+ if (mark)
162
+ marks++;
163
+ marked.push(mark);
164
+ return mark ? " [DELETED/STRUCK-THROUGH TEXT — not current guidance: " : " ";
165
+ }
166
+ return marked.pop() ? "] " : " ";
167
+ };
168
+ const text = decodeEntities(body
169
+ // Mark where headings and struck-through text begin and end; their inline tags go with the rest below.
170
+ .replace(/<h([1-6])(?:\s[^>]{0,2000})?>/gi, "\n\n\u0001$1\u0002").replace(/<\/h[1-6]\s*>/gi, "\u0003\n")
171
+ .replace(/<(\/?)(?:del|s|strike)(?:\s[^>]{0,2000})?>/gi, (_, closing) => struck(!closing))
172
+ .replace(/<\/(?:td|th)\s*>/gi, " | ").replace(/<\/?(?:a|b|i|u|em|strong|span|sup|sub|small|mark|abbr|code|cite|q|time|font|label)(?:\s[^>]{0,4000})?>/gi, "")
173
+ .replace(/<br\s*\/?>|<\/(?:p|div|li|tr|section|article|table|ul|ol|dd|dt|blockquote|pre)\s*>/gi, "\n").replace(/<li(?:\s[^>]{0,2000})?>/gi, "- ")
174
+ .replace(/<[^>]{0,8000}>/g, " "))
175
+ .replace(/\u0001([1-6])\u0002([^\u0001\u0003]{0,400})\u0003/g, (_, level, label) => {
176
+ const clean = label.replace(/\s+/g, " ").trim();
177
+ return clean ? `- heading ${JSON.stringify(clean)} [level=${level}]` : "";
178
+ }).replace(/[\u0001-\u0003]\d?/g, " ")
179
+ .replace(/[ \t\f\v\u00a0]+/g, " ").replace(/ \|? ?\n ?/g, "\n").replace(/\n /g, "\n").replace(/\n{3,}/g, "\n\n").trim();
180
+ return { title, scope: used, content: text && links.length ? `${text}\n\nSource links (first 128, bounded; not additional retrieved evidence):\n${links.join("\n").slice(0, 16000)}` : text };
181
+ }
182
+ const PDF_SCRIPT = `import sys, json
183
+ from pypdf import PdfReader
184
+ reader = PdfReader(sys.argv[1])
185
+ parts, total = [], 0
186
+ for index, page in enumerate(reader.pages):
187
+ text = (page.extract_text() or "").strip()
188
+ parts.append('- heading "Page %d" [level=2]\\n%s' % (index + 1, text))
189
+ total += len(text)
190
+ if total > 1000000: break
191
+ print(json.dumps({"pages": len(reader.pages), "read": len(parts), "text": "\\n\\n".join(parts)[:1000000]}))
192
+ `;
193
+ /** Text of a PDF, extracted offline in the sandbox: the document runtime's
194
+ * pypdf when installed, otherwise pdftotext when the host has it. Undefined
195
+ * when neither is available or the file holds no text layer. */
196
+ export async function pdfToText(bytes, signal, options = {}) {
197
+ if (bytes.subarray(0, 1024).indexOf("%PDF-") < 0)
198
+ return undefined;
199
+ const root = await fs.mkdtemp(path.join(os.tmpdir(), "codali-pdf-"));
200
+ try {
201
+ await fs.chmod(root, 0o700);
202
+ await fs.writeFile(path.join(root, "source.pdf"), bytes, { mode: 0o600 });
203
+ const runtime = path.resolve(options.pythonRoot ?? defaultDocumentPythonRoot());
204
+ const context = { workspaceRoot: root, signal, allowedWritePaths: [], shellTimeoutMs: 120000, shellMaxOutputBytes: 8 * 1024 * 1024 };
205
+ const hasRuntime = await fs.access(path.join(runtime, "bin/python")).then(() => true, () => false);
206
+ if (hasRuntime) {
207
+ try {
208
+ await fs.writeFile(path.join(root, "extract.py"), PDF_SCRIPT, { mode: 0o600 });
209
+ const run = await createIsolatedExecutor({ network: false, readOnlyRuntimeRoots: [runtime] })(path.join(runtime, "bin/python"), ["-I", "-B", path.join(root, "extract.py"), path.join(root, "source.pdf")], context);
210
+ const data = JSON.parse(run.data.stdout);
211
+ if (data.text.replace(/- heading "Page \d+" \[level=2\]/g, "").trim())
212
+ return { content: data.text, pages: data.pages, extractor: "pypdf", truncated: data.read < data.pages || data.text.length >= 1000000 };
213
+ }
214
+ catch (error) {
215
+ signal?.throwIfAborted();
216
+ void error; /* Try the host extractor. */
217
+ }
218
+ }
219
+ for (const directory of String(process.env.PATH ?? "").split(path.delimiter).filter(Boolean)) {
220
+ const binary = path.join(directory, "pdftotext");
221
+ if (!await fs.access(binary).then(() => true, () => false))
222
+ continue;
223
+ try {
224
+ const run = await createIsolatedExecutor({ network: false })(binary, ["-layout", "-enc", "UTF-8", path.join(root, "source.pdf"), "-"], context);
225
+ const text = run.data.stdout.split("\f").map((page, index) => page.trim() ? `- heading "Page ${index + 1}" [level=2]\n${page.trim()}` : "").filter(Boolean).join("\n\n");
226
+ if (text.trim())
227
+ return { content: text.slice(0, 1000000), pages: null, extractor: "pdftotext", truncated: text.length > 1000000 };
228
+ }
229
+ catch (error) {
230
+ signal?.throwIfAborted();
231
+ void error;
232
+ }
233
+ break;
234
+ }
235
+ return undefined;
236
+ }
237
+ finally {
238
+ await fs.rm(root, { recursive: true, force: true });
239
+ }
240
+ }
@@ -1,5 +1,20 @@
1
1
  import { type ToolDefinition } from "../ToolTypes.js";
2
+ export interface CalculationOptions {
3
+ /** Values usable by name. A Map, so no object or prototype lookup can occur. */
4
+ variables?: ReadonlyMap<string, number>;
5
+ /** Accept integers beyond 2^53 as rounded doubles and report that it happened. */
6
+ onInexactInteger?: () => void;
7
+ }
2
8
  /** Bounded Pratt parser; exponentiation is right associative and binds more tightly than unary minus. */
3
- export declare const evaluateCalculation: (expression: string) => number;
9
+ export declare const evaluateCalculation: (expression: string, options?: CalculationOptions) => number;
10
+ /** A calculation script: statements separated by ";" or line breaks, each either
11
+ * `name = formula` or a bare formula. Names are numbers held in a Map and can be
12
+ * used by later statements. Still the numeric grammar above: no code runs.
13
+ * The models write multi-step arithmetic this way; refusing it cost a round
14
+ * trip on about one calculator call in three. */
15
+ export declare const evaluateCalculationScript: (script: string, options?: CalculationOptions) => {
16
+ result: number | number[];
17
+ values: Record<string, number>;
18
+ };
4
19
  export declare const createCalculatorTool: () => ToolDefinition;
5
20
  //# sourceMappingURL=CalculatorTool.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"CalculatorTool.d.ts","sourceRoot":"","sources":["../../../src/tools/calculation/CalculatorTool.ts"],"names":[],"mappings":"AAAA,OAAO,EAAsB,KAAK,cAAc,EAAE,MAAM,iBAAiB,CAAC;AAsE1E,yGAAyG;AACzG,eAAO,MAAM,mBAAmB,GAAI,YAAY,MAAM,KAAG,MA0DxD,CAAC;AAEF,eAAO,MAAM,oBAAoB,QAAO,cA0BtC,CAAC"}
1
+ {"version":3,"file":"CalculatorTool.d.ts","sourceRoot":"","sources":["../../../src/tools/calculation/CalculatorTool.ts"],"names":[],"mappings":"AAAA,OAAO,EAAsB,KAAK,cAAc,EAAE,MAAM,iBAAiB,CAAC;AAkJ1E,MAAM,WAAW,kBAAkB;IACjC,gFAAgF;IAChF,SAAS,CAAC,EAAE,WAAW,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;IACxC,kFAAkF;IAClF,gBAAgB,CAAC,EAAE,MAAM,IAAI,CAAC;CAC/B;AAED,yGAAyG;AACzG,eAAO,MAAM,mBAAmB,GAAI,YAAY,MAAM,EAAE,UAAS,kBAAuB,KAAG,MAM1F,CAAC;AAyGF;;;;iDAIiD;AACjD,eAAO,MAAM,yBAAyB,GAAI,QAAQ,MAAM,EAAE,UAAS,kBAAuB,KAAG;IAAE,MAAM,EAAE,MAAM,GAAG,MAAM,EAAE,CAAC;IAAC,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAA;CA4CvJ,CAAC;AAWF,eAAO,MAAM,oBAAoB,QAAO,cA2DtC,CAAC"}