@mumbrane/leto 0.0.0-stage → 0.19.0

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 (56) hide show
  1. package/README.md +395 -2
  2. package/bin/leto.js +8 -0
  3. package/evals/core/suite.json +249 -0
  4. package/index.js +12 -0
  5. package/package.json +43 -4
  6. package/src/agent.js +572 -0
  7. package/src/agents.js +68 -0
  8. package/src/anthropic.js +204 -0
  9. package/src/browser.js +427 -0
  10. package/src/btw.js +56 -0
  11. package/src/checkpoints.js +90 -0
  12. package/src/ci.js +115 -0
  13. package/src/cli.js +1926 -0
  14. package/src/client.js +111 -0
  15. package/src/config.js +205 -0
  16. package/src/documents.js +198 -0
  17. package/src/eval.js +289 -0
  18. package/src/hooks.js +115 -0
  19. package/src/ide.js +231 -0
  20. package/src/input.js +148 -0
  21. package/src/jobs.js +97 -0
  22. package/src/legacy.js +41 -0
  23. package/src/lsp.js +401 -0
  24. package/src/markdown.js +153 -0
  25. package/src/mcp.js +346 -0
  26. package/src/memory.js +136 -0
  27. package/src/orchestrator.js +141 -0
  28. package/src/patching.js +185 -0
  29. package/src/permissions.js +75 -0
  30. package/src/plugins.js +118 -0
  31. package/src/policy.js +74 -0
  32. package/src/pricing.js +67 -0
  33. package/src/processes.js +139 -0
  34. package/src/prompt.js +134 -0
  35. package/src/prompts.js +189 -0
  36. package/src/providers.js +59 -0
  37. package/src/repomap.js +211 -0
  38. package/src/sandbox.js +90 -0
  39. package/src/sdk.js +220 -0
  40. package/src/selftool.js +238 -0
  41. package/src/serve.js +233 -0
  42. package/src/session.js +168 -0
  43. package/src/setup.js +157 -0
  44. package/src/skills.js +125 -0
  45. package/src/theme.js +185 -0
  46. package/src/toolcalls.js +257 -0
  47. package/src/tools.js +976 -0
  48. package/src/tui.js +1179 -0
  49. package/src/ui.js +454 -0
  50. package/src/update.js +33 -0
  51. package/src/usage.js +83 -0
  52. package/src/verify.js +131 -0
  53. package/src/version.js +3 -0
  54. package/src/worktree.js +87 -0
  55. package/vscode/extension.js +132 -0
  56. package/vscode/package.json +21 -0
package/src/client.js ADDED
@@ -0,0 +1,111 @@
1
+ // Minimal client for OpenAI-compatible /chat/completions with streaming and tool calls.
2
+ import { getProvider, normalizeModels } from './providers.js';
3
+ import { isNativeAnthropic, listAnthropicModels } from './anthropic.js';
4
+
5
+ // Providers known to support stream_options.include_usage.
6
+ const USAGE_PROVIDERS = new Set(['openai', 'openrouter']);
7
+
8
+ function headers(config) {
9
+ const h = { 'content-type': 'application/json' };
10
+ if (config.apiKey) h.authorization = `Bearer ${config.apiKey}`;
11
+ return h;
12
+ }
13
+
14
+ async function request(config, pathname, init, { retries = 3, extraHeaders } = {}) {
15
+ const url = `${config.baseUrl}${pathname}`;
16
+ for (let attempt = 0; ; attempt++) {
17
+ let res;
18
+ try {
19
+ res = await fetch(url, { ...init, headers: extraHeaders ? { 'content-type': 'application/json', ...extraHeaders } : headers(config) });
20
+ } catch (err) {
21
+ if (err.name === 'AbortError') throw err;
22
+ if (attempt < retries) {
23
+ await sleep(500 * 2 ** attempt, init.signal);
24
+ continue;
25
+ }
26
+ const e = new Error(`Could not reach ${config.baseUrl} (${err.cause?.code || err.message}).`);
27
+ e.unreachable = true;
28
+ throw e;
29
+ }
30
+ if (res.ok) return res;
31
+ const retryable = res.status === 429 || res.status >= 500;
32
+ if (retryable && attempt < retries) {
33
+ await res.text().catch(() => {});
34
+ // Honor Retry-After (seconds or a date) when the server sends one.
35
+ const ra = res.headers.get('retry-after');
36
+ const raMs = ra ? (Number.isFinite(Number(ra)) ? Number(ra) * 1000 : Date.parse(ra) - Date.now()) : NaN;
37
+ await sleep(raMs > 0 && raMs <= 60000 ? raMs : 1000 * 2 ** attempt, init.signal);
38
+ continue;
39
+ }
40
+ const body = await res.text().catch(() => '');
41
+ const e = new Error(`API error ${res.status} from ${url}: ${body.slice(0, 500)}`);
42
+ e.status = res.status;
43
+ throw e;
44
+ }
45
+ }
46
+
47
+ function sleep(ms, signal) {
48
+ return new Promise((resolve, reject) => {
49
+ const t = setTimeout(resolve, ms);
50
+ signal?.addEventListener('abort', () => {
51
+ clearTimeout(t);
52
+ reject(signal.reason ?? new DOMException('Aborted', 'AbortError'));
53
+ }, { once: true });
54
+ });
55
+ }
56
+
57
+ export async function* streamChat({ config, messages, tools, signal }) {
58
+ const body = { model: config.model, messages, stream: true };
59
+ if (tools?.length) body.tools = tools;
60
+ if (tools?.length && config.toolChoice === 'none') body.tool_choice = 'none';
61
+ if (config.maxTokens) body.max_tokens = config.maxTokens;
62
+ if (USAGE_PROVIDERS.has(config.provider)) body.stream_options = { include_usage: true };
63
+ const res = await request(config, '/chat/completions', { method: 'POST', body: JSON.stringify(body), signal });
64
+
65
+ const decoder = new TextDecoder();
66
+ let buf = '';
67
+ for await (const chunk of res.body) {
68
+ buf += decoder.decode(chunk, { stream: true });
69
+ let nl;
70
+ while ((nl = buf.indexOf('\n')) >= 0) {
71
+ const line = buf.slice(0, nl).trim();
72
+ buf = buf.slice(nl + 1);
73
+ if (!line.startsWith('data:')) continue;
74
+ const data = line.slice(5).trim();
75
+ if (data === '[DONE]') return;
76
+ let event;
77
+ try {
78
+ event = JSON.parse(data);
79
+ } catch {
80
+ continue;
81
+ }
82
+ if (event.error) throw new Error(`API error: ${event.error.message || JSON.stringify(event.error)}`);
83
+ yield event;
84
+ }
85
+ }
86
+ }
87
+
88
+ // Collect a full text response (used for summaries).
89
+ export async function completeText({ config, messages, signal }) {
90
+ let text = '';
91
+ for await (const event of streamChat({ config, messages, signal })) {
92
+ text += event.choices?.[0]?.delta?.content ?? '';
93
+ }
94
+ return text;
95
+ }
96
+
97
+ // List the chat models the provider offers, newest first when it says.
98
+ export async function listModels(config) {
99
+ if (isNativeAnthropic(config) && config.apiKey) return normalizeModels({ data: await listAnthropicModels(config) });
100
+ const provider = getProvider(config.provider);
101
+ const extraHeaders = provider?.modelsHeaders && config.apiKey ? provider.modelsHeaders(config.apiKey) : undefined;
102
+ const res = await request(config, `/models${provider?.modelsQuery ?? ''}`, { method: 'GET' }, { retries: 1, extraHeaders });
103
+ return normalizeModels(await res.json());
104
+ }
105
+
106
+ export async function resolveModel(config) {
107
+ if (config.model) return config.model;
108
+ const models = await listModels(config);
109
+ if (!models.length) throw new Error(`No model configured and ${config.baseUrl}/models listed none. Pick one with: leto setup`);
110
+ return models[0].id;
111
+ }
package/src/config.js ADDED
@@ -0,0 +1,205 @@
1
+ import './legacy.js';
2
+ import fs from 'node:fs';
3
+ import os from 'node:os';
4
+ import path from 'node:path';
5
+ import { getProvider } from './providers.js';
6
+ import { applyPolicyToConfig } from './policy.js';
7
+
8
+ export const HOME_DIR = process.env.LETO_HOME || path.join(os.homedir(), '.leto');
9
+ export const CONFIG_PATH = path.join(HOME_DIR, 'config.json');
10
+ export const SESSIONS_DIR = path.join(HOME_DIR, 'sessions');
11
+
12
+ // Config file shape:
13
+ // {
14
+ // "provider": "anthropic",
15
+ // "providers": { "anthropic": { "apiKey": "...", "model": "...", "contextWindow": 1000000 } },
16
+ // "maxTokens": 0
17
+ // }
18
+ // Each provider keeps its own key and last-used model, so switching back is instant.
19
+
20
+ export const CONFIG_KEYS = {
21
+ provider: { env: 'LETO_PROVIDER', help: 'Active provider id (see: leto setup)', global: true },
22
+ baseUrl: { env: 'LETO_BASE_URL', help: 'API base URL (custom provider)' },
23
+ apiKey: { env: 'LETO_API_KEY', help: 'API key for the active provider', secret: true },
24
+ model: { env: 'LETO_MODEL', help: 'Model name' },
25
+ contextWindow: { env: 'LETO_CONTEXT_WINDOW', help: 'Context window in tokens; history is compacted near 80%', number: true },
26
+ effort: { env: 'LETO_EFFORT', help: 'Claude effort: low, medium, high, xhigh, max (Anthropic only)' },
27
+ subagentModel: { env: 'LETO_SUBAGENT_MODEL', help: 'Model for sub-agents (e.g. a faster, cheaper one); default: same as the main model', global: true },
28
+ theme: { env: 'LETO_THEME', help: 'Color theme: auto, spice, spice-light, mono', global: true },
29
+ maxTokens: { env: 'LETO_MAX_TOKENS', help: 'Max output tokens per response (0 = provider default)', number: true, global: true },
30
+ toolMode: { env: 'LETO_TOOL_MODE', help: 'native (default) or text: describe tools in the prompt and parse calls from replies, for models without function calling' },
31
+ sandbox: { env: 'LETO_SANDBOX', help: 'on: run shell commands in a sandbox by default (they then run without asking)', global: true },
32
+ sandboxNetwork: { help: 'on: let sandboxed commands use the network', global: true },
33
+ syntaxCheck: { help: 'off: skip parsing edited files for syntax errors', global: true },
34
+ serverCompaction: { help: 'off: let leto summarize long sessions itself instead of Claude doing it server-side', global: true },
35
+ compactTokens: { help: 'Claude server-side compaction: summarize once the input passes this many tokens (default 150000)', number: true, global: true },
36
+ };
37
+
38
+ const DEFAULT_CONTEXT = 128000;
39
+
40
+ export function readConfigFile() {
41
+ let file;
42
+ try {
43
+ file = JSON.parse(fs.readFileSync(CONFIG_PATH, 'utf8'));
44
+ } catch {
45
+ return { providers: {} };
46
+ }
47
+ file.providers ??= {};
48
+ // Migrate the flat 0.2 format ({ baseUrl, apiKey, model }) to a custom provider.
49
+ if (!file.provider && file.baseUrl) {
50
+ file.providers.custom = { baseUrl: file.baseUrl, apiKey: file.apiKey, model: file.model, contextWindow: file.contextWindow };
51
+ file.provider = 'custom';
52
+ }
53
+ delete file.baseUrl;
54
+ delete file.apiKey;
55
+ delete file.model;
56
+ delete file.contextWindow;
57
+ return file;
58
+ }
59
+
60
+ // Change the config file: fn gets the parsed file to modify in place.
61
+ export function writeConfig(fn) {
62
+ const file = readConfigFile();
63
+ fn(file);
64
+ writeConfigFile(file);
65
+ }
66
+
67
+ function writeConfigFile(file) {
68
+ fs.mkdirSync(HOME_DIR, { recursive: true });
69
+ fs.writeFileSync(CONFIG_PATH, JSON.stringify(file, null, 2) + '\n', { mode: 0o600 });
70
+ fs.chmodSync(CONFIG_PATH, 0o600);
71
+ }
72
+
73
+ export function loadConfig(overrides = {}) {
74
+ const file = readConfigFile();
75
+ const env = process.env;
76
+ let providerId = overrides.provider || env.LETO_PROVIDER || file.provider || null;
77
+ // A base URL from the environment or flags without a provider means a custom API.
78
+ if (!providerId && (env.LETO_BASE_URL || overrides.baseUrl)) providerId = 'custom';
79
+ const provider = providerId ? getProvider(providerId) : null;
80
+ if (providerId && !provider) throw new Error(`Unknown provider "${providerId}". Run: leto setup`);
81
+ const saved = (providerId && file.providers[providerId]) || {};
82
+
83
+ const config = {
84
+ provider: providerId,
85
+ providerName: provider?.name ?? '',
86
+ baseUrl: saved.baseUrl || provider?.baseUrl || '',
87
+ apiKey: saved.apiKey || '',
88
+ model: saved.model || '',
89
+ effort: saved.effort || '',
90
+ contextWindow: Number(saved.contextWindow) || provider?.contextWindow || DEFAULT_CONTEXT,
91
+ maxTokens: Number(file.maxTokens) || provider?.maxTokens || 0,
92
+ subagentModel: file.subagentModel || '',
93
+ toolMode: saved.toolMode || provider?.toolMode || 'native',
94
+ syntaxCheck: file.syntaxCheck !== 'off',
95
+ serverCompaction: file.serverCompaction !== 'off',
96
+ compactTokens: Number(file.compactTokens) || 0,
97
+ };
98
+ if (env.LETO_TOOL_MODE) config.toolMode = env.LETO_TOOL_MODE;
99
+ if (env.LETO_SUBAGENT_MODEL) config.subagentModel = env.LETO_SUBAGENT_MODEL;
100
+ if (env.LETO_BASE_URL) config.baseUrl = env.LETO_BASE_URL;
101
+ if (env.LETO_API_KEY) config.apiKey = env.LETO_API_KEY;
102
+ if (env.LETO_MODEL) config.model = env.LETO_MODEL;
103
+ if (env.LETO_EFFORT) config.effort = env.LETO_EFFORT;
104
+ if (Number(env.LETO_CONTEXT_WINDOW)) config.contextWindow = Number(env.LETO_CONTEXT_WINDOW);
105
+ if (Number(env.LETO_MAX_TOKENS)) config.maxTokens = Number(env.LETO_MAX_TOKENS);
106
+ if (overrides.baseUrl) config.baseUrl = overrides.baseUrl;
107
+ if (overrides.model) config.model = overrides.model;
108
+ config.baseUrl = String(config.baseUrl).replace(/\/+$/, '');
109
+ config.configured = Boolean(config.provider && config.baseUrl && (config.apiKey || provider?.noKey || provider?.custom || env.LETO_BASE_URL));
110
+ return applyPolicyToConfig(config);
111
+ }
112
+
113
+ // Save settings for one provider and (by default) make it the active one.
114
+ export function saveProvider(providerId, patch, { activate = true } = {}) {
115
+ const file = readConfigFile();
116
+ const current = file.providers[providerId] ?? {};
117
+ const next = { ...current, ...patch };
118
+ for (const k of Object.keys(next)) if (next[k] === undefined || next[k] === '') delete next[k];
119
+ file.providers[providerId] = next;
120
+ if (activate) file.provider = providerId;
121
+ writeConfigFile(file);
122
+ }
123
+
124
+ export function savedProviderSettings(providerId) {
125
+ return readConfigFile().providers[providerId] ?? {};
126
+ }
127
+
128
+ // `leto config set <key> <value>`
129
+ export function setConfigValue(key, value) {
130
+ const spec = CONFIG_KEYS[key];
131
+ if (!spec) throw new Error(`Unknown config key "${key}". Keys: ${Object.keys(CONFIG_KEYS).join(', ')}`);
132
+ const file = readConfigFile();
133
+ const v = value === undefined || value === '' ? undefined : spec.number ? Number(value) : value;
134
+ if (key === 'provider') {
135
+ if (v && !getProvider(v)) throw new Error(`Unknown provider "${v}".`);
136
+ if (v) file.provider = v;
137
+ else delete file.provider;
138
+ } else if (spec.global) {
139
+ if (v === undefined) delete file[key];
140
+ else file[key] = v;
141
+ } else {
142
+ const id = file.provider ?? 'custom';
143
+ file.provider = id;
144
+ file.providers[id] ??= {};
145
+ if (v === undefined) delete file.providers[id][key];
146
+ else file.providers[id][key] = v;
147
+ }
148
+ writeConfigFile(file);
149
+ }
150
+
151
+ export function removeProviderKeys() {
152
+ const file = readConfigFile();
153
+ for (const p of Object.values(file.providers)) delete p.apiKey;
154
+ writeConfigFile(file);
155
+ }
156
+
157
+ export function maskSecret(value) {
158
+ if (!value) return '(not set)';
159
+ return value.length <= 10 ? '****' : `${value.slice(0, 6)}…${value.slice(-4)}`;
160
+ }
161
+
162
+ // Projects whose own MCP servers and hooks the user has allowed to run.
163
+ export function isTrustedProject(dir) {
164
+ return (readConfigFile().trustedProjects ?? []).includes(path.resolve(dir));
165
+ }
166
+
167
+ export function trustProject(dir) {
168
+ const file = readConfigFile();
169
+ file.trustedProjects = [...new Set([...(file.trustedProjects ?? []), path.resolve(dir)])];
170
+ writeConfigFile(file);
171
+ }
172
+
173
+ // The check command (typecheck, lint, tests) chosen for each project.
174
+ export function projectCheck(dir) {
175
+ return readConfigFile().projectChecks?.[path.resolve(dir)] ?? null;
176
+ }
177
+
178
+ export function saveProjectCheck(dir, command) {
179
+ const file = readConfigFile();
180
+ file.projectChecks ??= {};
181
+ if (command) file.projectChecks[path.resolve(dir)] = command;
182
+ else delete file.projectChecks[path.resolve(dir)];
183
+ writeConfigFile(file);
184
+ }
185
+
186
+ // Shell commands the user said to always allow, per project folder.
187
+ export function projectRules(dir) {
188
+ return readConfigFile().projectPermissions?.[path.resolve(dir)] ?? [];
189
+ }
190
+
191
+ export function saveProjectRule(dir, rule) {
192
+ const file = readConfigFile();
193
+ const key = path.resolve(dir);
194
+ file.projectPermissions ??= {};
195
+ file.projectPermissions[key] = [...new Set([...(file.projectPermissions[key] ?? []), rule])];
196
+ writeConfigFile(file);
197
+ }
198
+
199
+ export function removeProjectRule(dir, rule) {
200
+ const file = readConfigFile();
201
+ const key = path.resolve(dir);
202
+ if (!file.projectPermissions?.[key]) return;
203
+ file.projectPermissions[key] = file.projectPermissions[key].filter((r) => r !== rule);
204
+ writeConfigFile(file);
205
+ }
@@ -0,0 +1,198 @@
1
+ // PDFs and Jupyter notebooks.
2
+ //
3
+ // PDFs: text comes from pdftotext (poppler) when it is installed, otherwise
4
+ // from a small built-in extractor that handles ordinary text PDFs. On Claude
5
+ // the PDF itself is attached too, so Claude also sees layout, tables, charts
6
+ // and scanned pages.
7
+ //
8
+ // Notebooks: read_file shows each cell with its number, type, source and
9
+ // outputs (images in outputs are attached); notebook_edit changes cells.
10
+ import fs from 'node:fs';
11
+ import path from 'node:path';
12
+ import zlib from 'node:zlib';
13
+ import { spawnSync } from 'node:child_process';
14
+
15
+ let hasPdftotext;
16
+ function pdftotext(file, first, last) {
17
+ hasPdftotext ??= !spawnSync('pdftotext', ['-v'], { stdio: 'ignore' }).error;
18
+ if (!hasPdftotext) return null;
19
+ const args = ['-layout', '-enc', 'UTF-8'];
20
+ if (first) args.push('-f', String(first));
21
+ if (last) args.push('-l', String(last));
22
+ const r = spawnSync('pdftotext', [...args, file, '-'], { encoding: 'utf8', maxBuffer: 64 * 1024 * 1024, timeout: 60000 });
23
+ return r.status === 0 ? r.stdout : null;
24
+ }
25
+
26
+ function decodePdfString(s) {
27
+ return s.replace(/\\([nrtbf()\\]|[0-7]{1,3})/g, (_, e) => ({ n: '\n', r: '\r', t: '\t', b: '\b', f: '\f', '(': '(', ')': ')', '\\': '\\' })[e] ?? String.fromCharCode(parseInt(e, 8)));
28
+ }
29
+
30
+ function hexString(h) {
31
+ const clean = h.replace(/\s+/g, '');
32
+ let out = '';
33
+ // UTF-16BE with BOM, else single bytes.
34
+ if (/^feff/i.test(clean)) {
35
+ for (let i = 4; i + 3 < clean.length; i += 4) out += String.fromCharCode(parseInt(clean.slice(i, i + 4), 16));
36
+ } else for (let i = 0; i + 1 < clean.length; i += 2) out += String.fromCharCode(parseInt(clean.slice(i, i + 2), 16));
37
+ return out;
38
+ }
39
+
40
+ // Text from the content streams of a simple PDF. Returns pages of text.
41
+ export function extractPdfText(buf) {
42
+ const raw = buf.toString('latin1');
43
+ const pages = [];
44
+ const re = /<<([\s\S]*?)>>\s*stream\r?\n/g;
45
+ let m;
46
+ while ((m = re.exec(raw))) {
47
+ const dict = m[1];
48
+ const start = m.index + m[0].length;
49
+ const end = raw.indexOf('endstream', start);
50
+ if (end < 0) break;
51
+ re.lastIndex = end;
52
+ if (/\/Subtype\s*\/(Image|XML)|\/Type\s*\/(XObject|Metadata|XRef|ObjStm)|\/Length1|\/FontFile/.test(dict)) continue;
53
+ let data = buf.subarray(start, end);
54
+ if (/\/FlateDecode/.test(dict)) {
55
+ try {
56
+ data = zlib.inflateSync(data);
57
+ } catch {
58
+ try {
59
+ data = zlib.inflateSync(data, { finishFlush: zlib.constants.Z_SYNC_FLUSH });
60
+ } catch {
61
+ continue;
62
+ }
63
+ }
64
+ } else if (/\/Filter/.test(dict)) continue;
65
+ const content = data.toString('latin1');
66
+ if (!/\bBT\b/.test(content)) continue;
67
+ let text = '';
68
+ for (const block of content.match(/BT[\s\S]*?ET/g) ?? []) {
69
+ const ops = block.matchAll(/\[((?:\((?:\\.|[^\\)])*\)|<[0-9a-fA-F\s]*>|[^\]])*)\]\s*TJ|\(((?:\\.|[^\\)])*)\)\s*(?:Tj|'|")|<([0-9a-fA-F\s]*)>\s*Tj|(T\*|Td|TD|Tm)\b/g);
70
+ for (const op of ops) {
71
+ if (op[1] !== undefined) {
72
+ for (const part of op[1].matchAll(/\(((?:\\.|[^\\)])*)\)|<([0-9a-fA-F\s]*)>|(-?\d+(?:\.\d+)?)/g)) {
73
+ if (part[1] !== undefined) text += decodePdfString(part[1]);
74
+ else if (part[2] !== undefined) text += hexString(part[2]);
75
+ else if (Number(part[3]) < -200) text += ' ';
76
+ }
77
+ } else if (op[2] !== undefined) text += decodePdfString(op[2]);
78
+ else if (op[3] !== undefined) text += hexString(op[3]);
79
+ else if (op[4]) text += op[4] === 'Tm' ? ' ' : '\n';
80
+ }
81
+ text += '\n';
82
+ }
83
+ const clean = text.replace(/[^\S\n]+/g, ' ').replace(/\n\s*\n+/g, '\n').trim();
84
+ if (clean) pages.push(clean);
85
+ }
86
+ return pages;
87
+ }
88
+
89
+ // Mostly printable text? (Custom-encoded fonts give gibberish.)
90
+ const readable = (t) => t.length > 0 && (t.match(/[\p{L}\p{N}\s.,;:!?'"()\-]/gu)?.length ?? 0) / t.length > 0.85;
91
+
92
+ export function readPdf(file, { pages: range, native = false } = {}) {
93
+ const stat = fs.statSync(file);
94
+ const buf = fs.readFileSync(file);
95
+ const count = (buf.toString('latin1').match(/\/Type\s*\/Page(?!s)/g) ?? []).length || null;
96
+ let first;
97
+ let last;
98
+ if (range) {
99
+ const m = String(range).match(/^(\d+)(?:\s*-\s*(\d+))?$/);
100
+ if (!m) throw new Error('pages must look like "3" or "2-5".');
101
+ first = Number(m[1]);
102
+ last = Number(m[2] ?? m[1]);
103
+ }
104
+ let text = pdftotext(file, first, last);
105
+ let how = 'pdftotext';
106
+ if (text == null) {
107
+ let pages = extractPdfText(buf);
108
+ if (first) pages = pages.slice(first - 1, last);
109
+ text = pages.join('\n\n');
110
+ how = 'built-in extractor';
111
+ }
112
+ text = text.trim();
113
+ const ok = readable(text.slice(0, 4000));
114
+ const kb = Math.round(stat.size / 1024);
115
+ const head = `PDF ${path.basename(file)} (${count ? `${count} pages, ` : ''}${kb} KB${range ? `, pages ${range}` : ''}).`;
116
+ // Claude reads PDFs natively (up to 32 MB); attach the file so it sees everything.
117
+ const attach = native && stat.size <= 30 * 1024 * 1024 && !range;
118
+ let body;
119
+ if (ok && text) body = `${head} Text (via ${how}):\n\n${text}`;
120
+ else if (attach) body = `${head} Its text could not be extracted locally (scanned or unusual fonts); the PDF is attached so you can read it directly.`;
121
+ else body = `${head} No readable text could be extracted (it may be scanned images). Install poppler (pdftotext) for better extraction${spawnSync('which', ['pdftoppm'], { stdio: 'ignore' }).status === 0 ? ', or render pages to PNG with pdftoppm -png and read those' : ''}.`;
122
+ return {
123
+ content: body,
124
+ display: `pdf · ${count ? `${count} pages · ` : ''}${ok ? `${text.length.toLocaleString()} characters` : 'no text layer'}${attach ? ' · attached' : ''}`,
125
+ documents: attach ? [`data:application/pdf;base64,${buf.toString('base64')}`] : undefined,
126
+ };
127
+ }
128
+
129
+ // --- Notebooks -----------------------------------------------------------------
130
+
131
+ const src = (s) => (Array.isArray(s) ? s.join('') : String(s ?? ''));
132
+
133
+ export function readNotebook(file) {
134
+ const nb = JSON.parse(fs.readFileSync(file, 'utf8'));
135
+ const cells = nb.cells ?? [];
136
+ const lang = nb.metadata?.kernelspec?.language || nb.metadata?.language_info?.name || 'python';
137
+ const images = [];
138
+ const parts = cells.map((c, i) => {
139
+ let s = `<cell index="${i}" type="${c.cell_type}"${c.id ? ` id="${c.id}"` : ''}>\n${src(c.source)}\n</cell>`;
140
+ const outs = [];
141
+ for (const o of c.outputs ?? []) {
142
+ if (o.output_type === 'stream') outs.push(src(o.text));
143
+ else if (o.output_type === 'error') outs.push(`${o.ename}: ${o.evalue}`);
144
+ else if (o.data) {
145
+ if (o.data['text/plain']) outs.push(src(o.data['text/plain']));
146
+ for (const mime of ['image/png', 'image/jpeg']) {
147
+ if (o.data[mime] && images.length < 8) {
148
+ images.push(`data:${mime};base64,${src(o.data[mime]).replace(/\s+/g, '')}`);
149
+ outs.push(`[image output ${images.length} attached]`);
150
+ }
151
+ }
152
+ }
153
+ }
154
+ if (outs.length) s += `\n<output index="${i}">\n${outs.join('\n').slice(0, 4000)}\n</output>`;
155
+ return s;
156
+ });
157
+ return {
158
+ content: `Notebook ${path.basename(file)} (${cells.length} cells, ${lang}). Edit cells with notebook_edit using the cell index.\n\n${parts.join('\n\n')}`,
159
+ display: `notebook · ${cells.length} cells${images.length ? ` · ${images.length} images` : ''}`,
160
+ images: images.length ? images : undefined,
161
+ };
162
+ }
163
+
164
+ export function editNotebook(file, { cell_index, new_source = '', cell_type, edit_mode = 'replace' }) {
165
+ const raw = fs.readFileSync(file, 'utf8');
166
+ const nb = JSON.parse(raw);
167
+ nb.cells ??= [];
168
+ const n = nb.cells.length;
169
+ const i = Number(cell_index);
170
+ if (!Number.isInteger(i) || i < 0 || i > n || (edit_mode !== 'insert' && i >= n)) throw new Error(`cell_index ${cell_index} is out of range (the notebook has ${n} cells${edit_mode === 'insert' ? `; insert accepts 0-${n}` : ''}).`);
171
+ const toSource = (s) => s.split(/(?<=\n)/);
172
+ if (edit_mode === 'delete') nb.cells.splice(i, 1);
173
+ else if (edit_mode === 'insert') {
174
+ const type = cell_type || 'code';
175
+ const cell = { cell_type: type, metadata: {}, source: toSource(new_source) };
176
+ if (type === 'code') Object.assign(cell, { execution_count: null, outputs: [] });
177
+ if (nb.nbformat >= 4 && nb.nbformat_minor >= 5) cell.id = Math.random().toString(36).slice(2, 10);
178
+ nb.cells.splice(i, 0, cell);
179
+ } else {
180
+ const cell = nb.cells[i];
181
+ cell.source = toSource(new_source);
182
+ if (cell_type && cell_type !== cell.cell_type) {
183
+ cell.cell_type = cell_type;
184
+ if (cell_type === 'code') Object.assign(cell, { execution_count: null, outputs: [] });
185
+ else {
186
+ delete cell.outputs;
187
+ delete cell.execution_count;
188
+ }
189
+ } else if (cell.cell_type === 'code') {
190
+ // The old outputs no longer match the new code.
191
+ cell.outputs = [];
192
+ cell.execution_count = null;
193
+ }
194
+ }
195
+ const indent = raw.match(/^\{\n( +)/)?.[1]?.length ?? 1;
196
+ fs.writeFileSync(file, JSON.stringify(nb, null, indent) + '\n');
197
+ return { n: nb.cells.length };
198
+ }