@trama-dev/runtime 0.1.0 → 0.1.1
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/agent.d.ts +1 -1
- package/dist/agent.js +8 -9
- package/dist/client.js +7 -2
- package/dist/context.js +6 -42
- package/dist/index.d.ts +1 -0
- package/dist/index.js +71 -39
- package/dist/pi-adapter.d.ts +9 -1
- package/dist/pi-adapter.js +59 -9
- package/dist/runner.d.ts +14 -1
- package/dist/runner.js +267 -121
- package/dist/serializable.d.ts +8 -0
- package/dist/serializable.js +40 -0
- package/dist/tools.d.ts +5 -1
- package/dist/tools.js +177 -21
- package/package.json +1 -1
package/dist/runner.js
CHANGED
|
@@ -1,13 +1,13 @@
|
|
|
1
1
|
import { createServer } from "http";
|
|
2
2
|
import { spawn } from "child_process";
|
|
3
|
-
import { readFileSync, writeFileSync, appendFileSync, readdirSync, copyFileSync, mkdirSync, existsSync, symlinkSync, rmSync, lstatSync, readlinkSync, } from "fs";
|
|
3
|
+
import { readFileSync, writeFileSync, appendFileSync, readdirSync, copyFileSync, mkdirSync, existsSync, symlinkSync, rmSync, lstatSync, readlinkSync, cpSync, mkdtempSync, } from "fs";
|
|
4
4
|
import { join, dirname } from "path";
|
|
5
|
-
import { homedir } from "os";
|
|
5
|
+
import { homedir, tmpdir } from "os";
|
|
6
6
|
import { fileURLToPath } from "url";
|
|
7
7
|
import { PiAdapter } from "./pi-adapter.js";
|
|
8
8
|
import { createContext } from "./context.js";
|
|
9
9
|
import { createAgent } from "./agent.js";
|
|
10
|
-
import { createTools } from "./tools.js";
|
|
10
|
+
import { createTools, cappedBuffer } from "./tools.js";
|
|
11
11
|
// --- Module resolution for child processes ---
|
|
12
12
|
/**
|
|
13
13
|
* Find the node_modules directory that contains @trama-dev/runtime.
|
|
@@ -52,8 +52,7 @@ function ensureRuntimeLink(projectDir) {
|
|
|
52
52
|
}
|
|
53
53
|
}
|
|
54
54
|
catch (err) {
|
|
55
|
-
|
|
56
|
-
if (err instanceof Error && !("code" in err))
|
|
55
|
+
if (err.code !== "ENOENT")
|
|
57
56
|
throw err;
|
|
58
57
|
// ENOENT — path doesn't exist, proceed to create
|
|
59
58
|
}
|
|
@@ -67,18 +66,23 @@ function ensureRuntimeLink(projectDir) {
|
|
|
67
66
|
function ensureProjectScaffold(projectDir) {
|
|
68
67
|
const pkgPath = join(projectDir, "package.json");
|
|
69
68
|
if (existsSync(pkgPath)) {
|
|
69
|
+
let pkg;
|
|
70
70
|
try {
|
|
71
|
-
|
|
72
|
-
if (pkg.type !== "module") {
|
|
73
|
-
pkg.type = "module";
|
|
74
|
-
writeFileSync(pkgPath, JSON.stringify(pkg, null, 2));
|
|
75
|
-
}
|
|
71
|
+
pkg = JSON.parse(readFileSync(pkgPath, "utf-8"));
|
|
76
72
|
}
|
|
77
73
|
catch (err) {
|
|
78
74
|
throw new Error(`Malformed package.json at ${pkgPath}. ` +
|
|
79
75
|
`trama will not overwrite it automatically; fix or remove it and try again.\n` +
|
|
80
76
|
`Parse error: ${err instanceof Error ? err.message : err}`);
|
|
81
77
|
}
|
|
78
|
+
if (typeof pkg !== "object" || pkg === null || Array.isArray(pkg)) {
|
|
79
|
+
throw new Error(`Malformed package.json at ${pkgPath} — expected a JSON object but got ${Array.isArray(pkg) ? "an array" : typeof pkg}. trama will not overwrite it automatically; fix or remove it and try again.`);
|
|
80
|
+
}
|
|
81
|
+
const pkgObj = pkg;
|
|
82
|
+
if (pkgObj.type !== "module") {
|
|
83
|
+
pkgObj.type = "module";
|
|
84
|
+
writeFileSync(pkgPath, JSON.stringify(pkgObj, null, 2));
|
|
85
|
+
}
|
|
82
86
|
}
|
|
83
87
|
else {
|
|
84
88
|
writeFileSync(pkgPath, JSON.stringify({ type: "module" }, null, 2));
|
|
@@ -98,6 +102,13 @@ function ensureProjectScaffold(projectDir) {
|
|
|
98
102
|
}
|
|
99
103
|
}
|
|
100
104
|
// --- Runtime type definitions (included in system prompts) ---
|
|
105
|
+
/**
|
|
106
|
+
* Simplified API reference for LLM system prompts.
|
|
107
|
+
* NOT the canonical type definitions (those live in types.ts).
|
|
108
|
+
* Kept as a readable string rather than auto-generated, because the LLM
|
|
109
|
+
* needs a concise reference, not the full implementation types.
|
|
110
|
+
* If types.ts changes, review whether this summary needs updating.
|
|
111
|
+
*/
|
|
101
112
|
export const RUNTIME_TYPES = `// @trama-dev/runtime - Complete API
|
|
102
113
|
|
|
103
114
|
export interface Ctx {
|
|
@@ -149,26 +160,62 @@ export function loadConfig() {
|
|
|
149
160
|
defaultTimeout: 300_000,
|
|
150
161
|
defaultMaxIterations: 100,
|
|
151
162
|
};
|
|
163
|
+
let raw;
|
|
152
164
|
try {
|
|
153
|
-
|
|
165
|
+
raw = readFileSync(configPath, "utf-8");
|
|
154
166
|
}
|
|
155
|
-
catch {
|
|
156
|
-
|
|
167
|
+
catch (err) {
|
|
168
|
+
if (err.code === "ENOENT")
|
|
169
|
+
return defaults;
|
|
170
|
+
throw err;
|
|
157
171
|
}
|
|
172
|
+
let parsed;
|
|
173
|
+
try {
|
|
174
|
+
parsed = JSON.parse(raw);
|
|
175
|
+
}
|
|
176
|
+
catch (err) {
|
|
177
|
+
throw new Error(`Malformed config at ${configPath} — fix or delete it.\n` +
|
|
178
|
+
`Parse error: ${err instanceof Error ? err.message : err}`);
|
|
179
|
+
}
|
|
180
|
+
if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
|
|
181
|
+
throw new Error(`Malformed config at ${configPath} — expected a JSON object but got ${Array.isArray(parsed) ? "an array" : typeof parsed}. Fix or delete it to proceed.`);
|
|
182
|
+
}
|
|
183
|
+
const merged = { ...defaults, ...parsed };
|
|
184
|
+
const s = (v) => typeof v === "string" && v.length > 0;
|
|
185
|
+
const pint = (v) => Number.isInteger(v) && v > 0;
|
|
186
|
+
const checks = [
|
|
187
|
+
[s(merged.provider), `"provider" must be a non-empty string (got ${JSON.stringify(merged.provider)})`],
|
|
188
|
+
[s(merged.model), `"model" must be a non-empty string (got ${JSON.stringify(merged.model)})`],
|
|
189
|
+
[Number.isInteger(merged.maxRepairAttempts) && merged.maxRepairAttempts >= 0, `"maxRepairAttempts" must be a non-negative integer (got ${merged.maxRepairAttempts})`],
|
|
190
|
+
[Number.isFinite(merged.defaultTimeout) && merged.defaultTimeout > 0, `"defaultTimeout" must be a positive number (got ${merged.defaultTimeout})`],
|
|
191
|
+
[pint(merged.defaultMaxIterations), `"defaultMaxIterations" must be a positive integer (got ${merged.defaultMaxIterations})`],
|
|
192
|
+
];
|
|
193
|
+
for (const [ok, msg] of checks) {
|
|
194
|
+
if (!ok)
|
|
195
|
+
throw new Error(`Invalid config: ${msg}`);
|
|
196
|
+
}
|
|
197
|
+
return merged;
|
|
158
198
|
}
|
|
159
199
|
export function loadState(projectDir) {
|
|
160
200
|
const statePath = join(projectDir, "state.json");
|
|
161
201
|
if (!existsSync(statePath))
|
|
162
202
|
return {};
|
|
163
203
|
const raw = readFileSync(statePath, "utf-8");
|
|
204
|
+
const fail = (reason) => {
|
|
205
|
+
throw new Error(`Corrupt state.json in ${projectDir} — cannot safely continue.\n${reason}\n` +
|
|
206
|
+
`Back up or delete state.json to reset state.`);
|
|
207
|
+
};
|
|
208
|
+
let parsed;
|
|
164
209
|
try {
|
|
165
|
-
|
|
210
|
+
parsed = JSON.parse(raw);
|
|
166
211
|
}
|
|
167
212
|
catch (err) {
|
|
168
|
-
|
|
169
|
-
`Parse error: ${err instanceof Error ? err.message : err}\n` +
|
|
170
|
-
`Back up or delete state.json to reset state.`);
|
|
213
|
+
fail(`Parse error: ${err instanceof Error ? err.message : err}`);
|
|
171
214
|
}
|
|
215
|
+
if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
|
|
216
|
+
fail(`Expected a JSON object but got ${Array.isArray(parsed) ? "array" : typeof parsed}.`);
|
|
217
|
+
}
|
|
218
|
+
return parsed;
|
|
172
219
|
}
|
|
173
220
|
// --- IPC Server ---
|
|
174
221
|
function createIPCServer(ctx, agentImpl, toolsImpl) {
|
|
@@ -208,14 +255,14 @@ function createIPCServer(ctx, agentImpl, toolsImpl) {
|
|
|
208
255
|
case "/tools/shell":
|
|
209
256
|
result = await toolsImpl.shell(data.command, { cwd: data.cwd, timeout: data.timeout });
|
|
210
257
|
res.writeHead(200, { "Content-Type": "application/json" });
|
|
211
|
-
res.end(JSON.stringify(result));
|
|
258
|
+
res.end(JSON.stringify({ result }));
|
|
212
259
|
break;
|
|
213
260
|
case "/tools/fetch":
|
|
214
261
|
result = await toolsImpl.fetch(data.url, {
|
|
215
262
|
method: data.method, headers: data.headers, body: data.body,
|
|
216
263
|
});
|
|
217
264
|
res.writeHead(200, { "Content-Type": "application/json" });
|
|
218
|
-
res.end(JSON.stringify(result));
|
|
265
|
+
res.end(JSON.stringify({ result }));
|
|
219
266
|
break;
|
|
220
267
|
case "/ctx/checkpoint":
|
|
221
268
|
ctx.state = data.state;
|
|
@@ -240,7 +287,8 @@ function createIPCServer(ctx, agentImpl, toolsImpl) {
|
|
|
240
287
|
}
|
|
241
288
|
}
|
|
242
289
|
catch (err) {
|
|
243
|
-
res.
|
|
290
|
+
if (!res.headersSent)
|
|
291
|
+
res.writeHead(500);
|
|
244
292
|
res.end(String(err));
|
|
245
293
|
}
|
|
246
294
|
});
|
|
@@ -262,11 +310,19 @@ function startServer(server) {
|
|
|
262
310
|
}
|
|
263
311
|
function closeServer(server) {
|
|
264
312
|
return new Promise((resolve, reject) => {
|
|
265
|
-
server.close(err =>
|
|
313
|
+
server.close(err => {
|
|
314
|
+
if (!err || err.code === "ERR_SERVER_NOT_RUNNING") {
|
|
315
|
+
resolve();
|
|
316
|
+
}
|
|
317
|
+
else {
|
|
318
|
+
reject(err);
|
|
319
|
+
}
|
|
320
|
+
});
|
|
266
321
|
});
|
|
267
322
|
}
|
|
268
|
-
/**
|
|
269
|
-
function forceCloseServer(server, toolsImpl) {
|
|
323
|
+
/** Abort in-flight operations, kill orphan shells, drop HTTP connections, then close. */
|
|
324
|
+
function forceCloseServer(server, toolsImpl, abortController) {
|
|
325
|
+
abortController?.abort();
|
|
270
326
|
toolsImpl.killActiveShells();
|
|
271
327
|
server.closeAllConnections();
|
|
272
328
|
return closeServer(server);
|
|
@@ -278,40 +334,46 @@ function forceCloseServer(server, toolsImpl) {
|
|
|
278
334
|
*/
|
|
279
335
|
function waitForChild(child, timeout, sinks) {
|
|
280
336
|
return new Promise((resolve, reject) => {
|
|
281
|
-
|
|
282
|
-
|
|
337
|
+
const out = cappedBuffer();
|
|
338
|
+
const err = cappedBuffer();
|
|
283
339
|
let timedOut = false;
|
|
284
340
|
let exited = false;
|
|
341
|
+
let killFallbackTimer = null;
|
|
285
342
|
child.stdout?.on("data", (chunk) => {
|
|
286
343
|
const text = chunk.toString();
|
|
287
|
-
|
|
344
|
+
out.append(text);
|
|
288
345
|
sinks?.stdout?.(text);
|
|
289
346
|
});
|
|
290
347
|
child.stderr?.on("data", (chunk) => {
|
|
291
348
|
const text = chunk.toString();
|
|
292
|
-
|
|
349
|
+
err.append(text);
|
|
293
350
|
sinks?.stderr?.(text);
|
|
294
351
|
});
|
|
295
352
|
const timer = setTimeout(() => {
|
|
296
353
|
timedOut = true;
|
|
297
354
|
child.kill("SIGTERM");
|
|
298
|
-
setTimeout(() => {
|
|
355
|
+
killFallbackTimer = setTimeout(() => {
|
|
299
356
|
if (!exited)
|
|
300
357
|
child.kill("SIGKILL");
|
|
301
358
|
}, 5000);
|
|
359
|
+
killFallbackTimer.unref?.();
|
|
302
360
|
}, timeout);
|
|
303
361
|
child.on("error", (err) => {
|
|
304
362
|
clearTimeout(timer);
|
|
363
|
+
if (killFallbackTimer)
|
|
364
|
+
clearTimeout(killFallbackTimer);
|
|
305
365
|
reject(err);
|
|
306
366
|
});
|
|
307
367
|
child.on("close", (code) => {
|
|
308
368
|
exited = true;
|
|
309
369
|
clearTimeout(timer);
|
|
370
|
+
if (killFallbackTimer)
|
|
371
|
+
clearTimeout(killFallbackTimer);
|
|
310
372
|
if (timedOut) {
|
|
311
|
-
resolve({ exitCode: 1, stdout, stderr:
|
|
373
|
+
resolve({ exitCode: 1, stdout: out.value, stderr: err.value + "\n[trama] program killed: timeout" });
|
|
312
374
|
}
|
|
313
375
|
else {
|
|
314
|
-
resolve({ exitCode: code ?? 1, stdout, stderr });
|
|
376
|
+
resolve({ exitCode: code ?? 1, stdout: out.value, stderr: err.value });
|
|
315
377
|
}
|
|
316
378
|
});
|
|
317
379
|
});
|
|
@@ -325,10 +387,10 @@ function waitForChild(child, timeout, sinks) {
|
|
|
325
387
|
*/
|
|
326
388
|
export function copyToHistory(projectDir, reason, detail) {
|
|
327
389
|
const historyDir = join(projectDir, "history");
|
|
328
|
-
const existing = readdirSync(historyDir).filter(f => /^\d
|
|
390
|
+
const existing = readdirSync(historyDir).filter(f => /^\d+\.ts$/.test(f));
|
|
329
391
|
const nums = existing.map(f => parseInt(f.replace(".ts", ""), 10));
|
|
330
392
|
const nextNum = nums.length > 0 ? Math.max(...nums) + 1 : 1;
|
|
331
|
-
const next = String(nextNum).padStart(4, "0");
|
|
393
|
+
const next = String(nextNum).padStart(Math.max(4, String(nextNum).length), "0");
|
|
332
394
|
copyFileSync(join(projectDir, "program.ts"), join(historyDir, `${next}.ts`));
|
|
333
395
|
const entry = { version: nextNum, reason, timestamp: new Date().toISOString() };
|
|
334
396
|
if (reason === "repair" && detail)
|
|
@@ -337,63 +399,186 @@ export function copyToHistory(projectDir, reason, detail) {
|
|
|
337
399
|
entry.prompt = detail;
|
|
338
400
|
appendFileSync(join(historyDir, "index.jsonl"), JSON.stringify(entry) + "\n");
|
|
339
401
|
}
|
|
340
|
-
// ---
|
|
341
|
-
|
|
402
|
+
// --- Helpers ---
|
|
403
|
+
/** Run fn in a temp directory, clean up afterwards regardless of outcome. */
|
|
404
|
+
export async function withTempDir(prefix, fn) {
|
|
405
|
+
const dir = mkdtempSync(join(tmpdir(), prefix));
|
|
406
|
+
try {
|
|
407
|
+
return await fn(dir);
|
|
408
|
+
}
|
|
409
|
+
finally {
|
|
410
|
+
rmSync(dir, { recursive: true, force: true });
|
|
411
|
+
}
|
|
412
|
+
}
|
|
413
|
+
/**
|
|
414
|
+
* Attempt a single repair call with its own timeout and cancellation.
|
|
415
|
+
* Returns true if repair succeeded, false if it failed (error is appended to repairErrors).
|
|
416
|
+
*/
|
|
417
|
+
async function repairWithTimeout(adapter, input, timeout, repairErrors) {
|
|
418
|
+
const controller = new AbortController();
|
|
419
|
+
const timer = setTimeout(() => controller.abort(), timeout);
|
|
420
|
+
try {
|
|
421
|
+
return await adapter.repair(input, controller.signal);
|
|
422
|
+
}
|
|
423
|
+
catch (err) {
|
|
424
|
+
repairErrors.push(err instanceof Error ? err.message : String(err));
|
|
425
|
+
return null;
|
|
426
|
+
}
|
|
427
|
+
finally {
|
|
428
|
+
clearTimeout(timer);
|
|
429
|
+
}
|
|
430
|
+
}
|
|
431
|
+
async function executeProgram(options) {
|
|
432
|
+
const { projectDir, adapter, maxRepairAttempts, timeout, maxIterations } = options;
|
|
342
433
|
mkdirSync(join(projectDir, "history"), { recursive: true });
|
|
343
434
|
mkdirSync(join(projectDir, "logs"), { recursive: true });
|
|
344
435
|
ensureProjectScaffold(projectDir);
|
|
345
436
|
ensureRuntimeLink(projectDir);
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
const
|
|
437
|
+
writeFileSync(join(projectDir, "logs", "latest.jsonl"), "");
|
|
438
|
+
const originalSource = readFileSync(join(projectDir, "program.ts"), "utf-8");
|
|
439
|
+
const repairErrors = [];
|
|
440
|
+
const repairDetails = () => repairErrors.length > 0
|
|
441
|
+
? `\nRepair errors:\n${repairErrors.map((e, i) => ` [${i + 1}] ${e}`).join("\n")}` : "";
|
|
442
|
+
let pendingRepair = null;
|
|
443
|
+
let programModified = false;
|
|
444
|
+
try {
|
|
445
|
+
for (let attempt = 0; attempt <= maxRepairAttempts; attempt++) {
|
|
446
|
+
const abortController = new AbortController();
|
|
447
|
+
const { signal } = abortController;
|
|
448
|
+
const ctx = createContext(projectDir, loadState(projectDir), { maxIterations });
|
|
449
|
+
const agentImpl = createAgent(adapter, signal);
|
|
450
|
+
const toolsImpl = createTools(projectDir, signal);
|
|
451
|
+
const server = createIPCServer(ctx, agentImpl, toolsImpl);
|
|
452
|
+
// Phase A: Infrastructure setup — errors here are NOT program bugs,
|
|
453
|
+
// so they must NOT trigger the repair loop. (H1 fix)
|
|
454
|
+
let port;
|
|
455
|
+
try {
|
|
456
|
+
port = await startServer(server);
|
|
457
|
+
}
|
|
458
|
+
catch (infraError) {
|
|
459
|
+
await forceCloseServer(server, toolsImpl, abortController);
|
|
460
|
+
throw infraError;
|
|
461
|
+
}
|
|
356
462
|
const child = spawn(process.execPath, [TSX_CLI, join(projectDir, "program.ts")], {
|
|
357
463
|
cwd: projectDir,
|
|
358
464
|
env: {
|
|
359
465
|
...process.env,
|
|
360
466
|
TRAMA_PORT: String(port),
|
|
361
|
-
TRAMA_INPUT: JSON.stringify(
|
|
467
|
+
TRAMA_INPUT: JSON.stringify(ctx.input),
|
|
362
468
|
TRAMA_STATE: JSON.stringify(ctx.state),
|
|
363
469
|
TRAMA_ITERATION: String(ctx.iteration),
|
|
364
470
|
TRAMA_MAX_ITERATIONS: String(ctx.maxIterations),
|
|
365
471
|
},
|
|
366
472
|
stdio: ["pipe", "pipe", "pipe"],
|
|
367
473
|
});
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
474
|
+
// Phase B: Program execution.
|
|
475
|
+
// waitForChild rejects on spawn errors (ENOENT, EACCES) — those are
|
|
476
|
+
// infrastructure failures and must NOT trigger repair.
|
|
477
|
+
let result;
|
|
478
|
+
try {
|
|
479
|
+
result = await waitForChild(child, timeout, {
|
|
480
|
+
stdout: chunk => { process.stdout.write(chunk); },
|
|
481
|
+
stderr: chunk => { process.stderr.write(chunk); },
|
|
482
|
+
});
|
|
483
|
+
}
|
|
484
|
+
catch (spawnError) {
|
|
485
|
+
// Child process failed to start — not a program bug.
|
|
486
|
+
await forceCloseServer(server, toolsImpl, abortController);
|
|
487
|
+
throw spawnError;
|
|
488
|
+
}
|
|
371
489
|
if (result.exitCode === 0) {
|
|
372
|
-
|
|
490
|
+
// Repair is verified — program.ts is now the canonical source.
|
|
491
|
+
programModified = false;
|
|
492
|
+
// Program succeeded. Server cleanup failure is not a program bug.
|
|
493
|
+
try {
|
|
494
|
+
await closeServer(server);
|
|
495
|
+
}
|
|
496
|
+
catch {
|
|
497
|
+
await forceCloseServer(server, toolsImpl, abortController);
|
|
498
|
+
}
|
|
499
|
+
if (pendingRepair) {
|
|
500
|
+
options.onRepair?.(pendingRepair.attempt, maxRepairAttempts, pendingRepair.error);
|
|
501
|
+
}
|
|
373
502
|
return;
|
|
374
503
|
}
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
504
|
+
// Program failed — this is the only path that may trigger repair.
|
|
505
|
+
try {
|
|
506
|
+
await forceCloseServer(server, toolsImpl, abortController);
|
|
507
|
+
}
|
|
508
|
+
catch { /* best-effort cleanup */ }
|
|
509
|
+
const programError = new Error(`program.ts exited with code ${result.exitCode}\n` +
|
|
510
|
+
`stdout: ${result.stdout}\n` +
|
|
511
|
+
`stderr: ${result.stderr}`);
|
|
512
|
+
// Previous repair candidate failed — don't record it.
|
|
513
|
+
pendingRepair = null;
|
|
514
|
+
if (attempt === maxRepairAttempts) {
|
|
515
|
+
throw new Error(`Failed after ${maxRepairAttempts} repair attempts: ${programError}${repairDetails()}`);
|
|
381
516
|
}
|
|
382
|
-
appendFileSync(join(projectDir, "history", "index.jsonl"), JSON.stringify({
|
|
383
|
-
reason: `${reason}-repair`,
|
|
384
|
-
timestamp: new Date().toISOString(),
|
|
385
|
-
error: String(error),
|
|
386
|
-
}) + "\n");
|
|
387
517
|
const source = readFileSync(join(projectDir, "program.ts"), "utf-8");
|
|
388
|
-
const fixed = await adapter
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
518
|
+
const fixed = await repairWithTimeout(adapter, { programSource: source, error: String(programError), runtimeTypes: RUNTIME_TYPES }, timeout, repairErrors);
|
|
519
|
+
if (fixed !== null) {
|
|
520
|
+
writeFileSync(join(projectDir, "program.ts"), fixed);
|
|
521
|
+
programModified = true;
|
|
522
|
+
pendingRepair = { attempt, error: String(programError) };
|
|
523
|
+
}
|
|
524
|
+
else {
|
|
525
|
+
// Repair LLM call itself failed — don't re-run the same broken program.
|
|
526
|
+
throw new Error(`Failed after ${attempt + 1} repair attempt(s): ${programError}${repairDetails()}`);
|
|
527
|
+
}
|
|
395
528
|
}
|
|
396
529
|
}
|
|
530
|
+
catch (err) {
|
|
531
|
+
if (programModified) {
|
|
532
|
+
try {
|
|
533
|
+
writeFileSync(join(projectDir, "program.ts"), originalSource);
|
|
534
|
+
}
|
|
535
|
+
catch { /* best-effort */ }
|
|
536
|
+
}
|
|
537
|
+
throw err;
|
|
538
|
+
}
|
|
539
|
+
}
|
|
540
|
+
// --- Smoke run (used by create and update) ---
|
|
541
|
+
/** Copy new history entries from src to dst (appends only entries added after the shared prefix). */
|
|
542
|
+
function propagateHistoryEntries(srcDir, dstDir) {
|
|
543
|
+
const srcPath = join(srcDir, "history", "index.jsonl");
|
|
544
|
+
const dstPath = join(dstDir, "history", "index.jsonl");
|
|
545
|
+
if (!existsSync(srcPath))
|
|
546
|
+
return;
|
|
547
|
+
const srcHistory = readFileSync(srcPath, "utf-8");
|
|
548
|
+
const dstHistory = existsSync(dstPath) ? readFileSync(dstPath, "utf-8") : "";
|
|
549
|
+
if (!srcHistory.startsWith(dstHistory))
|
|
550
|
+
return; // History diverged — cannot safely propagate
|
|
551
|
+
const newEntries = srcHistory.slice(dstHistory.length);
|
|
552
|
+
if (newEntries.length > 0) {
|
|
553
|
+
mkdirSync(join(dstDir, "history"), { recursive: true });
|
|
554
|
+
appendFileSync(dstPath, newEntries);
|
|
555
|
+
}
|
|
556
|
+
}
|
|
557
|
+
export async function smokeRunAndRepair(projectDir, adapter, reason, options) {
|
|
558
|
+
const smokeTimeout = options?.timeout ?? 30_000;
|
|
559
|
+
// Run validation in a temp copy so side effects don't persist in the real project
|
|
560
|
+
await withTempDir("trama-smoke-", async (smokeDir) => {
|
|
561
|
+
cpSync(projectDir, smokeDir, { recursive: true });
|
|
562
|
+
const smokeAdapter = adapter.withCwd(smokeDir);
|
|
563
|
+
try {
|
|
564
|
+
await executeProgram({
|
|
565
|
+
projectDir: smokeDir,
|
|
566
|
+
adapter: smokeAdapter,
|
|
567
|
+
maxRepairAttempts: options?.maxRepairAttempts ?? 3,
|
|
568
|
+
timeout: smokeTimeout,
|
|
569
|
+
maxIterations: options?.maxIterations ?? 100,
|
|
570
|
+
onRepair(_attempt, _max, error) {
|
|
571
|
+
appendFileSync(join(smokeDir, "history", "index.jsonl"), JSON.stringify({ reason: `${reason}-repair`, timestamp: new Date().toISOString(), error }) + "\n");
|
|
572
|
+
},
|
|
573
|
+
});
|
|
574
|
+
// Smoke passed — copy back program.ts (may have been repaired)
|
|
575
|
+
copyFileSync(join(smokeDir, "program.ts"), join(projectDir, "program.ts"));
|
|
576
|
+
}
|
|
577
|
+
finally {
|
|
578
|
+
// Always propagate repair history, whether smoke passed or failed
|
|
579
|
+
propagateHistoryEntries(smokeDir, projectDir);
|
|
580
|
+
}
|
|
581
|
+
});
|
|
397
582
|
}
|
|
398
583
|
// --- Core execution ---
|
|
399
584
|
export async function runProgram(options) {
|
|
@@ -412,59 +597,20 @@ export async function runProgram(options) {
|
|
|
412
597
|
if (!Number.isInteger(maxRepairAttempts) || maxRepairAttempts < 0) {
|
|
413
598
|
throw new Error(`Invalid maxRepairAttempts: ${maxRepairAttempts}. Must be a non-negative integer.`);
|
|
414
599
|
}
|
|
415
|
-
mkdirSync(join(projectDir, "history"), { recursive: true });
|
|
416
|
-
mkdirSync(join(projectDir, "logs"), { recursive: true });
|
|
417
|
-
ensureProjectScaffold(projectDir);
|
|
418
|
-
ensureRuntimeLink(projectDir);
|
|
419
600
|
const adapter = new PiAdapter(config, projectDir);
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
const
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
TRAMA_INPUT: JSON.stringify(meta.input),
|
|
436
|
-
TRAMA_STATE: JSON.stringify(ctx.state),
|
|
437
|
-
TRAMA_ITERATION: String(ctx.iteration),
|
|
438
|
-
TRAMA_MAX_ITERATIONS: String(ctx.maxIterations),
|
|
439
|
-
},
|
|
440
|
-
stdio: ["pipe", "pipe", "pipe"],
|
|
441
|
-
});
|
|
442
|
-
const result = await waitForChild(child, timeout, {
|
|
443
|
-
stdout: chunk => { process.stdout.write(chunk); },
|
|
444
|
-
});
|
|
445
|
-
if (result.exitCode === 0) {
|
|
446
|
-
await closeServer(server);
|
|
447
|
-
return;
|
|
448
|
-
}
|
|
449
|
-
throw new Error(`program.ts exited with code ${result.exitCode}\n` +
|
|
450
|
-
`stdout: ${result.stdout}\n` +
|
|
451
|
-
`stderr: ${result.stderr}`);
|
|
452
|
-
}
|
|
453
|
-
catch (error) {
|
|
454
|
-
if (attempt === maxRepairAttempts) {
|
|
455
|
-
await forceCloseServer(server, toolsImpl);
|
|
456
|
-
throw new Error(`Failed after ${maxRepairAttempts} repair attempts: ${error}`);
|
|
457
|
-
}
|
|
458
|
-
await ctx.log(`Repair attempt ${attempt + 1}/${maxRepairAttempts}`, { error: String(error) });
|
|
459
|
-
const source = readFileSync(join(projectDir, "program.ts"), "utf-8");
|
|
460
|
-
const fixed = await adapter.repair({
|
|
461
|
-
programSource: source,
|
|
462
|
-
error: String(error),
|
|
463
|
-
runtimeTypes: RUNTIME_TYPES,
|
|
464
|
-
});
|
|
465
|
-
writeFileSync(join(projectDir, "program.ts"), fixed);
|
|
466
|
-
copyToHistory(projectDir, "repair", String(error));
|
|
467
|
-
await forceCloseServer(server, toolsImpl);
|
|
468
|
-
}
|
|
469
|
-
}
|
|
601
|
+
await executeProgram({
|
|
602
|
+
projectDir,
|
|
603
|
+
adapter,
|
|
604
|
+
maxRepairAttempts,
|
|
605
|
+
timeout,
|
|
606
|
+
maxIterations,
|
|
607
|
+
onRepair(attempt, max, error) {
|
|
608
|
+
// Log repair attempts (appends to already-open logs file)
|
|
609
|
+
const logsPath = join(projectDir, "logs", "latest.jsonl");
|
|
610
|
+
const entry = { ts: Date.now(), message: `Repair attempt ${attempt + 1}/${max}`, data: { error } };
|
|
611
|
+
appendFileSync(logsPath, JSON.stringify(entry) + "\n");
|
|
612
|
+
console.log(`[trama] Repair attempt ${attempt + 1}/${max}`);
|
|
613
|
+
copyToHistory(projectDir, "repair", error);
|
|
614
|
+
},
|
|
615
|
+
});
|
|
470
616
|
}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Recursively check that a value is strictly JSON-serializable.
|
|
3
|
+
* Throws TypeError with the path to the offending value.
|
|
4
|
+
*
|
|
5
|
+
* Uses a stack (ancestor chain) instead of a flat set so that shared-but-
|
|
6
|
+
* non-circular structures like { a: shared, b: shared } pass validation.
|
|
7
|
+
*/
|
|
8
|
+
export declare function assertSerializable(value: unknown, path: string, ancestors?: Set<unknown>): void;
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Recursively check that a value is strictly JSON-serializable.
|
|
3
|
+
* Throws TypeError with the path to the offending value.
|
|
4
|
+
*
|
|
5
|
+
* Uses a stack (ancestor chain) instead of a flat set so that shared-but-
|
|
6
|
+
* non-circular structures like { a: shared, b: shared } pass validation.
|
|
7
|
+
*/
|
|
8
|
+
export function assertSerializable(value, path, ancestors = new Set()) {
|
|
9
|
+
if (value === null || typeof value === "string" || typeof value === "boolean") {
|
|
10
|
+
return;
|
|
11
|
+
}
|
|
12
|
+
if (typeof value === "number") {
|
|
13
|
+
if (!Number.isFinite(value)) {
|
|
14
|
+
throw new TypeError(`${path} is not JSON-serializable (${value})`);
|
|
15
|
+
}
|
|
16
|
+
return;
|
|
17
|
+
}
|
|
18
|
+
if (typeof value === "undefined" || typeof value === "function" || typeof value === "symbol" || typeof value === "bigint") {
|
|
19
|
+
throw new TypeError(`${path} is not JSON-serializable (${typeof value})`);
|
|
20
|
+
}
|
|
21
|
+
if (ancestors.has(value)) {
|
|
22
|
+
throw new TypeError(`${path} contains a circular reference`);
|
|
23
|
+
}
|
|
24
|
+
ancestors.add(value);
|
|
25
|
+
if (Array.isArray(value)) {
|
|
26
|
+
for (let i = 0; i < value.length; i++) {
|
|
27
|
+
assertSerializable(value[i], `${path}[${i}]`, ancestors);
|
|
28
|
+
}
|
|
29
|
+
ancestors.delete(value);
|
|
30
|
+
return;
|
|
31
|
+
}
|
|
32
|
+
if (Object.getPrototypeOf(value) !== Object.prototype) {
|
|
33
|
+
const name = value.constructor?.name ?? "unknown";
|
|
34
|
+
throw new TypeError(`${path} is not a plain object (${name})`);
|
|
35
|
+
}
|
|
36
|
+
for (const [k, v] of Object.entries(value)) {
|
|
37
|
+
assertSerializable(v, `${path}.${k}`, ancestors);
|
|
38
|
+
}
|
|
39
|
+
ancestors.delete(value);
|
|
40
|
+
}
|
package/dist/tools.d.ts
CHANGED
|
@@ -1,6 +1,10 @@
|
|
|
1
1
|
import type { Tools } from "./types.js";
|
|
2
|
+
export declare function cappedBuffer(): {
|
|
3
|
+
append(text: string): void;
|
|
4
|
+
readonly value: string;
|
|
5
|
+
};
|
|
2
6
|
export interface ToolsWithCleanup extends Tools {
|
|
3
7
|
/** Kill all in-flight shell processes. Called by runner on timeout/error. */
|
|
4
8
|
killActiveShells(): void;
|
|
5
9
|
}
|
|
6
|
-
export declare function createTools(projectDir: string): ToolsWithCleanup;
|
|
10
|
+
export declare function createTools(projectDir: string, signal?: AbortSignal): ToolsWithCleanup;
|