@mcoda/mswarm 0.1.135-codali.41 → 0.1.135-codali.42
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/dist/vendor/codali/cli/TerminalCommand.js +2 -2
- package/dist/vendor/codali/cli/tui/TerminalPresentation.js +1 -1
- package/dist/vendor/codali/config/OrchestrationConfig.d.ts +1 -0
- package/dist/vendor/codali/config/OrchestrationConfig.d.ts.map +1 -1
- package/dist/vendor/codali/config/OrchestrationConfig.js +3 -1
- package/dist/vendor/codali/docdex/DocdexClient.d.ts +11 -0
- package/dist/vendor/codali/docdex/DocdexClient.d.ts.map +1 -1
- package/dist/vendor/codali/docdex/DocdexClient.js +55 -1
- package/dist/vendor/codali/permissions/PermissionGate.d.ts +7 -0
- package/dist/vendor/codali/permissions/PermissionGate.d.ts.map +1 -1
- package/dist/vendor/codali/permissions/PermissionGate.js +26 -0
- package/dist/vendor/codali/providers/ConfiguredProvider.d.ts +2 -0
- package/dist/vendor/codali/providers/ConfiguredProvider.d.ts.map +1 -1
- package/dist/vendor/codali/providers/ConfiguredProvider.js +29 -0
- package/dist/vendor/codali/providers/ModelServiceError.d.ts +2 -2
- package/dist/vendor/codali/providers/ModelServiceError.d.ts.map +1 -1
- package/dist/vendor/codali/providers/ModelServiceError.js +4 -0
- package/dist/vendor/codali/runtime/ContextCompression.d.ts +5 -0
- package/dist/vendor/codali/runtime/ContextCompression.d.ts.map +1 -1
- package/dist/vendor/codali/runtime/ContextCompression.js +16 -4
- package/dist/vendor/codali/runtime/InteractionContract.d.ts +15 -0
- package/dist/vendor/codali/runtime/InteractionContract.d.ts.map +1 -1
- package/dist/vendor/codali/runtime/InteractionContract.js +33 -0
- package/dist/vendor/codali/runtime/InteractionRouter.d.ts +3 -3
- package/dist/vendor/codali/runtime/InteractionRouter.d.ts.map +1 -1
- package/dist/vendor/codali/runtime/InteractionRouter.js +1 -1
- package/dist/vendor/codali/runtime/OutageWait.d.ts +33 -5
- package/dist/vendor/codali/runtime/OutageWait.d.ts.map +1 -1
- package/dist/vendor/codali/runtime/OutageWait.js +68 -8
- package/dist/vendor/codali/runtime/ResearchEvidence.d.ts +14 -0
- package/dist/vendor/codali/runtime/ResearchEvidence.d.ts.map +1 -1
- package/dist/vendor/codali/runtime/ResearchEvidence.js +60 -0
- package/dist/vendor/codali/runtime/ReviewCoordinator.d.ts.map +1 -1
- package/dist/vendor/codali/runtime/ReviewCoordinator.js +2 -1
- package/dist/vendor/codali/runtime/ReviewSource.d.ts +5 -0
- package/dist/vendor/codali/runtime/ReviewSource.d.ts.map +1 -1
- package/dist/vendor/codali/runtime/ReviewSource.js +6 -1
- package/dist/vendor/codali/runtime/SessionController.d.ts +67 -1
- package/dist/vendor/codali/runtime/SessionController.d.ts.map +1 -1
- package/dist/vendor/codali/runtime/SessionController.js +443 -39
- package/dist/vendor/codali/runtime/TaskReview.d.ts.map +1 -1
- package/dist/vendor/codali/runtime/TaskReview.js +17 -2
- package/dist/vendor/codali/runtime/VerificationCommand.d.ts +8 -0
- package/dist/vendor/codali/runtime/VerificationCommand.d.ts.map +1 -1
- package/dist/vendor/codali/runtime/VerificationCommand.js +114 -0
- package/dist/vendor/codali/runtime/WorkingStyle.d.ts +20 -0
- package/dist/vendor/codali/runtime/WorkingStyle.d.ts.map +1 -0
- package/dist/vendor/codali/runtime/WorkingStyle.js +71 -0
- package/dist/vendor/codali/tools/ToolRegistry.d.ts.map +1 -1
- package/dist/vendor/codali/tools/ToolRegistry.js +19 -2
- package/dist/vendor/codali/tools/ToolTypes.d.ts +3 -0
- package/dist/vendor/codali/tools/ToolTypes.d.ts.map +1 -1
- package/dist/vendor/codali/tools/browser/BrowserTool.d.ts +23 -1
- package/dist/vendor/codali/tools/browser/BrowserTool.d.ts.map +1 -1
- package/dist/vendor/codali/tools/browser/BrowserTool.js +83 -4
- package/dist/vendor/codali/tools/browser/HttpFallback.d.ts +39 -0
- package/dist/vendor/codali/tools/browser/HttpFallback.d.ts.map +1 -0
- package/dist/vendor/codali/tools/browser/HttpFallback.js +240 -0
- package/dist/vendor/codali/tools/calculation/CalculatorTool.d.ts +16 -1
- package/dist/vendor/codali/tools/calculation/CalculatorTool.d.ts.map +1 -1
- package/dist/vendor/codali/tools/calculation/CalculatorTool.js +147 -20
- package/dist/vendor/codali/tools/shell/AsyncProcess.d.ts.map +1 -1
- package/dist/vendor/codali/tools/shell/AsyncProcess.js +6 -0
- package/dist/vendor/codali/tools/shell/IsolatedExecutor.d.ts.map +1 -1
- package/dist/vendor/codali/tools/shell/IsolatedExecutor.js +10 -2
- package/dist/vendor/codali/tools/shell/ShellTool.d.ts +2 -0
- package/dist/vendor/codali/tools/shell/ShellTool.d.ts.map +1 -1
- package/dist/vendor/codali/tools/shell/ShellTool.js +32 -2
- package/dist/vendor/codali/tools/verification/VitestTool.d.ts.map +1 -1
- package/dist/vendor/codali/tools/verification/VitestTool.js +75 -5
- package/dist/vendor/config/skills/testing-and-verification/SKILL.md +5 -5
- package/dist/vendor/config/skills/webapp-testing/SKILL.md +13 -0
- package/dist/vendor/config/skills/webapp-testing/journey-driver.mjs +85 -0
- package/package.json +3 -3
|
@@ -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;
|
|
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;
|
|
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;AA4F1E,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;AAmEF;;;;iDAIiD;AACjD,eAAO,MAAM,yBAAyB,GAAI,QAAQ,MAAM,EAAE,UAAS,kBAAuB,KAAG;IAAE,MAAM,EAAE,MAAM,CAAC;IAAC,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAA;CAiC5I,CAAC;AAWF,eAAO,MAAM,oBAAoB,QAAO,cAuCtC,CAAC"}
|
|
@@ -1,16 +1,22 @@
|
|
|
1
1
|
import { ToolExecutionError } from "../ToolTypes.js";
|
|
2
|
+
/** Set while a caller accepts integers beyond 2^53 as rounded doubles (capacity
|
|
3
|
+
* arithmetic such as bytes per year); without it they are refused as inexact. */
|
|
4
|
+
let inexactInteger;
|
|
2
5
|
const finite = (value) => {
|
|
3
6
|
if (!Number.isFinite(value))
|
|
4
7
|
throw new Error("Calculation is undefined or exceeds finite numeric range");
|
|
5
|
-
if (Number.isInteger(value) && !Number.isSafeInteger(value))
|
|
6
|
-
|
|
8
|
+
if (Number.isInteger(value) && !Number.isSafeInteger(value)) {
|
|
9
|
+
if (!inexactInteger)
|
|
10
|
+
throw new Error("Integer exceeds exact supported range");
|
|
11
|
+
inexactInteger();
|
|
12
|
+
}
|
|
7
13
|
return value;
|
|
8
14
|
};
|
|
9
15
|
/** A numeric grammar, not JavaScript: every character is consumed, and nothing is evaluated as code. */
|
|
10
16
|
const tokenize = (expression) => {
|
|
11
17
|
if (typeof expression !== "string" || !expression.trim() || expression.length > 4096)
|
|
12
18
|
throw new Error("Expected an expression of 1 to 4096 characters");
|
|
13
|
-
const pattern = /\s+|(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?|Math\.[A-Za-z_][A-Za-z_0-9]*|[A-Za-z_][A-Za-z_0-9]*|\*\*|[+*/%^()
|
|
19
|
+
const pattern = /\s+|(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?|Math\.[A-Za-z_][A-Za-z_0-9]*|[A-Za-z_][A-Za-z_0-9]*|\*\*|[+*/%^(),=;-]/y;
|
|
14
20
|
const tokens = [];
|
|
15
21
|
let offset = 0;
|
|
16
22
|
while (offset < expression.length) {
|
|
@@ -22,7 +28,7 @@ const tokenize = (expression) => {
|
|
|
22
28
|
// Literal aliases enter the same bounded grammar; no object lookup or code execution.
|
|
23
29
|
const token = match[0].startsWith("Math.") ? match[0].slice(5) : match[0];
|
|
24
30
|
if (token.trim())
|
|
25
|
-
tokens.push(token
|
|
31
|
+
tokens.push(token);
|
|
26
32
|
if (tokens.length > 1024)
|
|
27
33
|
throw new Error("Expression exceeds 1024 tokens");
|
|
28
34
|
}
|
|
@@ -61,6 +67,20 @@ const functions = new Map([
|
|
|
61
67
|
["sin", { min: 1, max: 1, run: Math.sin }],
|
|
62
68
|
["cos", { min: 1, max: 1, run: Math.cos }],
|
|
63
69
|
["tan", { min: 1, max: 1, run: Math.tan }],
|
|
70
|
+
// Orbit, heading and angle questions were answered from memory after asin,
|
|
71
|
+
// acos, atan and atan2 were each refused.
|
|
72
|
+
["asin", { min: 1, max: 1, run: Math.asin }],
|
|
73
|
+
["acos", { min: 1, max: 1, run: Math.acos }],
|
|
74
|
+
["atan", { min: 1, max: 1, run: Math.atan }],
|
|
75
|
+
["atan2", { min: 2, max: 2, run: Math.atan2 }],
|
|
76
|
+
["sinh", { min: 1, max: 1, run: Math.sinh }],
|
|
77
|
+
["cosh", { min: 1, max: 1, run: Math.cosh }],
|
|
78
|
+
["tanh", { min: 1, max: 1, run: Math.tanh }],
|
|
79
|
+
["log2", { min: 1, max: 1, run: Math.log2 }],
|
|
80
|
+
["cbrt", { min: 1, max: 1, run: Math.cbrt }],
|
|
81
|
+
["hypot", { min: 1, max: 128, run: Math.hypot }],
|
|
82
|
+
["trunc", { min: 1, max: 1, run: Math.trunc }],
|
|
83
|
+
["sign", { min: 1, max: 1, run: Math.sign }],
|
|
64
84
|
["pow", { min: 2, max: 2, run: Math.pow }],
|
|
65
85
|
["floor", { min: 1, max: 1, run: Math.floor }],
|
|
66
86
|
["ceil", { min: 1, max: 1, run: Math.ceil }],
|
|
@@ -74,9 +94,22 @@ const functions = new Map([
|
|
|
74
94
|
...["perm", "nPr", "P"].map(name => [name, { min: 2, max: 2, run: permutations }]),
|
|
75
95
|
["factorial", { min: 1, max: 1, run: (n) => permutations(n, n) }],
|
|
76
96
|
]);
|
|
97
|
+
const variableName = (name) => !!name && /^[A-Za-z][A-Za-z_0-9]{0,63}$/.test(name);
|
|
77
98
|
/** Bounded Pratt parser; exponentiation is right associative and binds more tightly than unary minus. */
|
|
78
|
-
export const evaluateCalculation = (expression) => {
|
|
99
|
+
export const evaluateCalculation = (expression, options = {}) => {
|
|
79
100
|
const tokens = tokenize(expression);
|
|
101
|
+
if (tokens.includes("=") || tokens.includes(";"))
|
|
102
|
+
throw new Error("One formula only; assignments and several statements belong in a calculation script");
|
|
103
|
+
const previous = inexactInteger;
|
|
104
|
+
inexactInteger = options.onInexactInteger;
|
|
105
|
+
try {
|
|
106
|
+
return evaluateTokens(tokens, options.variables);
|
|
107
|
+
}
|
|
108
|
+
finally {
|
|
109
|
+
inexactInteger = previous;
|
|
110
|
+
}
|
|
111
|
+
};
|
|
112
|
+
const evaluateTokens = (tokens, variables) => {
|
|
80
113
|
let position = 0;
|
|
81
114
|
const expect = (token) => {
|
|
82
115
|
if (tokens[position++] !== token)
|
|
@@ -97,14 +130,19 @@ export const evaluateCalculation = (expression) => {
|
|
|
97
130
|
}
|
|
98
131
|
else if (token && /^(?:\d|\.)/.test(token))
|
|
99
132
|
value = finite(Number(token));
|
|
100
|
-
|
|
133
|
+
// An assigned name wins over a constant or function of the same spelling:
|
|
134
|
+
// e is an eccentricity and P a pressure as often as they are e and nPr.
|
|
135
|
+
else if (token && variables?.has(token) && tokens[position] !== "(")
|
|
136
|
+
value = variables.get(token);
|
|
137
|
+
else if (token === "pi" || token === "PI")
|
|
101
138
|
value = Math.PI;
|
|
102
|
-
else if (token === "e")
|
|
139
|
+
else if (token === "e" || token === "E")
|
|
103
140
|
value = Math.E;
|
|
104
141
|
else {
|
|
105
142
|
const fn = functions.get(token);
|
|
106
143
|
if (!fn)
|
|
107
|
-
throw new Error(`
|
|
144
|
+
throw new Error(variableName(token) ? `Unknown name ${token}: assign it first (${token} = ...) or use a supported function`
|
|
145
|
+
: `Expected a number or supported function, received ${token ?? "end of expression"}`);
|
|
108
146
|
expect("(");
|
|
109
147
|
const args = [];
|
|
110
148
|
if (tokens[position] !== ")") {
|
|
@@ -158,11 +196,83 @@ export const evaluateCalculation = (expression) => {
|
|
|
158
196
|
// JSON has a single zero representation; keep the exported numeric API consistent.
|
|
159
197
|
return result === 0 ? 0 : result;
|
|
160
198
|
};
|
|
199
|
+
const MAX_STATEMENTS = 64;
|
|
200
|
+
/** A calculation script: statements separated by ";" or line breaks, each either
|
|
201
|
+
* `name = formula` or a bare formula. Names are numbers held in a Map and can be
|
|
202
|
+
* used by later statements. Still the numeric grammar above: no code runs.
|
|
203
|
+
* The models write multi-step arithmetic this way; refusing it cost a round
|
|
204
|
+
* trip on about one calculator call in three. */
|
|
205
|
+
export const evaluateCalculationScript = (script, options = {}) => {
|
|
206
|
+
if (typeof script !== "string" || !script.trim() || script.length > 4096)
|
|
207
|
+
throw new Error("Expected an expression of 1 to 4096 characters");
|
|
208
|
+
// A line break separates statements only outside parentheses, so a formula may wrap.
|
|
209
|
+
const statements = [];
|
|
210
|
+
let depth = 0, piece = "";
|
|
211
|
+
for (const char of script) {
|
|
212
|
+
if (char === "(")
|
|
213
|
+
depth++;
|
|
214
|
+
else if (char === ")")
|
|
215
|
+
depth = Math.max(0, depth - 1);
|
|
216
|
+
if (char === ";" || char === "\n" && depth === 0) {
|
|
217
|
+
statements.push(piece);
|
|
218
|
+
piece = "";
|
|
219
|
+
}
|
|
220
|
+
else
|
|
221
|
+
piece += char === "\n" ? " " : char;
|
|
222
|
+
}
|
|
223
|
+
statements.push(piece);
|
|
224
|
+
for (let index = statements.length - 1; index >= 0; index--) {
|
|
225
|
+
statements[index] = statements[index].trim();
|
|
226
|
+
if (!statements[index])
|
|
227
|
+
statements.splice(index, 1);
|
|
228
|
+
}
|
|
229
|
+
if (!statements.length)
|
|
230
|
+
throw new Error("Expected an expression of 1 to 4096 characters");
|
|
231
|
+
if (statements.length > MAX_STATEMENTS)
|
|
232
|
+
throw new Error(`A calculation holds at most ${MAX_STATEMENTS} statements`);
|
|
233
|
+
const variables = new Map(options.variables ?? []);
|
|
234
|
+
const values = new Map();
|
|
235
|
+
let result = NaN;
|
|
236
|
+
const previous = inexactInteger;
|
|
237
|
+
inexactInteger = options.onInexactInteger;
|
|
238
|
+
try {
|
|
239
|
+
for (const statement of statements) {
|
|
240
|
+
const tokens = tokenize(statement);
|
|
241
|
+
if (tokens[1] === "=") {
|
|
242
|
+
const name = tokens[0];
|
|
243
|
+
if (!variableName(name))
|
|
244
|
+
throw new Error(`${name} cannot be assigned: a name starts with a letter and holds letters, digits or _`);
|
|
245
|
+
if (tokens.indexOf("=", 2) !== -1)
|
|
246
|
+
throw new Error("One assignment per statement");
|
|
247
|
+
result = evaluateTokens(tokens.slice(2), variables);
|
|
248
|
+
variables.set(name, result);
|
|
249
|
+
values.set(name, result);
|
|
250
|
+
}
|
|
251
|
+
else {
|
|
252
|
+
if (tokens.includes("="))
|
|
253
|
+
throw new Error("Assignments take the form name = formula");
|
|
254
|
+
result = evaluateTokens(tokens, variables);
|
|
255
|
+
}
|
|
256
|
+
}
|
|
257
|
+
}
|
|
258
|
+
finally {
|
|
259
|
+
inexactInteger = previous;
|
|
260
|
+
}
|
|
261
|
+
return { result: result === 0 ? 0 : result, values: Object.fromEntries(values) };
|
|
262
|
+
};
|
|
263
|
+
const ARITHMETIC = "IEEE-754 double; not exact decimal arithmetic";
|
|
264
|
+
/** Names that are constants until a calculation assigns them. */
|
|
265
|
+
const CONSTANT_NAMES = new Set(["e", "E", "pi", "PI"]);
|
|
266
|
+
const shadowNote = (names) => {
|
|
267
|
+
const shadowed = names.filter(name => CONSTANT_NAMES.has(name));
|
|
268
|
+
return shadowed.length ? `${shadowed.join(", ")} ${shadowed.length > 1 ? "were" : "was"} given a value here, so later formulas use that value, not the constant (${shadowed.map(name => name.toLowerCase() === "e" ? "Euler's number: use exp(x)" : "pi: use acos(-1)").join("; ")}).` : undefined;
|
|
269
|
+
};
|
|
270
|
+
const INEXACT = "An integer above 2^53 was rounded to about 16 significant digits; use decimal_calculate where every digit matters";
|
|
161
271
|
export const createCalculatorTool = () => ({
|
|
162
272
|
name: "calculate", capability: "calculation", readOnly: true,
|
|
163
|
-
description: "Calculate {expression:'formula'} OR {expressions:{label:'formula'}} (up
|
|
164
|
-
inputSchema: { type: "object", properties: { expression: { type: "string", description: "
|
|
165
|
-
expressions: { type: "object", description: "Map labels to complete formula STRINGS, e.g. {total:'2*3+4',check:'10'}.
|
|
273
|
+
description: "Calculate {expression:'formula'} OR {expressions:{label:'formula'}} (up to 64). An expression may hold several statements separated by ; with names: 'r1 = 6778; v = sqrt(398600/r1); v*2'. In expressions, a later formula may use an earlier label as a number. Supports exp,ln/log(natural),log2,log10,pow,sqrt,cbrt,hypot,sin/cos/tan,asin/acos/atan/atan2,sinh/cosh/tanh (radians),abs,floor,ceil,round,trunc,sign,min,max,sum,comb/C(n,k),perm/P(n,k),factorial; + - * / %, ^ **, pi,e. Math.function aliases accepted only for this allowlist. Numbers only: no strings, lists, loops, imports or code. IEEE-754 approximate; exact decimals use decimal_calculate. Tool success checks arithmetic, not whether your formula models the request.",
|
|
274
|
+
inputSchema: { type: "object", properties: { expression: { type: "string", description: "A numeric formula, e.g. exp(-2)*3, or statements separated by ; such as 'a = 2*3; b = a+4; b/2'. Supply this OR expressions.", minLength: 1, maxLength: 4096 },
|
|
275
|
+
expressions: { type: "object", description: "Map labels to complete formula STRINGS, e.g. {total:'2*3+4',check:'10'}. A formula may use the label of an earlier formula as a number. Supply this OR expression.", minProperties: 1, maxProperties: 64, propertyNames: { pattern: "^[A-Za-z][A-Za-z0-9_]{0,63}$" }, additionalProperties: true },
|
|
166
276
|
}, oneOf: [{ required: ["expression"] }, { required: ["expressions"] }], additionalProperties: false },
|
|
167
277
|
handler: async (args, context) => {
|
|
168
278
|
context.signal?.throwIfAborted();
|
|
@@ -170,22 +280,39 @@ export const createCalculatorTool = () => ({
|
|
|
170
280
|
const input = args;
|
|
171
281
|
if (!input || typeof input !== "object" || Array.isArray(input) || input.expression === undefined && input.expressions === undefined)
|
|
172
282
|
throw new Error('Use {"expression":"2+3"} or {"expressions":{"total":"2+3"}}; formulas must be strings');
|
|
283
|
+
let inexact = false;
|
|
284
|
+
const options = { onInexactInteger: () => { inexact = true; } };
|
|
285
|
+
let assigned = [];
|
|
286
|
+
const note = () => { const warnings = [inexact ? INEXACT : undefined, shadowNote(assigned)].filter(Boolean); return warnings.length ? { arithmetic: ARITHMETIC, warning: warnings.join(" ") } : { arithmetic: ARITHMETIC }; };
|
|
173
287
|
if (input.expressions !== undefined) {
|
|
174
|
-
if (input.expression !== undefined
|
|
175
|
-
throw new Error("Supply expression or
|
|
176
|
-
|
|
288
|
+
if (input.expression !== undefined)
|
|
289
|
+
throw new Error("Supply expression or expressions, not both");
|
|
290
|
+
if (!input.expressions || typeof input.expressions !== "object" || Array.isArray(input.expressions) || Object.keys(input.expressions).length < 1 || Object.keys(input.expressions).length > MAX_STATEMENTS)
|
|
291
|
+
throw new Error(`Supply 1 to ${MAX_STATEMENTS} named expressions`);
|
|
292
|
+
const variables = new Map();
|
|
293
|
+
const results = {};
|
|
294
|
+
for (const [label, expression] of Object.entries(input.expressions)) {
|
|
177
295
|
if (!/^[A-Za-z][A-Za-z0-9_]{0,63}$/.test(label))
|
|
178
296
|
throw new Error("Invalid calculation label");
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
297
|
+
if (typeof expression !== "string")
|
|
298
|
+
throw new Error(`Formula ${label} must be a string such as "2*3+4"`);
|
|
299
|
+
const value = evaluateCalculation(expression, { ...options, variables });
|
|
300
|
+
results[label] = value;
|
|
301
|
+
if (variableName(label))
|
|
302
|
+
variables.set(label, value);
|
|
303
|
+
}
|
|
304
|
+
assigned = Object.keys(results);
|
|
305
|
+
return { output: JSON.stringify({ results, ...note() }) };
|
|
182
306
|
}
|
|
183
|
-
|
|
184
|
-
|
|
307
|
+
if (typeof input.expression !== "string")
|
|
308
|
+
throw new Error('Use {"expression":"2+3"}; the formula must be a string');
|
|
309
|
+
const { result, values } = evaluateCalculationScript(input.expression, options);
|
|
310
|
+
assigned = Object.keys(values);
|
|
311
|
+
return { output: JSON.stringify(Object.keys(values).length ? { result, values, ...note() } : { result, ...note() }) };
|
|
185
312
|
}
|
|
186
313
|
catch (error) {
|
|
187
314
|
const message = error instanceof Error ? error.message : String(error);
|
|
188
|
-
throw new ToolExecutionError("tool_invalid_args", `${message}. Correct the arguments before retrying; use tools_describe for the schema.
|
|
315
|
+
throw new ToolExecutionError("tool_invalid_args", `${message}. Correct the arguments before retrying; use tools_describe for the schema. Numbers, names (a = 2*3; a+1) and the listed functions only; strings, lists, loops and imports need a code tool such as verify_javascript.`, { retryable: false });
|
|
189
316
|
}
|
|
190
317
|
},
|
|
191
318
|
});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"AsyncProcess.d.ts","sourceRoot":"","sources":["../../../src/tools/shell/AsyncProcess.ts"],"names":[],"mappings":"AAEA,OAAO,EAAsB,KAAK,WAAW,EAAE,KAAK,iBAAiB,EAAE,MAAM,iBAAiB,CAAC;AAG/F,eAAO,MAAM,sBAAsB,QAAO,MAAM,CAAC,UAGhD,CAAC;AAEF,kFAAkF;AAClF,MAAM,WAAW,kBAAkB;IACjC,IAAI,CAAC,EAAE,MAAM,CAAC;IAAC,MAAM,CAAC,EAAE,MAAM,CAAC;IAAC,IAAI,CAAC,EAAE,MAAM,CAAC;IAC9C,UAAU,CAAC,EAAE,MAAM,CAAC;IAAC,cAAc,CAAC,EAAE,MAAM,CAAC;IAAC,mBAAmB,CAAC,EAAE,MAAM,CAAC;IAAC,cAAc,CAAC,EAAE,MAAM,CAAC;IACpG,gBAAgB,CAAC,EAAE,MAAM,CAAC;IAAC,gBAAgB,CAAC,EAAE,MAAM,CAAC;IAAC,aAAa,CAAC,EAAE,MAAM,CAAC;IAAC,YAAY,CAAC,EAAE,MAAM,CAAC;IACpG,OAAO,CAAC,EAAE,MAAM,CAAC;IAAC,aAAa,CAAC,EAAE,MAAM,CAAC;IACzC,mBAAmB,CAAC,EAAE,MAAM,CAAC;IAAC,iBAAiB,CAAC,EAAE,MAAM,CAAC;IAAC,iBAAiB,CAAC,EAAE,MAAM,CAAC;CACtF;AASD,eAAO,MAAM,UAAU,GAAI,SAAS,MAAM,EAAE,MAAM,MAAM,EAAE,EAAE,SAAS,WAAW,EAAE,cAAa,kBAAuB,KAAG,OAAO,CAAC,iBAAiB,
|
|
1
|
+
{"version":3,"file":"AsyncProcess.d.ts","sourceRoot":"","sources":["../../../src/tools/shell/AsyncProcess.ts"],"names":[],"mappings":"AAEA,OAAO,EAAsB,KAAK,WAAW,EAAE,KAAK,iBAAiB,EAAE,MAAM,iBAAiB,CAAC;AAG/F,eAAO,MAAM,sBAAsB,QAAO,MAAM,CAAC,UAGhD,CAAC;AAEF,kFAAkF;AAClF,MAAM,WAAW,kBAAkB;IACjC,IAAI,CAAC,EAAE,MAAM,CAAC;IAAC,MAAM,CAAC,EAAE,MAAM,CAAC;IAAC,IAAI,CAAC,EAAE,MAAM,CAAC;IAC9C,UAAU,CAAC,EAAE,MAAM,CAAC;IAAC,cAAc,CAAC,EAAE,MAAM,CAAC;IAAC,mBAAmB,CAAC,EAAE,MAAM,CAAC;IAAC,cAAc,CAAC,EAAE,MAAM,CAAC;IACpG,gBAAgB,CAAC,EAAE,MAAM,CAAC;IAAC,gBAAgB,CAAC,EAAE,MAAM,CAAC;IAAC,aAAa,CAAC,EAAE,MAAM,CAAC;IAAC,YAAY,CAAC,EAAE,MAAM,CAAC;IACpG,OAAO,CAAC,EAAE,MAAM,CAAC;IAAC,aAAa,CAAC,EAAE,MAAM,CAAC;IACzC,mBAAmB,CAAC,EAAE,MAAM,CAAC;IAAC,iBAAiB,CAAC,EAAE,MAAM,CAAC;IAAC,iBAAiB,CAAC,EAAE,MAAM,CAAC;CACtF;AASD,eAAO,MAAM,UAAU,GAAI,SAAS,MAAM,EAAE,MAAM,MAAM,EAAE,EAAE,SAAS,WAAW,EAAE,cAAa,kBAAuB,KAAG,OAAO,CAAC,iBAAiB,CAmDjJ,CAAC"}
|
|
@@ -90,6 +90,12 @@ export const runProcess = (command, args, context, environment = {}) => {
|
|
|
90
90
|
reject(new ToolExecutionError("tool_timeout", processFailureMessage("Process deadline exceeded", stdout, stderr), { retryable: false, details }));
|
|
91
91
|
return;
|
|
92
92
|
}
|
|
93
|
+
// Killed from outside (SIGKILL with no timeout of ours: usually the kernel
|
|
94
|
+
// reclaiming memory on a crowded host), the command itself may be fine.
|
|
95
|
+
if (signal === "SIGKILL" || exitCode === 137) {
|
|
96
|
+
reject(new ToolExecutionError("tool_execution_failed", processFailureMessage("Process was killed from outside (SIGKILL, often the system running out of memory). The command itself may be correct; running it again, or with less parallelism, may succeed", stdout, stderr), { retryable: true, details }));
|
|
97
|
+
return;
|
|
98
|
+
}
|
|
93
99
|
if (exitCode !== 0 || signal) {
|
|
94
100
|
reject(new ToolExecutionError("tool_execution_failed", processFailureMessage(`Process terminated (${signal ?? exitCode})`, stdout, stderr), { retryable: false, details }));
|
|
95
101
|
return;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"IsolatedExecutor.d.ts","sourceRoot":"","sources":["../../../src/tools/shell/IsolatedExecutor.ts"],"names":[],"mappings":"AAMA,OAAO,EAAsB,KAAK,WAAW,EAAE,KAAK,iBAAiB,EAAE,MAAM,iBAAiB,CAAC;AAC/F,OAAO,EAA8D,KAAK,WAAW,EAAE,MAAM,oBAAoB,CAAC;AAElH,MAAM,WAAW,cAAc;IAAG,SAAS,EAAE,OAAO,CAAC;IAAC,OAAO,EAAE,YAAY,GAAG,cAAc,GAAG,aAAa,CAAC;IAAC,MAAM,CAAC,EAAE,MAAM,CAAC;CAAE;AAEhI,mFAAmF;AACnF,eAAO,MAAM,oBAAoB,GAAI,MAAM,MAAM,EAAE,SAAS,MAAM,EAAE,YAAY,MAAM,EAAE,EAAE,UAAU,WAAW,EAAE,EAAE,iBAAe,EAAE,eAAc,MAAM,EAAO,EAAE,iBAAgB,MAAM,EAAO,EAAE,YAAY,MAAM,EAAE,iBAAiB,MAAM,KAAG,MAkC7O,CAAC;AA6BF,eAAO,MAAM,cAAc,QAAO,
|
|
1
|
+
{"version":3,"file":"IsolatedExecutor.d.ts","sourceRoot":"","sources":["../../../src/tools/shell/IsolatedExecutor.ts"],"names":[],"mappings":"AAMA,OAAO,EAAsB,KAAK,WAAW,EAAE,KAAK,iBAAiB,EAAE,MAAM,iBAAiB,CAAC;AAC/F,OAAO,EAA8D,KAAK,WAAW,EAAE,MAAM,oBAAoB,CAAC;AAElH,MAAM,WAAW,cAAc;IAAG,SAAS,EAAE,OAAO,CAAC;IAAC,OAAO,EAAE,YAAY,GAAG,cAAc,GAAG,aAAa,CAAC;IAAC,MAAM,CAAC,EAAE,MAAM,CAAC;CAAE;AAEhI,mFAAmF;AACnF,eAAO,MAAM,oBAAoB,GAAI,MAAM,MAAM,EAAE,SAAS,MAAM,EAAE,YAAY,MAAM,EAAE,EAAE,UAAU,WAAW,EAAE,EAAE,iBAAe,EAAE,eAAc,MAAM,EAAO,EAAE,iBAAgB,MAAM,EAAO,EAAE,YAAY,MAAM,EAAE,iBAAiB,MAAM,KAAG,MAkC7O,CAAC;AA6BF,eAAO,MAAM,cAAc,QAAO,cAqBjC,CAAC;AAuBF,eAAO,MAAM,sBAAsB,GAAI,UAAS;IAAE,OAAO,CAAC,EAAE,OAAO,CAAC;IAAC,MAAM,CAAC,EAAE,cAAc,CAAC,CAAC,0DAA0D;IAAC,SAAS,CAAC,EAAE,MAAM,CAAC,CAAC,mFAAmF;IAAC,WAAW,CAAC,EAAE,MAAM,CAAC,CAAC,+DAA+D;IAAC,oBAAoB,CAAC,EAAE,MAAM,EAAE,CAAA;CAAO,KAAG,CAAC,CAAC,OAAO,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,EAAE,EAAE,OAAO,EAAE,WAAW,KAAK,OAAO,CAAC,iBAAiB,CAAC,CAoGrd,CAAC"}
|
|
@@ -81,8 +81,16 @@ export const executorStatus = () => {
|
|
|
81
81
|
if (process.platform === "linux") {
|
|
82
82
|
if (!existsSync("/usr/bin/bwrap"))
|
|
83
83
|
return { available: false, backend: "unavailable", reason: "Install bubblewrap to enable isolated shell execution" };
|
|
84
|
-
|
|
85
|
-
|
|
84
|
+
// On a busy host the probe itself can take seconds. A probe that ran out of
|
|
85
|
+
// time says nothing about user namespaces, so it is tried again with more
|
|
86
|
+
// time before the sandbox is declared missing (a full test run on a loaded
|
|
87
|
+
// machine skipped fourteen sandbox tests for this reason).
|
|
88
|
+
let probe = spawnSync("/usr/bin/bwrap", [...bubblewrapRoot(), "--", "/usr/bin/true"], { timeout: 3000, stdio: "ignore" });
|
|
89
|
+
const timedOut = () => probe.status === null && (probe.error?.code === "ETIMEDOUT" || probe.signal === "SIGTERM");
|
|
90
|
+
if (timedOut())
|
|
91
|
+
probe = spawnSync("/usr/bin/bwrap", [...bubblewrapRoot(), "--", "/usr/bin/true"], { timeout: 20000, stdio: "ignore" });
|
|
92
|
+
return probe.status === 0 ? { available: true, backend: "bubblewrap" }
|
|
93
|
+
: { available: false, backend: "unavailable", reason: timedOut() ? "the bubblewrap sandbox did not start within 20 seconds; the host may be overloaded" : "bubblewrap user namespaces are unavailable" };
|
|
86
94
|
}
|
|
87
95
|
if (process.platform === "darwin" && existsSync("/usr/bin/sandbox-exec")) {
|
|
88
96
|
const scratch = realpathSync(mkdtempSync(path.join(os.tmpdir(), "codali-isolation-probe-")));
|
|
@@ -1,5 +1,7 @@
|
|
|
1
1
|
import { type ToolDefinition } from "../ToolTypes.js";
|
|
2
2
|
/** Shared by terminal execution and tool-enabled benchmark baselines. */
|
|
3
3
|
export declare const DEVELOPMENT_COMMANDS: string[];
|
|
4
|
+
export declare const DEFAULT_SHELL_TIMEOUT_SECONDS = 120;
|
|
5
|
+
export declare const MAX_SHELL_TIMEOUT_SECONDS = 900;
|
|
4
6
|
export declare const createShellTool: () => ToolDefinition;
|
|
5
7
|
//# sourceMappingURL=ShellTool.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ShellTool.d.ts","sourceRoot":"","sources":["../../../src/tools/shell/ShellTool.ts"],"names":[],"mappings":"AACA,OAAO,EAAwC,KAAK,cAAc,EAAE,MAAM,iBAAiB,CAAC;AAI5F,yEAAyE;AACzE,eAAO,MAAM,oBAAoB,UAA4iB,CAAC;
|
|
1
|
+
{"version":3,"file":"ShellTool.d.ts","sourceRoot":"","sources":["../../../src/tools/shell/ShellTool.ts"],"names":[],"mappings":"AACA,OAAO,EAAwC,KAAK,cAAc,EAAE,MAAM,iBAAiB,CAAC;AAI5F,yEAAyE;AACzE,eAAO,MAAM,oBAAoB,UAA4iB,CAAC;AAO9kB,eAAO,MAAM,6BAA6B,MAAM,CAAC;AACjD,eAAO,MAAM,yBAAyB,MAAM,CAAC;AA6C7C,eAAO,MAAM,eAAe,QAAO,cAqFjC,CAAC"}
|