@sontoriyama/mcp-code-mode 0.0.0-stage → 0.4.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.
- package/CHANGELOG.md +148 -0
- package/LICENSE +21 -0
- package/README.md +207 -3
- package/SKILL.md +42 -0
- package/docs/pig.md +131 -0
- package/examples/codemode.tools.json +23 -0
- package/examples/pr-status.program.mjs +64 -0
- package/package.json +60 -6
- package/skills/pig/SKILL.md +48 -0
- package/src/core.mjs +135 -0
- package/src/executor.mjs +447 -0
- package/src/manifest.mjs +154 -0
- package/src/mcp-client.mjs +891 -0
- package/src/mcp-server.mjs +593 -0
- package/src/plugins/engram.mjs +32 -0
- package/src/plugins/gh.mjs +83 -0
- package/src/run.mjs +347 -0
- package/src/tools.mjs +136 -0
package/package.json
CHANGED
|
@@ -1,6 +1,60 @@
|
|
|
1
|
-
{
|
|
2
|
-
"name": "@sontoriyama/mcp-code-mode",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
1
|
+
{
|
|
2
|
+
"name": "@sontoriyama/mcp-code-mode",
|
|
3
|
+
"version": "0.4.0",
|
|
4
|
+
"description": "Zero-dependency local Code Mode runner for MCP servers and CLIs: inline/stdin/file execution, lazy stdio MCP bridge, progressive tool discovery, bounded output, and disk spill.",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"license": "MIT",
|
|
7
|
+
"author": {
|
|
8
|
+
"name": "sontoriyama",
|
|
9
|
+
"url": "https://github.com/sontoriyama"
|
|
10
|
+
},
|
|
11
|
+
"homepage": "https://github.com/sontoriyama/agent-maxicodemode#readme",
|
|
12
|
+
"repository": {
|
|
13
|
+
"type": "git",
|
|
14
|
+
"url": "git+https://github.com/sontoriyama/agent-maxicodemode.git"
|
|
15
|
+
},
|
|
16
|
+
"bugs": {
|
|
17
|
+
"url": "https://github.com/sontoriyama/agent-maxicodemode/issues"
|
|
18
|
+
},
|
|
19
|
+
"engines": {
|
|
20
|
+
"node": ">=20.0.0"
|
|
21
|
+
},
|
|
22
|
+
"files": [
|
|
23
|
+
"src/",
|
|
24
|
+
"examples/",
|
|
25
|
+
"docs/",
|
|
26
|
+
"skills/",
|
|
27
|
+
"SKILL.md",
|
|
28
|
+
"README.md",
|
|
29
|
+
"CHANGELOG.md",
|
|
30
|
+
"LICENSE"
|
|
31
|
+
],
|
|
32
|
+
"bin": {
|
|
33
|
+
"mcp-code-mode": "src/run.mjs"
|
|
34
|
+
},
|
|
35
|
+
"exports": {
|
|
36
|
+
".": "./src/tools.mjs",
|
|
37
|
+
"./run": "./src/run.mjs",
|
|
38
|
+
"./manifest": "./src/manifest.mjs",
|
|
39
|
+
"./mcp": "./src/mcp-client.mjs",
|
|
40
|
+
"./plugins/gh": "./src/plugins/gh.mjs",
|
|
41
|
+
"./plugins/engram": "./src/plugins/engram.mjs"
|
|
42
|
+
},
|
|
43
|
+
"scripts": {
|
|
44
|
+
"test": "node --test test/codemode.test.mjs test/mcp-client.test.mjs test/mcp-server.test.mjs",
|
|
45
|
+
"prepublishOnly": "npm test"
|
|
46
|
+
},
|
|
47
|
+
"publishConfig": {
|
|
48
|
+
"access": "public"
|
|
49
|
+
},
|
|
50
|
+
"keywords": [
|
|
51
|
+
"ai-agents",
|
|
52
|
+
"code-mode",
|
|
53
|
+
"mcp",
|
|
54
|
+
"cli",
|
|
55
|
+
"batching",
|
|
56
|
+
"context-optimization",
|
|
57
|
+
"llm",
|
|
58
|
+
"agent-tools"
|
|
59
|
+
]
|
|
60
|
+
}
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: mcp-code-mode-pig
|
|
3
|
+
description: Batch many read-only MCP/CLI queries into one turn on PiG. Trigger: 4+ homogeneous reads (PRs, issues, memory, files), fan-out with a concurrency cap, or filtering a huge payload before it reaches the model. Use PiG's native codemode tool, not the Node runner; the runner is a fallback for five listed cases.
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
# Code mode on PiG
|
|
7
|
+
|
|
8
|
+
PiG has code mode built in: the `codemode` tool runs JavaScript in QuickJS/WASM inside the `pig`
|
|
9
|
+
process. No Node.js, no sidecar, no `mcp-config`. Use it.
|
|
10
|
+
|
|
11
|
+
## Do this
|
|
12
|
+
|
|
13
|
+
1. **One script instead of N tool calls.** Everything the session can call is on `tools`:
|
|
14
|
+
`tools.bash({ command })`, `tools.read({ path })`, `tools.edit({...})`,
|
|
15
|
+
`tools.mcp__<server>__<tool>({...})` (double underscore).
|
|
16
|
+
2. **Fan out with `Promise.allSettled([...])`.** There is no `mapBounded` here. Do it only for
|
|
17
|
+
read-only calls; writes and anything with an external effect stay in their own visible tool call.
|
|
18
|
+
3. **Return a summary, never a payload.** Counts, statuses, short excerpts. The model sees the
|
|
19
|
+
script's output, not the tool results.
|
|
20
|
+
4. **Cap the output** when it can be large, on the first line of the script:
|
|
21
|
+
`// @options: {"max_output_tokens": 2000, "timeout_ms": 60000}`. The full text goes to a temp
|
|
22
|
+
file whose path the result names; re-filter it later with `tools.read({ path })`.
|
|
23
|
+
5. **Find tools you were not given:** `searchTools(query)`, `describeTool(name)`, `ALL_TOOLS`.
|
|
24
|
+
Do not guess names; a wrong member throws with close matches.
|
|
25
|
+
6. **Keep state between scripts** with `store(key, value)` / `load(key)` — IDs, cursors, summaries.
|
|
26
|
+
Never store image data.
|
|
27
|
+
7. **Docs in the repo:** `pig docs path` → `codemode.md`.
|
|
28
|
+
|
|
29
|
+
## Do not
|
|
30
|
+
|
|
31
|
+
- Do not install or invoke the Node runner (`node .../agent-maxicodemode/src/run.mjs`) by habit.
|
|
32
|
+
It exists for harnesses without native code mode.
|
|
33
|
+
- Do not use the script for 1–2 queries; a direct tool call is clearer and cheaper.
|
|
34
|
+
- Do not use it for writes, pushes, comments or deletes. The script is sandboxed, but `tools.bash`
|
|
35
|
+
runs on the host with your privileges.
|
|
36
|
+
- Do not print raw JSON at volume; the point is to filter it here, not in the context window.
|
|
37
|
+
|
|
38
|
+
## The only cases where the Node runner is still right
|
|
39
|
+
|
|
40
|
+
`node <repo>/src/run.mjs` — for PiG sessions, only when:
|
|
41
|
+
|
|
42
|
+
1. the program needs Node APIs (`fs`, `net`, `crypto`, `timers`, `node_modules`);
|
|
43
|
+
2. you need a declarative `--manifest` with typed validation instead of a shell command string;
|
|
44
|
+
3. the spill must live at a stable path inside the repo (`.agent/out/`) instead of a temp file;
|
|
45
|
+
4. the same `.mjs` program must run unchanged in Claude Code, Codex or Command Code;
|
|
46
|
+
5. you need `--list-tools` as a committed, diffable catalog.
|
|
47
|
+
|
|
48
|
+
Full comparison and verification recipe: `docs/pig.md` in that repository.
|
package/src/core.mjs
ADDED
|
@@ -0,0 +1,135 @@
|
|
|
1
|
+
// Core runtime primitives for local code-mode programs.
|
|
2
|
+
import { execFile } from 'node:child_process';
|
|
3
|
+
import { promisify } from 'node:util';
|
|
4
|
+
|
|
5
|
+
const execFileAsync = promisify(execFile);
|
|
6
|
+
|
|
7
|
+
export const REPO_RE = /^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/;
|
|
8
|
+
export const SAFE_TOKEN_RE = /^(?!-)[A-Za-z0-9_.-]+$/;
|
|
9
|
+
|
|
10
|
+
export class ToolCallError extends Error {
|
|
11
|
+
constructor(toolName, message) {
|
|
12
|
+
super(message);
|
|
13
|
+
this.name = 'ToolCallError';
|
|
14
|
+
this.toolName = toolName;
|
|
15
|
+
}
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
// A per-call signal (e.g. mapBounded's item signal) must not shadow the run's
|
|
19
|
+
// signal, or a timeout would stop cancelling that call.
|
|
20
|
+
export function mergeSignals(primary, secondary) {
|
|
21
|
+
if (!primary) return secondary;
|
|
22
|
+
if (!secondary || primary === secondary) return primary;
|
|
23
|
+
if (typeof AbortSignal.any === 'function') return AbortSignal.any([primary, secondary]);
|
|
24
|
+
const controller = new AbortController();
|
|
25
|
+
const abort = () => controller.abort(primary.aborted ? primary.reason : secondary.reason);
|
|
26
|
+
if (primary.aborted || secondary.aborted) {
|
|
27
|
+
abort();
|
|
28
|
+
return controller.signal;
|
|
29
|
+
}
|
|
30
|
+
primary.addEventListener('abort', abort, { once: true });
|
|
31
|
+
secondary.addEventListener('abort', abort, { once: true });
|
|
32
|
+
return controller.signal;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export function assertPositiveInt(toolName, field, value) {
|
|
36
|
+
const n = Number(value);
|
|
37
|
+
if (!Number.isInteger(n) || n <= 0) {
|
|
38
|
+
throw new ToolCallError(toolName, `${field} must be a positive integer`);
|
|
39
|
+
}
|
|
40
|
+
return n;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export function assertRepo(toolName, repo) {
|
|
44
|
+
if (typeof repo !== 'string' || !REPO_RE.test(repo) || repo.startsWith('-')) {
|
|
45
|
+
throw new ToolCallError(toolName, 'repo must be a valid owner/name string');
|
|
46
|
+
}
|
|
47
|
+
return repo;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
export function assertFields(toolName, fields) {
|
|
51
|
+
if (
|
|
52
|
+
!Array.isArray(fields)
|
|
53
|
+
|| fields.length === 0
|
|
54
|
+
|| !fields.every((f) => typeof f === 'string' && SAFE_TOKEN_RE.test(f))
|
|
55
|
+
) {
|
|
56
|
+
throw new ToolCallError(toolName, 'fields must be a non-empty array of field names');
|
|
57
|
+
}
|
|
58
|
+
return fields;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
function extractErrorDetail(err, cmd) {
|
|
62
|
+
const candidates = [err?.stderr, err?.stdout, err?.message];
|
|
63
|
+
let detail = '';
|
|
64
|
+
for (const c of candidates) {
|
|
65
|
+
if (typeof c === 'string' && c.trim().length > 0) {
|
|
66
|
+
detail = c.trim().split(/\r?\n/).pop() || '';
|
|
67
|
+
if (detail) break;
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
const meta = [];
|
|
71
|
+
if (err?.killed && err?.signal) meta.push(`killed:${err.signal}`);
|
|
72
|
+
if (err?.code !== undefined && err?.code !== null) meta.push(`code:${err.code}`);
|
|
73
|
+
const suffix = meta.length > 0 ? ` (${meta.join(', ')})` : '';
|
|
74
|
+
return (detail || `${cmd} failed`) + suffix;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
export async function execTool(toolName, cmd, args, { timeout = 180000, signal } = {}) {
|
|
78
|
+
try {
|
|
79
|
+
const { stdout } = await execFileAsync(cmd, args, {
|
|
80
|
+
encoding: 'utf8',
|
|
81
|
+
maxBuffer: 64 * 1024 * 1024,
|
|
82
|
+
timeout,
|
|
83
|
+
signal,
|
|
84
|
+
windowsHide: true,
|
|
85
|
+
});
|
|
86
|
+
return stdout;
|
|
87
|
+
} catch (e) {
|
|
88
|
+
throw new ToolCallError(toolName, extractErrorDetail(e, cmd));
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
export async function execJson(toolName, cmd, args, opts) {
|
|
93
|
+
const out = await execTool(toolName, cmd, args, opts);
|
|
94
|
+
try {
|
|
95
|
+
return JSON.parse(out);
|
|
96
|
+
} catch {
|
|
97
|
+
throw new ToolCallError(toolName, `invalid JSON from ${cmd}`);
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
export const MAX_CONCURRENCY = 16;
|
|
102
|
+
|
|
103
|
+
export function clampConcurrency(concurrency, fallback = 4) {
|
|
104
|
+
if (concurrency === undefined || concurrency === null) return fallback;
|
|
105
|
+
const n = Number(concurrency);
|
|
106
|
+
if (n === Infinity) return MAX_CONCURRENCY;
|
|
107
|
+
if (!Number.isFinite(n) || n < 1) return 1;
|
|
108
|
+
return Math.min(Math.floor(n), MAX_CONCURRENCY);
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
export async function mapBounded(items, concurrency, fn) {
|
|
112
|
+
if (!Array.isArray(items)) {
|
|
113
|
+
throw new TypeError('mapBounded: items must be an array');
|
|
114
|
+
}
|
|
115
|
+
const limit = clampConcurrency(concurrency, 4);
|
|
116
|
+
const results = new Array(items.length);
|
|
117
|
+
const controller = new AbortController();
|
|
118
|
+
let next = 0;
|
|
119
|
+
|
|
120
|
+
async function worker() {
|
|
121
|
+
while (next < items.length && !controller.signal.aborted) {
|
|
122
|
+
const idx = next++;
|
|
123
|
+
try {
|
|
124
|
+
results[idx] = await fn(items[idx], idx, controller.signal);
|
|
125
|
+
} catch (err) {
|
|
126
|
+
if (!controller.signal.aborted) controller.abort(err);
|
|
127
|
+
throw err;
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
const workers = Array.from({ length: Math.min(limit, items.length) }, () => worker());
|
|
133
|
+
await Promise.all(workers);
|
|
134
|
+
return results;
|
|
135
|
+
}
|
package/src/executor.mjs
ADDED
|
@@ -0,0 +1,447 @@
|
|
|
1
|
+
// Shared execution core: own the console capture, spill envelope and optional
|
|
2
|
+
// timeout/abort so the CLI front-end (run.mjs) and the MCP front-end
|
|
3
|
+
// (mcp-server.mjs) run exactly the same program semantics.
|
|
4
|
+
import { randomBytes } from 'node:crypto';
|
|
5
|
+
import { closeSync, fstatSync, lstatSync, mkdirSync, openSync, readdirSync, readFileSync, readSync, realpathSync, writeFileSync } from 'node:fs';
|
|
6
|
+
import { isAbsolute, relative, resolve, sep } from 'node:path';
|
|
7
|
+
import { pathToFileURL } from 'node:url';
|
|
8
|
+
import { StringDecoder } from 'node:string_decoder';
|
|
9
|
+
import { inspect } from 'node:util';
|
|
10
|
+
import { execJson, execTool, mapBounded, ToolCallError } from './tools.mjs';
|
|
11
|
+
|
|
12
|
+
export const DEFAULT_MAX_CHARS = 32000;
|
|
13
|
+
|
|
14
|
+
const AsyncFunction = Object.getPrototypeOf(async function () {}).constructor;
|
|
15
|
+
const MODULE_SYNTAX_RE = /cannot use import statement outside a module|unexpected token 'export'|cannot use 'import\.meta' outside a module/i;
|
|
16
|
+
|
|
17
|
+
export function parseMaxChars(raw = process.env.CODEMODE_MAX_OUTPUT_CHARS) {
|
|
18
|
+
if (raw === undefined || raw === null || String(raw).trim() === '') {
|
|
19
|
+
return DEFAULT_MAX_CHARS;
|
|
20
|
+
}
|
|
21
|
+
const n = Number(raw);
|
|
22
|
+
return Number.isFinite(n) && n >= 1 ? Math.floor(n) : DEFAULT_MAX_CHARS;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export function safeJsonStringify(value, space = 0) {
|
|
26
|
+
const ancestors = [];
|
|
27
|
+
return JSON.stringify(
|
|
28
|
+
value,
|
|
29
|
+
function (_key, v) {
|
|
30
|
+
if (typeof v === 'bigint') return `${v.toString()}n`;
|
|
31
|
+
if (typeof v !== 'object' || v === null) return v;
|
|
32
|
+
while (ancestors.length > 0 && ancestors.at(-1) !== this) ancestors.pop();
|
|
33
|
+
if (ancestors.includes(v)) return '[Circular]';
|
|
34
|
+
ancestors.push(v);
|
|
35
|
+
return v;
|
|
36
|
+
},
|
|
37
|
+
space,
|
|
38
|
+
);
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
export function boundOutput(text, maxChars = parseMaxChars()) {
|
|
42
|
+
const limit = parseMaxChars(maxChars);
|
|
43
|
+
if (text.length <= limit) return { text, truncated: false };
|
|
44
|
+
const marker = '\n… code mode output truncated …\n';
|
|
45
|
+
if (limit <= marker.length) {
|
|
46
|
+
return { text: text.slice(0, limit), truncated: true };
|
|
47
|
+
}
|
|
48
|
+
const head = Math.ceil((limit - marker.length) / 2);
|
|
49
|
+
const tail = limit - marker.length - head;
|
|
50
|
+
return {
|
|
51
|
+
text: text.slice(0, head) + marker + (tail > 0 ? text.slice(-tail) : ''),
|
|
52
|
+
truncated: true,
|
|
53
|
+
};
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
function formatLogPart(part) {
|
|
57
|
+
if (typeof part === 'string') return part;
|
|
58
|
+
try {
|
|
59
|
+
return safeJsonStringify(part) ?? String(part);
|
|
60
|
+
} catch {
|
|
61
|
+
return inspect(part, { depth: 4, breakLength: Infinity });
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
export function normalizeError(err) {
|
|
66
|
+
if (err instanceof ToolCallError) {
|
|
67
|
+
return { kind: 'tool-call', toolName: err.toolName, message: err.message };
|
|
68
|
+
}
|
|
69
|
+
if (err instanceof Error) {
|
|
70
|
+
return { kind: 'exception', message: err.message };
|
|
71
|
+
}
|
|
72
|
+
return { kind: 'exception', message: formatLogPart(err) };
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
function isInsideDir(baseReal, candidateReal) {
|
|
76
|
+
const rel = relative(baseReal, candidateReal);
|
|
77
|
+
return rel !== ''
|
|
78
|
+
&& rel !== '.'
|
|
79
|
+
&& rel !== '..'
|
|
80
|
+
&& !rel.startsWith(`..${sep}`)
|
|
81
|
+
&& !isAbsolute(rel);
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
function isFailedSpillHeader(filePath) {
|
|
85
|
+
let fd;
|
|
86
|
+
try {
|
|
87
|
+
fd = openSync(filePath, 'r');
|
|
88
|
+
if (!fstatSync(fd).isFile()) return true;
|
|
89
|
+
const buf = Buffer.allocUnsafe(1024);
|
|
90
|
+
const bytes = readSync(fd, buf, 0, buf.length, 0);
|
|
91
|
+
const head = buf.subarray(0, bytes).toString('utf8');
|
|
92
|
+
return /"ok"\s*:\s*false\b/.test(head);
|
|
93
|
+
} catch {
|
|
94
|
+
return true;
|
|
95
|
+
} finally {
|
|
96
|
+
if (fd !== undefined) {
|
|
97
|
+
try { closeSync(fd); } catch {}
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
function resolveSpillTarget(baseDir, nameOrPath) {
|
|
103
|
+
let baseReal;
|
|
104
|
+
try {
|
|
105
|
+
baseReal = realpathSync(baseDir);
|
|
106
|
+
} catch (err) {
|
|
107
|
+
if ((err?.code === 'ENOENT' || err?.code === 'ENOTDIR') && !nameOrPath) {
|
|
108
|
+
throw new Error('no spill files found in output directory');
|
|
109
|
+
}
|
|
110
|
+
throw err;
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
if (!nameOrPath) {
|
|
114
|
+
let entries;
|
|
115
|
+
try {
|
|
116
|
+
entries = readdirSync(baseReal);
|
|
117
|
+
} catch (err) {
|
|
118
|
+
if (err?.code === 'ENOENT') {
|
|
119
|
+
throw new Error('no spill files found in output directory');
|
|
120
|
+
}
|
|
121
|
+
throw err;
|
|
122
|
+
}
|
|
123
|
+
const files = [];
|
|
124
|
+
for (const entry of entries) {
|
|
125
|
+
if (!entry.endsWith('.json')) continue;
|
|
126
|
+
try {
|
|
127
|
+
const real = realpathSync(resolve(baseReal, entry));
|
|
128
|
+
if (!isInsideDir(baseReal, real)) continue;
|
|
129
|
+
const st = lstatSync(real);
|
|
130
|
+
if (!st.isFile()) continue;
|
|
131
|
+
files.push({ path: real, mtime: st.mtimeMs });
|
|
132
|
+
} catch {
|
|
133
|
+
continue;
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
files.sort((a, b) => b.mtime - a.mtime);
|
|
137
|
+
if (files.length === 0) throw new Error('no spill files found in output directory');
|
|
138
|
+
for (const file of files) {
|
|
139
|
+
if (!isFailedSpillHeader(file.path)) return file.path;
|
|
140
|
+
}
|
|
141
|
+
return files[0].path;
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
// Reject lexical escapes (`..`, bare `.`) before touching the filesystem so
|
|
145
|
+
// the error message stays stable, then resolve symlinks and re-check.
|
|
146
|
+
const lexical = resolve(baseReal, String(nameOrPath));
|
|
147
|
+
if (!isInsideDir(baseReal, lexical)) {
|
|
148
|
+
throw new Error('spill.read path must stay inside CODEMODE_OUT_DIR');
|
|
149
|
+
}
|
|
150
|
+
const real = realpathSync(lexical);
|
|
151
|
+
if (!isInsideDir(baseReal, real)) {
|
|
152
|
+
throw new Error('spill.read path must stay inside CODEMODE_OUT_DIR');
|
|
153
|
+
}
|
|
154
|
+
if (!lstatSync(real).isFile()) {
|
|
155
|
+
throw new Error('spill.read target must be a regular file');
|
|
156
|
+
}
|
|
157
|
+
return real;
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
export function createSpillHelper(outDir = resolve(process.env.CODEMODE_OUT_DIR ?? '.agent/out')) {
|
|
161
|
+
const baseDir = resolve(outDir);
|
|
162
|
+
return Object.freeze({
|
|
163
|
+
dir: baseDir,
|
|
164
|
+
read(nameOrPath) {
|
|
165
|
+
return JSON.parse(readFileSync(resolveSpillTarget(baseDir, nameOrPath), 'utf8'));
|
|
166
|
+
},
|
|
167
|
+
});
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
const SPILL_READ_CHUNK_BYTES = 64 * 1024;
|
|
171
|
+
const DEFAULT_SPILL_PAGE_CHARS = 20000;
|
|
172
|
+
const MAX_SPILL_PAGE_CHARS = 1000000;
|
|
173
|
+
|
|
174
|
+
export function readSpillPage(outDir, { name, path, offset = 0, maxChars = DEFAULT_SPILL_PAGE_CHARS } = {}) {
|
|
175
|
+
const target = resolveSpillTarget(resolve(outDir), name ?? path);
|
|
176
|
+
const requested = Number(offset);
|
|
177
|
+
const start = Number.isInteger(requested) && requested > 0 ? requested : 0;
|
|
178
|
+
const limit = Number.isInteger(maxChars) && maxChars > 0
|
|
179
|
+
? Math.max(2, Math.min(Math.floor(maxChars), MAX_SPILL_PAGE_CHARS))
|
|
180
|
+
: DEFAULT_SPILL_PAGE_CHARS;
|
|
181
|
+
|
|
182
|
+
const fd = openSync(target, 'r');
|
|
183
|
+
const decoder = new StringDecoder('utf8');
|
|
184
|
+
const buffer = Buffer.allocUnsafe(SPILL_READ_CHUNK_BYTES);
|
|
185
|
+
let position = 0;
|
|
186
|
+
let charCount = 0;
|
|
187
|
+
let text = '';
|
|
188
|
+
try {
|
|
189
|
+
if (!fstatSync(fd).isFile()) {
|
|
190
|
+
throw new Error('spill.read target must be a regular file');
|
|
191
|
+
}
|
|
192
|
+
for (;;) {
|
|
193
|
+
const bytes = readSync(fd, buffer, 0, buffer.length, position);
|
|
194
|
+
position += bytes;
|
|
195
|
+
const chunk = bytes === 0 ? decoder.end() : decoder.write(buffer.subarray(0, bytes));
|
|
196
|
+
if (chunk.length > 0) {
|
|
197
|
+
const chunkStart = charCount;
|
|
198
|
+
const chunkEnd = charCount + chunk.length;
|
|
199
|
+
if (text.length < limit) {
|
|
200
|
+
const from = Math.max(start, chunkStart);
|
|
201
|
+
const to = Math.min(start + limit, chunkEnd);
|
|
202
|
+
if (to > from) text += chunk.slice(from - chunkStart, to - chunkStart);
|
|
203
|
+
}
|
|
204
|
+
charCount = chunkEnd;
|
|
205
|
+
}
|
|
206
|
+
if (bytes === 0) break;
|
|
207
|
+
}
|
|
208
|
+
} finally {
|
|
209
|
+
closeSync(fd);
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
// Never end a page on a lone high surrogate: it would be mangled when the
|
|
213
|
+
// host re-encodes it. Drop it so the next page starts on a clean code point.
|
|
214
|
+
if (text.length > 0) {
|
|
215
|
+
const last = text.charCodeAt(text.length - 1);
|
|
216
|
+
if (last >= 0xd800 && last <= 0xdbff) text = text.slice(0, -1);
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
const pageOffset = Math.min(start, charCount);
|
|
220
|
+
const nextOffset = pageOffset + text.length < charCount ? pageOffset + text.length : null;
|
|
221
|
+
return {
|
|
222
|
+
text,
|
|
223
|
+
totalChars: charCount,
|
|
224
|
+
offset: pageOffset,
|
|
225
|
+
truncated: nextOffset !== null,
|
|
226
|
+
nextOffset,
|
|
227
|
+
};
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
async function importModuleSource(code, scope) {
|
|
231
|
+
const dataUrl = `data:text/javascript;base64,${Buffer.from(code, 'utf8').toString('base64')}`;
|
|
232
|
+
const mod = await import(dataUrl);
|
|
233
|
+
const run = mod.run ?? mod.default;
|
|
234
|
+
if (typeof run !== 'function') {
|
|
235
|
+
throw new Error('program must export run({ tools, args }) or a default function');
|
|
236
|
+
}
|
|
237
|
+
return run(scope);
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
async function executeSourceCode(code, scope) {
|
|
241
|
+
let fn;
|
|
242
|
+
try {
|
|
243
|
+
fn = new AsyncFunction(
|
|
244
|
+
'tools',
|
|
245
|
+
'args',
|
|
246
|
+
'mapBounded',
|
|
247
|
+
'execTool',
|
|
248
|
+
'execJson',
|
|
249
|
+
'spill',
|
|
250
|
+
'listTools',
|
|
251
|
+
'callTool',
|
|
252
|
+
code,
|
|
253
|
+
);
|
|
254
|
+
} catch (err) {
|
|
255
|
+
if (!(err instanceof SyntaxError) || !MODULE_SYNTAX_RE.test(err.message)) throw err;
|
|
256
|
+
return importModuleSource(code, scope);
|
|
257
|
+
}
|
|
258
|
+
return fn(
|
|
259
|
+
scope.tools,
|
|
260
|
+
scope.args,
|
|
261
|
+
mapBounded,
|
|
262
|
+
execTool,
|
|
263
|
+
execJson,
|
|
264
|
+
scope.spill,
|
|
265
|
+
scope.listTools,
|
|
266
|
+
scope.callTool,
|
|
267
|
+
);
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
export async function executeProgram({
|
|
271
|
+
mode,
|
|
272
|
+
source,
|
|
273
|
+
programPath,
|
|
274
|
+
args = {},
|
|
275
|
+
registry,
|
|
276
|
+
spill,
|
|
277
|
+
outDir = resolve(process.env.CODEMODE_OUT_DIR ?? '.agent/out'),
|
|
278
|
+
label = 'inline',
|
|
279
|
+
spillStem = label,
|
|
280
|
+
version,
|
|
281
|
+
maxChars = parseMaxChars(),
|
|
282
|
+
timeoutMs,
|
|
283
|
+
signal,
|
|
284
|
+
listTools,
|
|
285
|
+
callTool,
|
|
286
|
+
isolateProcess = false,
|
|
287
|
+
emptySourceMessage,
|
|
288
|
+
sourceError,
|
|
289
|
+
log = (line) => console.error(line),
|
|
290
|
+
} = {}) {
|
|
291
|
+
const logs = [];
|
|
292
|
+
const startedAt = new Date().toISOString();
|
|
293
|
+
let result;
|
|
294
|
+
let failed = false;
|
|
295
|
+
let errorPayload;
|
|
296
|
+
|
|
297
|
+
const originalLog = console.log;
|
|
298
|
+
const originalWrite = process.stdout.write;
|
|
299
|
+
const originalExit = process.exit;
|
|
300
|
+
|
|
301
|
+
console.log = (...parts) => logs.push(parts.map(formatLogPart).join(' '));
|
|
302
|
+
if (isolateProcess) {
|
|
303
|
+
process.stdout.write = (chunk, encoding, callback) => {
|
|
304
|
+
logs.push(Buffer.isBuffer(chunk) ? chunk.toString('utf8') : String(chunk));
|
|
305
|
+
if (typeof encoding === 'function') encoding();
|
|
306
|
+
else if (typeof callback === 'function') callback();
|
|
307
|
+
return true;
|
|
308
|
+
};
|
|
309
|
+
process.exit = (code) => {
|
|
310
|
+
throw new Error(`process.exit(${code ?? 0}) is not allowed inside run_code`);
|
|
311
|
+
};
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
const controller = new AbortController();
|
|
315
|
+
let timer = null;
|
|
316
|
+
const abortFromOutside = () => controller.abort(signal.reason);
|
|
317
|
+
if (signal) {
|
|
318
|
+
if (signal.aborted) controller.abort(signal.reason);
|
|
319
|
+
else signal.addEventListener('abort', abortFromOutside, { once: true });
|
|
320
|
+
}
|
|
321
|
+
if (Number.isInteger(timeoutMs) && timeoutMs > 0) {
|
|
322
|
+
timer = setTimeout(() => {
|
|
323
|
+
controller.abort(new Error(`run_code timed out after ${timeoutMs}ms`));
|
|
324
|
+
}, timeoutMs);
|
|
325
|
+
timer.unref?.();
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
const scope = {
|
|
329
|
+
tools: registry,
|
|
330
|
+
args,
|
|
331
|
+
spill,
|
|
332
|
+
listTools,
|
|
333
|
+
callTool,
|
|
334
|
+
};
|
|
335
|
+
|
|
336
|
+
try {
|
|
337
|
+
const programPromise = (async () => {
|
|
338
|
+
if (sourceError) throw sourceError;
|
|
339
|
+
if (emptySourceMessage && String(source ?? '').trim().length === 0) {
|
|
340
|
+
throw new Error(emptySourceMessage);
|
|
341
|
+
}
|
|
342
|
+
if (mode === 'file') {
|
|
343
|
+
const url = `${pathToFileURL(resolve(programPath)).href}?t=${Date.now()}`;
|
|
344
|
+
const mod = await import(url);
|
|
345
|
+
const run = mod.run ?? mod.default;
|
|
346
|
+
if (typeof run !== 'function') {
|
|
347
|
+
throw new Error('program must export run({ tools, args }) or a default function');
|
|
348
|
+
}
|
|
349
|
+
return run(scope);
|
|
350
|
+
}
|
|
351
|
+
return executeSourceCode(source, scope);
|
|
352
|
+
})();
|
|
353
|
+
|
|
354
|
+
const aborted = new Promise((_resolve, reject) => {
|
|
355
|
+
if (controller.signal.aborted) {
|
|
356
|
+
reject(controller.signal.reason ?? new Error('aborted'));
|
|
357
|
+
return;
|
|
358
|
+
}
|
|
359
|
+
controller.signal.addEventListener(
|
|
360
|
+
'abort',
|
|
361
|
+
() => reject(controller.signal.reason ?? new Error('aborted')),
|
|
362
|
+
{ once: true },
|
|
363
|
+
);
|
|
364
|
+
});
|
|
365
|
+
programPromise.catch(() => {});
|
|
366
|
+
result = await Promise.race([programPromise, aborted]);
|
|
367
|
+
} catch (e) {
|
|
368
|
+
failed = true;
|
|
369
|
+
errorPayload = normalizeError(e);
|
|
370
|
+
} finally {
|
|
371
|
+
if (timer) clearTimeout(timer);
|
|
372
|
+
if (signal) signal.removeEventListener('abort', abortFromOutside);
|
|
373
|
+
console.log = originalLog;
|
|
374
|
+
if (isolateProcess) {
|
|
375
|
+
process.stdout.write = originalWrite;
|
|
376
|
+
process.exit = originalExit;
|
|
377
|
+
}
|
|
378
|
+
}
|
|
379
|
+
|
|
380
|
+
const finishedAt = new Date().toISOString();
|
|
381
|
+
const stamp = startedAt.replace(/[:.]/g, '-');
|
|
382
|
+
const suffix = `${process.pid}-${randomBytes(4).toString('hex')}`;
|
|
383
|
+
|
|
384
|
+
let outPath = null;
|
|
385
|
+
try {
|
|
386
|
+
mkdirSync(outDir, { recursive: true, mode: 0o700 });
|
|
387
|
+
outPath = resolve(outDir, `${spillStem}-${stamp}-${suffix}.json`);
|
|
388
|
+
} catch (e) {
|
|
389
|
+
log(`[codemode] spill-dir-failed: ${e instanceof Error ? e.message : String(e)}`);
|
|
390
|
+
}
|
|
391
|
+
|
|
392
|
+
const serialize = (spillPath) => {
|
|
393
|
+
const envelope = {
|
|
394
|
+
ok: !failed,
|
|
395
|
+
version,
|
|
396
|
+
program: label,
|
|
397
|
+
startedAt,
|
|
398
|
+
finishedAt,
|
|
399
|
+
logs,
|
|
400
|
+
...(failed ? { error: errorPayload } : { result: result ?? null }),
|
|
401
|
+
...(spillPath ? { spill: { path: spillPath } } : {}),
|
|
402
|
+
};
|
|
403
|
+
try {
|
|
404
|
+
return { envelope, text: safeJsonStringify(envelope, 2) };
|
|
405
|
+
} catch (e) {
|
|
406
|
+
failed = true;
|
|
407
|
+
const fallback = {
|
|
408
|
+
ok: false,
|
|
409
|
+
version,
|
|
410
|
+
program: label,
|
|
411
|
+
startedAt,
|
|
412
|
+
finishedAt,
|
|
413
|
+
logs,
|
|
414
|
+
error: { kind: 'serialization', message: e instanceof Error ? e.message : String(e) },
|
|
415
|
+
...(spillPath ? { spill: { path: spillPath } } : {}),
|
|
416
|
+
};
|
|
417
|
+
return { envelope: fallback, text: safeJsonStringify(fallback, 2) };
|
|
418
|
+
}
|
|
419
|
+
};
|
|
420
|
+
|
|
421
|
+
let serialized = serialize(null);
|
|
422
|
+
if (outPath && serialized.text.length > maxChars) {
|
|
423
|
+
serialized = serialize(outPath);
|
|
424
|
+
}
|
|
425
|
+
|
|
426
|
+
if (outPath) {
|
|
427
|
+
try {
|
|
428
|
+
writeFileSync(outPath, serialized.text, { mode: 0o600, flag: 'wx' });
|
|
429
|
+
} catch (e) {
|
|
430
|
+
log(`[codemode] spill-write-failed: ${e instanceof Error ? e.message : String(e)}`);
|
|
431
|
+
outPath = null;
|
|
432
|
+
serialized = serialize(null);
|
|
433
|
+
}
|
|
434
|
+
}
|
|
435
|
+
|
|
436
|
+
return {
|
|
437
|
+
ok: !failed,
|
|
438
|
+
envelope: serialized.envelope,
|
|
439
|
+
text: serialized.text,
|
|
440
|
+
logs,
|
|
441
|
+
spillPath: outPath,
|
|
442
|
+
truncated: Boolean(outPath) && serialized.text.length > maxChars,
|
|
443
|
+
maxChars,
|
|
444
|
+
startedAt,
|
|
445
|
+
finishedAt,
|
|
446
|
+
};
|
|
447
|
+
}
|