@neurouter/executor 0.0.0-stage → 0.1.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/LICENSE +202 -0
- package/NOTICE +10 -0
- package/dist/.tsbuildinfo +1 -0
- package/dist/client.d.ts +57 -0
- package/dist/client.d.ts.map +1 -0
- package/dist/client.js +306 -0
- package/dist/client.js.map +1 -0
- package/dist/convert.d.ts +10 -0
- package/dist/convert.d.ts.map +1 -0
- package/dist/convert.js +57 -0
- package/dist/convert.js.map +1 -0
- package/dist/frames.d.ts +268 -0
- package/dist/frames.d.ts.map +1 -0
- package/dist/frames.js +139 -0
- package/dist/frames.js.map +1 -0
- package/dist/index.d.ts +12 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +12 -0
- package/dist/index.js.map +1 -0
- package/dist/local-executor.d.ts +17 -0
- package/dist/local-executor.d.ts.map +1 -0
- package/dist/local-executor.js +25 -0
- package/dist/local-executor.js.map +1 -0
- package/dist/logger.d.ts +5 -0
- package/dist/logger.d.ts.map +1 -0
- package/dist/logger.js +22 -0
- package/dist/logger.js.map +1 -0
- package/dist/main.d.ts +3 -0
- package/dist/main.d.ts.map +1 -0
- package/dist/main.js +56 -0
- package/dist/main.js.map +1 -0
- package/dist/monty-info.d.ts +11 -0
- package/dist/monty-info.d.ts.map +1 -0
- package/dist/monty-info.js +36 -0
- package/dist/monty-info.js.map +1 -0
- package/dist/monty-runner.d.ts +41 -0
- package/dist/monty-runner.d.ts.map +1 -0
- package/dist/monty-runner.js +390 -0
- package/dist/monty-runner.js.map +1 -0
- package/dist/server.d.ts +30 -0
- package/dist/server.d.ts.map +1 -0
- package/dist/server.js +182 -0
- package/dist/server.js.map +1 -0
- package/dist/spawn.d.ts +48 -0
- package/dist/spawn.d.ts.map +1 -0
- package/dist/spawn.js +124 -0
- package/dist/spawn.js.map +1 -0
- package/dist/types.d.ts +121 -0
- package/dist/types.d.ts.map +1 -0
- package/dist/types.js +17 -0
- package/dist/types.js.map +1 -0
- package/dist/version.d.ts +2 -0
- package/dist/version.d.ts.map +1 -0
- package/dist/version.js +2 -0
- package/dist/version.js.map +1 -0
- package/package.json +53 -4
- package/README.md +0 -3
|
@@ -0,0 +1,390 @@
|
|
|
1
|
+
import { ExternalModule, FunctionSnapshot, Monty, MontyComplete, MontyCrashedError, MontyRuntimeError, MontySyntaxError, MontyTypingError, NameLookupSnapshot, NOT_HANDLED, } from '@pydantic/monty';
|
|
2
|
+
import { jsonBytes, toJson, truncateUtf8 } from './convert.js';
|
|
3
|
+
import { montyVersion, resolveMontyBinary, verifyMontyBinary } from './monty-info.js';
|
|
4
|
+
import { DEFAULT_LIMITS, MAX_STDOUT_BYTES, PREVIEW_BYTES, } from './types.js';
|
|
5
|
+
/** Helpers implemented inside the executor (no host round trip). */
|
|
6
|
+
const BUILTIN_OPS_STUBS = `from typing import Any
|
|
7
|
+
def parallel(calls: list[tuple[str, dict[str, Any]]]) -> list[dict[str, Any]]:
|
|
8
|
+
"""Run several tool calls concurrently; returns [{"ok": True, "value": ...} | {"ok": False, "error": {...}}] in input order."""
|
|
9
|
+
...
|
|
10
|
+
def days_since(iso: str) -> float:
|
|
11
|
+
"""Days between the run's start time and an ISO-8601 timestamp."""
|
|
12
|
+
...
|
|
13
|
+
def now() -> str:
|
|
14
|
+
"""The run's start time (ISO-8601, fixed for the whole run)."""
|
|
15
|
+
...
|
|
16
|
+
`;
|
|
17
|
+
const BUILTIN_OPS = new Set(['parallel', 'days_since', 'now']);
|
|
18
|
+
/** Also callable without the `ops.` prefix (composite scripts in overlays use them bare). */
|
|
19
|
+
const BARE_GLOBALS = new Set(['days_since']);
|
|
20
|
+
const LIMIT_EXCEPTIONS = new Set(['TimeoutError', 'MemoryError', 'RecursionError']);
|
|
21
|
+
const IDENT = /^[A-Za-z_][A-Za-z0-9_]*$/;
|
|
22
|
+
const SCRIPT_NAME = 'script.py';
|
|
23
|
+
class Aborted extends Error {
|
|
24
|
+
}
|
|
25
|
+
const noopLogger = { debug() { }, info() { }, warn() { }, error() { } };
|
|
26
|
+
/** Runs scripts in a pool of crash-isolated Monty worker subprocesses, one fresh worker per run. */
|
|
27
|
+
export class MontyRunner {
|
|
28
|
+
pool;
|
|
29
|
+
poolMax;
|
|
30
|
+
binaryPath;
|
|
31
|
+
binarySha256;
|
|
32
|
+
log;
|
|
33
|
+
active = 0;
|
|
34
|
+
closed = false;
|
|
35
|
+
constructor(pool, poolMax, binaryPath, binarySha256, log) {
|
|
36
|
+
this.pool = pool;
|
|
37
|
+
this.poolMax = poolMax;
|
|
38
|
+
this.binaryPath = binaryPath;
|
|
39
|
+
this.binarySha256 = binarySha256;
|
|
40
|
+
this.log = log;
|
|
41
|
+
}
|
|
42
|
+
static async create(opts) {
|
|
43
|
+
const binaryPath = resolveMontyBinary(opts.binaryPath);
|
|
44
|
+
const sha = verifyMontyBinary(binaryPath, opts.binarySha256 ?? process.env.MONTY_BINARY_SHA256);
|
|
45
|
+
const poolMax = Math.max(1, opts.poolMax);
|
|
46
|
+
const prewarm = Math.max(0, Math.min(opts.prewarm, poolMax));
|
|
47
|
+
const clock = opts.executionClock ?? (process.platform === 'linux' ? 'cpu' : 'wall');
|
|
48
|
+
const pool = await Monty.create({
|
|
49
|
+
binaryPath,
|
|
50
|
+
executionClock: clock,
|
|
51
|
+
minProcesses: prewarm,
|
|
52
|
+
preWarm: prewarm,
|
|
53
|
+
maxProcesses: poolMax,
|
|
54
|
+
checkoutTimeout: opts.checkoutTimeoutSec ?? 5,
|
|
55
|
+
requestTimeout: opts.requestTimeoutSec ?? 35,
|
|
56
|
+
feedDurationLimitGrace: 1,
|
|
57
|
+
turnDurationLimitGrace: 1,
|
|
58
|
+
// one session per worker: discard after every run (plan L2/L6)
|
|
59
|
+
maxCheckoutsPerWorker: 1,
|
|
60
|
+
});
|
|
61
|
+
const log = opts.logger ?? noopLogger;
|
|
62
|
+
log.info({ binaryPath, sha256: sha, poolMax, prewarm, clock, montyVersion: montyVersion() }, 'monty pool started');
|
|
63
|
+
return new MontyRunner(pool, poolMax, binaryPath, sha, log);
|
|
64
|
+
}
|
|
65
|
+
get busy() {
|
|
66
|
+
return this.active;
|
|
67
|
+
}
|
|
68
|
+
get montyVersion() {
|
|
69
|
+
return montyVersion();
|
|
70
|
+
}
|
|
71
|
+
health() {
|
|
72
|
+
return { ok: !this.closed, montyVersion: montyVersion(), poolSize: this.poolMax, busy: this.active, ...(this.closed ? { detail: 'closed' } : {}) };
|
|
73
|
+
}
|
|
74
|
+
async close() {
|
|
75
|
+
if (this.closed)
|
|
76
|
+
return;
|
|
77
|
+
this.closed = true;
|
|
78
|
+
await this.pool.close().catch(() => { });
|
|
79
|
+
}
|
|
80
|
+
async run(req, host, signal) {
|
|
81
|
+
const t0 = performance.now();
|
|
82
|
+
const limits = { ...DEFAULT_LIMITS, ...req.limits };
|
|
83
|
+
const lineOffset = req.lineOffset ?? 0;
|
|
84
|
+
const colOffset = req.colOffset ?? 0;
|
|
85
|
+
const stats = { wallMs: 0, suspensions: 0, toolCalls: 0 };
|
|
86
|
+
let stdout = '';
|
|
87
|
+
let stdoutBytes = 0;
|
|
88
|
+
let limitTripped = null;
|
|
89
|
+
let wallExpired = false;
|
|
90
|
+
let session = null;
|
|
91
|
+
let killed = false;
|
|
92
|
+
let workerPid;
|
|
93
|
+
const finish = (status, extra = {}) => {
|
|
94
|
+
stats.wallMs = Math.round(performance.now() - t0);
|
|
95
|
+
return { status, valueBytes: 0, stats, stdout, ...extra };
|
|
96
|
+
};
|
|
97
|
+
if (this.closed)
|
|
98
|
+
return finish('crashed', { error: { type: 'executor_unavailable', message: 'executor is shutting down' } });
|
|
99
|
+
// abort plumbing: caller signal + executor wall deadline
|
|
100
|
+
let rejectAbort;
|
|
101
|
+
const aborted = new Promise((_, rej) => (rejectAbort = rej));
|
|
102
|
+
aborted.catch(() => { });
|
|
103
|
+
const onAbort = () => rejectAbort(new Aborted('aborted'));
|
|
104
|
+
if (signal.aborted)
|
|
105
|
+
return finish('cancelled', { error: { type: 'cancelled', message: String(signal.reason ?? 'cancelled') } });
|
|
106
|
+
signal.addEventListener('abort', onAbort, { once: true });
|
|
107
|
+
const wallTimer = setTimeout(() => {
|
|
108
|
+
wallExpired = true;
|
|
109
|
+
rejectAbort(new Aborted('wall'));
|
|
110
|
+
}, limits.wallTimeSec * 1000);
|
|
111
|
+
const race = (p) => Promise.race([p, aborted]);
|
|
112
|
+
const allowed = new Set();
|
|
113
|
+
const externalModules = {};
|
|
114
|
+
const refuse = () => {
|
|
115
|
+
throw new Error('host functions are answered by the executor drive loop');
|
|
116
|
+
};
|
|
117
|
+
const modules = { ...req.modules };
|
|
118
|
+
if (!modules.ops)
|
|
119
|
+
modules.ops = { functions: [], stubs: '' };
|
|
120
|
+
for (const [ns, spec] of Object.entries(modules)) {
|
|
121
|
+
const attrs = {};
|
|
122
|
+
const fns = ns === 'ops' ? [...new Set([...spec.functions, ...BUILTIN_OPS])] : spec.functions;
|
|
123
|
+
for (const fn of fns) {
|
|
124
|
+
attrs[fn] = refuse;
|
|
125
|
+
if (!(ns === 'ops' && BUILTIN_OPS.has(fn)))
|
|
126
|
+
allowed.add(`${ns}.${fn}`);
|
|
127
|
+
}
|
|
128
|
+
const stubs = ns === 'ops' ? `${BUILTIN_OPS_STUBS}\n${spec.stubs}` : spec.stubs;
|
|
129
|
+
externalModules[ns] = new ExternalModule(attrs, { stubs });
|
|
130
|
+
}
|
|
131
|
+
const inputs = req.inputs ?? {};
|
|
132
|
+
const globalStubs = ['from typing import Any', 'def days_since(iso: str) -> float: ...', ...Object.keys(inputs).filter((k) => IDENT.test(k)).map((k) => `${k}: Any`)].join('\n') + '\n';
|
|
133
|
+
const frozenNow = new Date(req.osPolicy.datetime);
|
|
134
|
+
const nowMs = Number.isNaN(frozenNow.getTime()) ? Date.now() : frozenNow.getTime();
|
|
135
|
+
const prelude = req.prelude ?? `import ${Object.keys(modules).join(', ')}`;
|
|
136
|
+
const denyOs = () => NOT_HANDLED;
|
|
137
|
+
const callHost = async (fn, kwargs) => {
|
|
138
|
+
stats.toolCalls++;
|
|
139
|
+
if (stats.toolCalls > limits.maxToolCalls) {
|
|
140
|
+
limitTripped = `limit_exceeded: ${limits.maxToolCalls} tool calls`;
|
|
141
|
+
return { ok: false, error: { code: 'limit_exceeded', message: `${limits.maxToolCalls} tool calls` } };
|
|
142
|
+
}
|
|
143
|
+
try {
|
|
144
|
+
const r = await race(host.call(fn, kwargs));
|
|
145
|
+
if (!r.ok && r.error.code === 'limit_exceeded')
|
|
146
|
+
limitTripped = `limit_exceeded: ${r.error.message}`;
|
|
147
|
+
return r;
|
|
148
|
+
}
|
|
149
|
+
catch (err) {
|
|
150
|
+
if (err instanceof Aborted)
|
|
151
|
+
throw err;
|
|
152
|
+
return { ok: false, error: { code: 'internal', message: err instanceof Error ? err.message : String(err) } };
|
|
153
|
+
}
|
|
154
|
+
};
|
|
155
|
+
const toPyError = (e) => new Error(`${e.code}: ${e.message}${e.errorId ? ` (error_id=${e.errorId})` : ''}`);
|
|
156
|
+
const parallel = async (calls) => {
|
|
157
|
+
if (!Array.isArray(calls))
|
|
158
|
+
throw new TypeError('ops.parallel expects a list of (tool_name, kwargs) tuples');
|
|
159
|
+
const items = calls.map((c) => {
|
|
160
|
+
if (!Array.isArray(c) || c.length !== 2 || typeof c[0] !== 'string')
|
|
161
|
+
return null;
|
|
162
|
+
const kw = toJson(c[1]);
|
|
163
|
+
if (kw === null || typeof kw !== 'object' || Array.isArray(kw))
|
|
164
|
+
return null;
|
|
165
|
+
return { fn: c[0], kwargs: kw };
|
|
166
|
+
});
|
|
167
|
+
const results = new Array(items.length);
|
|
168
|
+
let next = 0;
|
|
169
|
+
const worker = async () => {
|
|
170
|
+
while (next < items.length) {
|
|
171
|
+
const i = next++;
|
|
172
|
+
const item = items[i];
|
|
173
|
+
if (!item) {
|
|
174
|
+
results[i] = { ok: false, error: { code: 'invalid_args', message: 'each item must be a (tool_name, kwargs) tuple', error_id: null } };
|
|
175
|
+
continue;
|
|
176
|
+
}
|
|
177
|
+
if (!allowed.has(item.fn)) {
|
|
178
|
+
results[i] = { ok: false, error: { code: 'unknown_tool', message: 'Tool not found or not permitted', error_id: null } };
|
|
179
|
+
continue;
|
|
180
|
+
}
|
|
181
|
+
const r = await callHost(item.fn, item.kwargs);
|
|
182
|
+
results[i] = r.ok ? { ok: true, value: r.value } : { ok: false, error: { code: r.error.code, message: r.error.message, error_id: r.error.errorId ?? null } };
|
|
183
|
+
}
|
|
184
|
+
};
|
|
185
|
+
await Promise.all(Array.from({ length: Math.min(limits.maxConcurrentCalls, items.length) }, worker));
|
|
186
|
+
return results;
|
|
187
|
+
};
|
|
188
|
+
const builtin = async (name, args, kwargs) => {
|
|
189
|
+
switch (name) {
|
|
190
|
+
case 'parallel':
|
|
191
|
+
return parallel(args[0] ?? kwargs.calls);
|
|
192
|
+
case 'days_since': {
|
|
193
|
+
const iso = args[0] ?? kwargs.iso;
|
|
194
|
+
const t = typeof iso === 'string' ? Date.parse(iso) : NaN;
|
|
195
|
+
if (Number.isNaN(t))
|
|
196
|
+
throw new TypeError('days_since expects an ISO-8601 string');
|
|
197
|
+
return (nowMs - t) / 86_400_000;
|
|
198
|
+
}
|
|
199
|
+
case 'now':
|
|
200
|
+
return new Date(nowMs).toISOString();
|
|
201
|
+
}
|
|
202
|
+
throw new TypeError(`unknown helper ${name}`);
|
|
203
|
+
};
|
|
204
|
+
this.active++;
|
|
205
|
+
try {
|
|
206
|
+
session = await race(this.pool.checkout({
|
|
207
|
+
scriptName: SCRIPT_NAME,
|
|
208
|
+
limits: {
|
|
209
|
+
maxFeedDurationSecs: limits.cpuTimeSec,
|
|
210
|
+
maxMemory: Math.round(limits.maxMemoryMb * 1024 * 1024),
|
|
211
|
+
maxRecursionDepth: limits.maxRecursionDepth ?? 200,
|
|
212
|
+
maxSuspensions: limits.maxToolCalls + 50 + 10 * Object.keys(modules).length,
|
|
213
|
+
maxTotalSleepSecs: 0,
|
|
214
|
+
},
|
|
215
|
+
typeCheck: req.typeCheck ?? true,
|
|
216
|
+
typeCheckFormat: 'json',
|
|
217
|
+
typeCheckStubs: globalStubs,
|
|
218
|
+
externalModules,
|
|
219
|
+
osPolicy: { datetime: new Date(nowMs), timezone: 'utc', sleep: 'zero', randomStart: { seed: req.osPolicy.seed }, processTime: 'zero' },
|
|
220
|
+
}));
|
|
221
|
+
const s = session;
|
|
222
|
+
// the pid is not readable while a turn is in flight, so remember it now (cancel/wall kill)
|
|
223
|
+
workerPid = s.workerPid;
|
|
224
|
+
// feed 1: the prelude binds the namespaces (imports resolve only from externalModules)
|
|
225
|
+
let snap = await race(s.feedStart(prelude, { os: denyOs }));
|
|
226
|
+
while (!(snap instanceof MontyComplete))
|
|
227
|
+
snap = await race(snap.resumeAuto());
|
|
228
|
+
// feed 2: the wrapped user code
|
|
229
|
+
snap = await race(s.feedStart(req.code, {
|
|
230
|
+
inputs,
|
|
231
|
+
os: denyOs,
|
|
232
|
+
printCallback: (_stream, text) => {
|
|
233
|
+
if (stdoutBytes >= MAX_STDOUT_BYTES)
|
|
234
|
+
return;
|
|
235
|
+
const chunk = truncateUtf8(text, MAX_STDOUT_BYTES - stdoutBytes);
|
|
236
|
+
stdout += chunk;
|
|
237
|
+
stdoutBytes += Buffer.byteLength(chunk, 'utf8');
|
|
238
|
+
},
|
|
239
|
+
}));
|
|
240
|
+
while (!(snap instanceof MontyComplete)) {
|
|
241
|
+
stats.suspensions++;
|
|
242
|
+
if (snap instanceof FunctionSnapshot) {
|
|
243
|
+
const name = snap.functionName;
|
|
244
|
+
if (snap.isOsFunction) {
|
|
245
|
+
snap = await race(snap.resumeNotHandled());
|
|
246
|
+
continue;
|
|
247
|
+
}
|
|
248
|
+
const dot = name.indexOf('.');
|
|
249
|
+
const bare = dot < 0 && BARE_GLOBALS.has(name) ? name : null;
|
|
250
|
+
const opsHelper = name.startsWith('ops.') && BUILTIN_OPS.has(name.slice(4)) ? name.slice(4) : null;
|
|
251
|
+
if (bare || opsHelper) {
|
|
252
|
+
const call = snap;
|
|
253
|
+
let value;
|
|
254
|
+
try {
|
|
255
|
+
value = await builtin((bare ?? opsHelper), call.args, call.kwargs);
|
|
256
|
+
}
|
|
257
|
+
catch (err) {
|
|
258
|
+
if (err instanceof Aborted)
|
|
259
|
+
throw err;
|
|
260
|
+
snap = await race(call.resumeError(err));
|
|
261
|
+
continue;
|
|
262
|
+
}
|
|
263
|
+
snap = await race(call.resume(value));
|
|
264
|
+
continue;
|
|
265
|
+
}
|
|
266
|
+
if (allowed.has(name)) {
|
|
267
|
+
if (snap.args.length > 0) {
|
|
268
|
+
snap = await race(snap.resumeError(new TypeError(`${name}() takes keyword arguments only: use keyword arguments, e.g. ${name}(name=value)`)));
|
|
269
|
+
continue;
|
|
270
|
+
}
|
|
271
|
+
const call = snap;
|
|
272
|
+
const r = await callHost(name, toJson(call.kwargs));
|
|
273
|
+
snap = await race(r.ok ? call.resume(r.value) : call.resumeError(toPyError(r.error)));
|
|
274
|
+
continue;
|
|
275
|
+
}
|
|
276
|
+
// import machinery or a name we do not provide: Monty's default answer (AttributeError/NameError)
|
|
277
|
+
snap = await race(snap.resumeAuto());
|
|
278
|
+
continue;
|
|
279
|
+
}
|
|
280
|
+
if (snap instanceof NameLookupSnapshot && BARE_GLOBALS.has(snap.variableName)) {
|
|
281
|
+
snap = await race(snap.resume(snap.variableName));
|
|
282
|
+
continue;
|
|
283
|
+
}
|
|
284
|
+
snap = await race(snap.resumeAuto());
|
|
285
|
+
}
|
|
286
|
+
const value = toJson(snap.output);
|
|
287
|
+
const valueBytes = jsonBytes(value);
|
|
288
|
+
if (valueBytes > limits.maxResultBytes) {
|
|
289
|
+
return finish('ok', { valueBytes, truncated: true, preview: truncateUtf8(JSON.stringify(value), PREVIEW_BYTES) });
|
|
290
|
+
}
|
|
291
|
+
return finish('ok', { value, valueBytes });
|
|
292
|
+
}
|
|
293
|
+
catch (err) {
|
|
294
|
+
if (err instanceof Aborted) {
|
|
295
|
+
if (session) {
|
|
296
|
+
killWorker(workerPid);
|
|
297
|
+
killed = true;
|
|
298
|
+
}
|
|
299
|
+
return wallExpired
|
|
300
|
+
? finish('limit_exceeded', { error: { type: 'TimeoutError', message: `wall time limit of ${limits.wallTimeSec}s exceeded` } })
|
|
301
|
+
: finish('cancelled', { error: { type: 'cancelled', message: String(signal.reason ?? 'cancelled') } });
|
|
302
|
+
}
|
|
303
|
+
const mapped = mapError(err, lineOffset, limitTripped, limits.cpuTimeSec, colOffset);
|
|
304
|
+
if (mapped.status === 'crashed')
|
|
305
|
+
this.log.warn({ runId: req.runId, err: mapped.error }, 'monty worker crashed');
|
|
306
|
+
return finish(mapped.status, { error: mapped.error });
|
|
307
|
+
}
|
|
308
|
+
finally {
|
|
309
|
+
clearTimeout(wallTimer);
|
|
310
|
+
signal.removeEventListener('abort', onAbort);
|
|
311
|
+
this.active--;
|
|
312
|
+
if (session) {
|
|
313
|
+
// a killed worker's close can wait for the turn to unwind; never hold the result for it
|
|
314
|
+
const closing = session.close().catch(() => { });
|
|
315
|
+
if (!killed)
|
|
316
|
+
await closing;
|
|
317
|
+
}
|
|
318
|
+
}
|
|
319
|
+
}
|
|
320
|
+
}
|
|
321
|
+
function killWorker(pid) {
|
|
322
|
+
if (pid) {
|
|
323
|
+
try {
|
|
324
|
+
process.kill(pid, 'SIGKILL');
|
|
325
|
+
}
|
|
326
|
+
catch {
|
|
327
|
+
/* already gone */
|
|
328
|
+
}
|
|
329
|
+
}
|
|
330
|
+
}
|
|
331
|
+
const mapCol = (col, offset) => (col === undefined ? undefined : Math.max(1, col - offset));
|
|
332
|
+
const mapLine = (line, offset) => (line === undefined ? undefined : Math.max(1, line - offset));
|
|
333
|
+
function cleanTraceback(text, offset) {
|
|
334
|
+
return text.replace(/<python-input-\d+>/g, SCRIPT_NAME).replace(/line (\d+)/g, (_m, n) => `line ${mapLine(Number(n), offset)}`);
|
|
335
|
+
}
|
|
336
|
+
/** Maps a Monty exception to a run status and a user-facing error with user line numbers. */
|
|
337
|
+
export function mapError(err, offset, limitTripped, cpuSec, colOffset = 0) {
|
|
338
|
+
if (err instanceof MontyTypingError) {
|
|
339
|
+
let diags = [];
|
|
340
|
+
try {
|
|
341
|
+
diags = JSON.parse(err.display());
|
|
342
|
+
}
|
|
343
|
+
catch {
|
|
344
|
+
/* non-JSON rendering */
|
|
345
|
+
}
|
|
346
|
+
const errors = diags.filter((d) => d.severity !== 'warning' && d.severity !== 'info');
|
|
347
|
+
const first = errors[0] ?? diags[0];
|
|
348
|
+
const syntax = errors.some((d) => d.code === 'invalid-syntax');
|
|
349
|
+
const lines = errors.map((d) => `line ${mapLine(d.location?.row, offset)}, col ${mapCol(d.location?.column, colOffset) ?? '?'}: ${d.message ?? ''} [${d.code ?? 'type'}]`);
|
|
350
|
+
return {
|
|
351
|
+
status: syntax ? 'syntax_error' : 'type_error',
|
|
352
|
+
error: {
|
|
353
|
+
type: syntax ? 'SyntaxError' : 'TypeError',
|
|
354
|
+
message: first?.message ?? err.message,
|
|
355
|
+
...(first?.location?.row !== undefined ? { line: mapLine(first.location.row, offset) } : {}),
|
|
356
|
+
...(first?.location?.column !== undefined ? { col: mapCol(first.location.column, colOffset) } : {}),
|
|
357
|
+
traceback: lines.join('\n') || err.display(),
|
|
358
|
+
},
|
|
359
|
+
};
|
|
360
|
+
}
|
|
361
|
+
if (err instanceof MontySyntaxError) {
|
|
362
|
+
const tb = err.display('traceback');
|
|
363
|
+
const m = /line (\d+)/.exec(tb);
|
|
364
|
+
return { status: 'syntax_error', error: { type: 'SyntaxError', message: err.display('msg'), ...(m ? { line: mapLine(Number(m[1]), offset) } : {}), traceback: cleanTraceback(tb, offset) } };
|
|
365
|
+
}
|
|
366
|
+
if (err instanceof MontyRuntimeError) {
|
|
367
|
+
const { typeName } = err.exception;
|
|
368
|
+
const frames = err.traceback();
|
|
369
|
+
const last = frames[frames.length - 1];
|
|
370
|
+
const status = LIMIT_EXCEPTIONS.has(typeName) || limitTripped ? 'limit_exceeded' : 'script_error';
|
|
371
|
+
return {
|
|
372
|
+
status,
|
|
373
|
+
error: {
|
|
374
|
+
type: typeName,
|
|
375
|
+
message: err.display('msg'),
|
|
376
|
+
...(last ? { line: mapLine(last.line, offset), col: mapCol(last.column, colOffset) } : {}),
|
|
377
|
+
traceback: cleanTraceback(err.display('traceback'), offset),
|
|
378
|
+
},
|
|
379
|
+
};
|
|
380
|
+
}
|
|
381
|
+
if (err instanceof MontyCrashedError) {
|
|
382
|
+
if (err.timedOut)
|
|
383
|
+
return { status: 'limit_exceeded', error: { type: 'TimeoutError', message: `time limit exceeded (${cpuSec}s execution budget)` } };
|
|
384
|
+
return { status: 'crashed', error: { type: 'crashed', message: err.message + (err.exitStatus ? ` (${err.exitStatus})` : '') } };
|
|
385
|
+
}
|
|
386
|
+
if (err instanceof Error && err.name === 'TimeoutError')
|
|
387
|
+
return { status: 'crashed', error: { type: 'executor_busy', message: 'no Monty worker became available in time' } };
|
|
388
|
+
return { status: 'crashed', error: { type: 'executor_error', message: err instanceof Error ? err.message : String(err) } };
|
|
389
|
+
}
|
|
390
|
+
//# sourceMappingURL=monty-runner.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"monty-runner.js","sourceRoot":"","sources":["../src/monty-runner.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,cAAc,EACd,gBAAgB,EAChB,KAAK,EACL,aAAa,EACb,iBAAiB,EACjB,iBAAiB,EACjB,gBAAgB,EAChB,gBAAgB,EAChB,kBAAkB,EAClB,WAAW,GAGZ,MAAM,iBAAiB,CAAC;AACzB,OAAO,EAAE,SAAS,EAAE,MAAM,EAAE,YAAY,EAAE,MAAM,cAAc,CAAC;AAC/D,OAAO,EAAE,YAAY,EAAE,kBAAkB,EAAE,iBAAiB,EAAE,MAAM,iBAAiB,CAAC;AACtF,OAAO,EACL,cAAc,EACd,gBAAgB,EAChB,aAAa,GASd,MAAM,YAAY,CAAC;AAoBpB,oEAAoE;AACpE,MAAM,iBAAiB,GAAG;;;;;;;;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C,GAAG,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,GAAG,CAAC,EAAE,EAAE,CAAC;AAC7H,CAAC"}
|
package/dist/server.d.ts
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import type { MontyRunner } from './monty-runner.js';
|
|
2
|
+
import { type ExecLogger } from './types.js';
|
|
3
|
+
export interface ExecutorServerOptions {
|
|
4
|
+
runner: MontyRunner;
|
|
5
|
+
/** Shared secret the server must present in `hello`. */
|
|
6
|
+
token: string;
|
|
7
|
+
logger?: ExecLogger;
|
|
8
|
+
}
|
|
9
|
+
export type ListenAddress = {
|
|
10
|
+
socketPath: string;
|
|
11
|
+
} | {
|
|
12
|
+
host: string;
|
|
13
|
+
port: number;
|
|
14
|
+
};
|
|
15
|
+
/**
|
|
16
|
+
* The executor side of the frame protocol (§10.6): authenticates the server with `hello`, then runs
|
|
17
|
+
* scripts multiplexed by `runId`, forwarding each host call as a `call` frame.
|
|
18
|
+
*/
|
|
19
|
+
export declare class ExecutorServer {
|
|
20
|
+
private readonly opts;
|
|
21
|
+
private server;
|
|
22
|
+
private readonly sockets;
|
|
23
|
+
private readonly log;
|
|
24
|
+
constructor(opts: ExecutorServerOptions);
|
|
25
|
+
listen(addr: ListenAddress): Promise<string>;
|
|
26
|
+
close(): Promise<void>;
|
|
27
|
+
private onConnection;
|
|
28
|
+
private startRun;
|
|
29
|
+
}
|
|
30
|
+
//# sourceMappingURL=server.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"server.d.ts","sourceRoot":"","sources":["../src/server.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,mBAAmB,CAAC;AAErD,OAAO,EAAoB,KAAK,UAAU,EAAuC,MAAM,YAAY,CAAC;AAGpG,MAAM,WAAW,qBAAqB;IACpC,MAAM,EAAE,WAAW,CAAC;IACpB,wDAAwD;IACxD,KAAK,EAAE,MAAM,CAAC;IACd,MAAM,CAAC,EAAE,UAAU,CAAC;CACrB;AAED,MAAM,MAAM,aAAa,GAAG;IAAE,UAAU,EAAE,MAAM,CAAA;CAAE,GAAG;IAAE,IAAI,EAAE,MAAM,CAAC;IAAC,IAAI,EAAE,MAAM,CAAA;CAAE,CAAC;AAepF;;;GAGG;AACH,qBAAa,cAAc;IAKb,OAAO,CAAC,QAAQ,CAAC,IAAI;IAJjC,OAAO,CAAC,MAAM,CAA2B;IACzC,OAAO,CAAC,QAAQ,CAAC,OAAO,CAAyB;IACjD,OAAO,CAAC,QAAQ,CAAC,GAAG,CAAa;gBAEJ,IAAI,EAAE,qBAAqB;IAIlD,MAAM,CAAC,IAAI,EAAE,aAAa,GAAG,OAAO,CAAC,MAAM,CAAC;IAoB5C,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC;IAK5B,OAAO,CAAC,YAAY;IAsFpB,OAAO,CAAC,QAAQ;CAoCjB"}
|
package/dist/server.js
ADDED
|
@@ -0,0 +1,182 @@
|
|
|
1
|
+
import { createHash, timingSafeEqual } from 'node:crypto';
|
|
2
|
+
import { chmodSync, existsSync, unlinkSync } from 'node:fs';
|
|
3
|
+
import net from 'node:net';
|
|
4
|
+
import { encodeFrame, FrameDecoder, FrameError, parseFrame, ToExecutorFrame } from './frames.js';
|
|
5
|
+
import { silentLogger } from './logger.js';
|
|
6
|
+
import { PROTOCOL_VERSION } from './types.js';
|
|
7
|
+
import { EXECUTOR_VERSION } from './version.js';
|
|
8
|
+
function tokenEquals(a, b) {
|
|
9
|
+
const ha = createHash('sha256').update(a).digest();
|
|
10
|
+
const hb = createHash('sha256').update(b).digest();
|
|
11
|
+
return timingSafeEqual(ha, hb) && a.length === b.length;
|
|
12
|
+
}
|
|
13
|
+
/**
|
|
14
|
+
* The executor side of the frame protocol (§10.6): authenticates the server with `hello`, then runs
|
|
15
|
+
* scripts multiplexed by `runId`, forwarding each host call as a `call` frame.
|
|
16
|
+
*/
|
|
17
|
+
export class ExecutorServer {
|
|
18
|
+
opts;
|
|
19
|
+
server = null;
|
|
20
|
+
sockets = new Set();
|
|
21
|
+
log;
|
|
22
|
+
constructor(opts) {
|
|
23
|
+
this.opts = opts;
|
|
24
|
+
this.log = opts.logger ?? silentLogger;
|
|
25
|
+
}
|
|
26
|
+
async listen(addr) {
|
|
27
|
+
const server = net.createServer((sock) => this.onConnection(sock));
|
|
28
|
+
this.server = server;
|
|
29
|
+
if ('socketPath' in addr) {
|
|
30
|
+
if (existsSync(addr.socketPath))
|
|
31
|
+
unlinkSync(addr.socketPath);
|
|
32
|
+
await new Promise((res, rej) => {
|
|
33
|
+
server.once('error', rej);
|
|
34
|
+
server.listen(addr.socketPath, () => res());
|
|
35
|
+
});
|
|
36
|
+
chmodSync(addr.socketPath, 0o600);
|
|
37
|
+
return addr.socketPath;
|
|
38
|
+
}
|
|
39
|
+
await new Promise((res, rej) => {
|
|
40
|
+
server.once('error', rej);
|
|
41
|
+
server.listen(addr.port, addr.host, () => res());
|
|
42
|
+
});
|
|
43
|
+
const a = server.address();
|
|
44
|
+
return typeof a === 'object' && a ? `${a.address}:${a.port}` : String(a);
|
|
45
|
+
}
|
|
46
|
+
async close() {
|
|
47
|
+
for (const s of this.sockets)
|
|
48
|
+
s.destroy();
|
|
49
|
+
await new Promise((res) => (this.server ? this.server.close(() => res()) : res()));
|
|
50
|
+
}
|
|
51
|
+
onConnection(sock) {
|
|
52
|
+
this.sockets.add(sock);
|
|
53
|
+
const decoder = new FrameDecoder();
|
|
54
|
+
const runs = new Map();
|
|
55
|
+
let authed = false;
|
|
56
|
+
const send = (frame) => {
|
|
57
|
+
if (sock.destroyed)
|
|
58
|
+
return;
|
|
59
|
+
sock.write(encodeFrame(frame));
|
|
60
|
+
};
|
|
61
|
+
const fail = (message) => {
|
|
62
|
+
this.log.warn({ message }, 'closing executor connection');
|
|
63
|
+
try {
|
|
64
|
+
send({ type: 'error', message });
|
|
65
|
+
}
|
|
66
|
+
catch {
|
|
67
|
+
/* ignore */
|
|
68
|
+
}
|
|
69
|
+
sock.destroy();
|
|
70
|
+
};
|
|
71
|
+
const helloTimer = setTimeout(() => !authed && fail('hello timeout'), 10_000);
|
|
72
|
+
sock.on('data', (chunk) => {
|
|
73
|
+
let raws;
|
|
74
|
+
try {
|
|
75
|
+
raws = decoder.push(chunk);
|
|
76
|
+
}
|
|
77
|
+
catch (err) {
|
|
78
|
+
return fail(err instanceof Error ? err.message : 'protocol error');
|
|
79
|
+
}
|
|
80
|
+
for (const raw of raws) {
|
|
81
|
+
let frame;
|
|
82
|
+
try {
|
|
83
|
+
frame = parseFrame(ToExecutorFrame, raw);
|
|
84
|
+
}
|
|
85
|
+
catch (err) {
|
|
86
|
+
return fail(err instanceof FrameError ? err.message : 'invalid frame');
|
|
87
|
+
}
|
|
88
|
+
if (!authed) {
|
|
89
|
+
if (frame.type !== 'hello' || !tokenEquals(frame.token, this.opts.token))
|
|
90
|
+
return fail('unauthorized');
|
|
91
|
+
authed = true;
|
|
92
|
+
clearTimeout(helloTimer);
|
|
93
|
+
send({
|
|
94
|
+
type: 'hello_ack',
|
|
95
|
+
protocol: PROTOCOL_VERSION,
|
|
96
|
+
executorVersion: EXECUTOR_VERSION,
|
|
97
|
+
montyVersion: this.opts.runner.montyVersion,
|
|
98
|
+
montyBinarySha256: this.opts.runner.binarySha256,
|
|
99
|
+
poolMax: this.opts.runner.poolMax,
|
|
100
|
+
});
|
|
101
|
+
continue;
|
|
102
|
+
}
|
|
103
|
+
switch (frame.type) {
|
|
104
|
+
case 'hello':
|
|
105
|
+
return fail('duplicate hello');
|
|
106
|
+
case 'ping':
|
|
107
|
+
send({ type: 'pong', ...(frame.t !== undefined ? { t: frame.t } : {}) });
|
|
108
|
+
break;
|
|
109
|
+
case 'pong':
|
|
110
|
+
break;
|
|
111
|
+
case 'run':
|
|
112
|
+
if (runs.has(frame.runId))
|
|
113
|
+
return fail(`duplicate runId ${frame.runId}`);
|
|
114
|
+
this.startRun(frame, runs, send);
|
|
115
|
+
break;
|
|
116
|
+
case 'call_result': {
|
|
117
|
+
const run = runs.get(frame.runId);
|
|
118
|
+
const resolve = run?.pending.get(frame.callId);
|
|
119
|
+
if (!run || !resolve)
|
|
120
|
+
break; // late answer for a finished/cancelled run
|
|
121
|
+
run.pending.delete(frame.callId);
|
|
122
|
+
resolve(frame.ok ? { ok: true, value: frame.value } : { ok: false, error: frame.error });
|
|
123
|
+
break;
|
|
124
|
+
}
|
|
125
|
+
case 'cancel':
|
|
126
|
+
runs.get(frame.runId)?.ac.abort(frame.reason);
|
|
127
|
+
break;
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
});
|
|
131
|
+
sock.on('error', () => { });
|
|
132
|
+
sock.on('close', () => {
|
|
133
|
+
clearTimeout(helloTimer);
|
|
134
|
+
this.sockets.delete(sock);
|
|
135
|
+
for (const run of runs.values()) {
|
|
136
|
+
run.ac.abort('server disconnected');
|
|
137
|
+
for (const resolve of run.pending.values())
|
|
138
|
+
resolve({ ok: false, error: { code: 'executor_disconnected', message: 'server disconnected' } });
|
|
139
|
+
}
|
|
140
|
+
runs.clear();
|
|
141
|
+
});
|
|
142
|
+
}
|
|
143
|
+
startRun(frame, runs, send) {
|
|
144
|
+
const state = { capability: frame.capability, ac: new AbortController(), nextCallId: 1, pending: new Map() };
|
|
145
|
+
runs.set(frame.runId, state);
|
|
146
|
+
const bridge = {
|
|
147
|
+
call: (fn, kwargs) => new Promise((resolve) => {
|
|
148
|
+
if (state.ac.signal.aborted)
|
|
149
|
+
return resolve({ ok: false, error: { code: 'cancelled', message: 'run cancelled' } });
|
|
150
|
+
const callId = state.nextCallId++;
|
|
151
|
+
state.pending.set(callId, resolve);
|
|
152
|
+
try {
|
|
153
|
+
send({ type: 'call', runId: frame.runId, capability: state.capability, callId, fn, kwargs });
|
|
154
|
+
}
|
|
155
|
+
catch (err) {
|
|
156
|
+
state.pending.delete(callId);
|
|
157
|
+
resolve({ ok: false, error: { code: 'invalid_args', message: err instanceof Error ? err.message : 'call too large' } });
|
|
158
|
+
}
|
|
159
|
+
}),
|
|
160
|
+
};
|
|
161
|
+
const { type: _t, ...req } = frame;
|
|
162
|
+
const t0 = Date.now();
|
|
163
|
+
void this.opts.runner
|
|
164
|
+
.run(req, bridge, state.ac.signal)
|
|
165
|
+
.then((result) => {
|
|
166
|
+
runs.delete(frame.runId);
|
|
167
|
+
this.log.debug({ runId: frame.runId, status: result.status, ms: Date.now() - t0, toolCalls: result.stats.toolCalls }, 'run finished');
|
|
168
|
+
try {
|
|
169
|
+
send({ type: 'done', runId: frame.runId, ...result });
|
|
170
|
+
}
|
|
171
|
+
catch {
|
|
172
|
+
send({ type: 'done', runId: frame.runId, ...result, value: undefined, truncated: true, preview: '' });
|
|
173
|
+
}
|
|
174
|
+
})
|
|
175
|
+
.catch((err) => {
|
|
176
|
+
runs.delete(frame.runId);
|
|
177
|
+
this.log.error({ runId: frame.runId, err }, 'run failed unexpectedly');
|
|
178
|
+
send({ type: 'done', runId: frame.runId, status: 'crashed', valueBytes: 0, error: { type: 'executor_error', message: String(err) }, stats: { wallMs: Date.now() - t0, suspensions: 0, toolCalls: 0 }, stdout: '' });
|
|
179
|
+
});
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
//# sourceMappingURL=server.js.map
|