@trama-dev/runtime 0.3.0 → 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/dist/runner.js CHANGED
@@ -1,19 +1,20 @@
1
1
  import { spawn } from "child_process";
2
2
  import { readFileSync, writeFileSync, appendFileSync, readdirSync, copyFileSync, mkdirSync, existsSync, statSync, symlinkSync, rmSync, lstatSync, readlinkSync, cpSync, mkdtempSync, openSync, closeSync, realpathSync, } from "fs";
3
- import { join, dirname } from "path";
3
+ import { join, dirname, relative } from "path";
4
4
  import { homedir, tmpdir } from "os";
5
5
  import { fileURLToPath } from "url";
6
- import { randomBytes } from "crypto";
6
+ import { createHash, randomBytes } from "crypto";
7
+ import { rejectOnAbort } from "./agent-backend.js";
7
8
  import { PiAdapter } from "./pi-adapter.js";
8
9
  import { createContext } from "./context.js";
9
10
  import { createAgent, stripCodeFences } from "./agent.js";
10
11
  import { createTools } from "./tools.js";
11
12
  import { createWorkspace } from "./workspace.js";
12
13
  import { guardPath } from "./path-guard.js";
13
- import { createAllowance, stopGroups, superviseChild } from "./child-process.js";
14
- import { openBridge } from "./bridge-client.js";
15
- import { removeTempDir, removeWithThisProcess, stopWithThisProcess } from "./lifetime.js";
14
+ import { createAllowance, superviseChild } from "./child-process.js";
15
+ import { removeTempDir, removeWithThisProcess, requireWatchdog, stopGroups, stopWithThisProcess } from "./stopping.js";
16
16
  import { createIPCServer, listen, closeServer } from "./ipc-server.js";
17
+ import { JOURNAL_DIR, openJournal } from "./journal.js";
17
18
  // --- Locating the runtime itself ---
18
19
  /** The installed @trama-dev/runtime package — this file lives in its dist/. */
19
20
  const RUNTIME_PACKAGE_DIR = dirname(dirname(fileURLToPath(import.meta.url)));
@@ -141,6 +142,7 @@ export function loadConfig() {
141
142
  maxRepairAttempts: 3,
142
143
  defaultTimeout: 300_000,
143
144
  defaultMaxIterations: 100,
145
+ journalRuns: 20,
144
146
  };
145
147
  let raw;
146
148
  try {
@@ -171,6 +173,7 @@ export function loadConfig() {
171
173
  [Number.isInteger(merged.maxRepairAttempts) && merged.maxRepairAttempts >= 0, `"maxRepairAttempts" must be a non-negative integer (got ${merged.maxRepairAttempts})`],
172
174
  [Number.isFinite(merged.defaultTimeout) && merged.defaultTimeout > 0, `"defaultTimeout" must be a positive number (got ${merged.defaultTimeout})`],
173
175
  [pint(merged.defaultMaxIterations), `"defaultMaxIterations" must be a positive integer (got ${merged.defaultMaxIterations})`],
176
+ [Number.isInteger(merged.journalRuns) && merged.journalRuns >= 0, `"journalRuns" must be a non-negative integer (got ${merged.journalRuns})`],
174
177
  ];
175
178
  for (const [ok, msg] of checks) {
176
179
  if (!ok)
@@ -193,7 +196,10 @@ export function loadProjectConfig(projectDir) {
193
196
  * everything else is handed one and does not know which it is.
194
197
  */
195
198
  export function createBackend(config) {
196
- return new PiAdapter(config);
199
+ const backend = new PiAdapter(config);
200
+ // The interface promises that a cancelled call rejects, and a run's end
201
+ // waits on that. Every backend is held to it here, rather than trusted with it.
202
+ return { ask: (prompt, call) => rejectOnAbort(backend.ask(prompt, call), call.signal) };
197
203
  }
198
204
  export function loadState(projectDir) {
199
205
  const statePath = guardPath(projectDir, "state.json");
@@ -337,10 +343,19 @@ export async function withTempDir(prefix, fn) {
337
343
  settled();
338
344
  }
339
345
  }
340
- /** Copy a directory's contents into an existing one, keeping symlinks as they are written. */
346
+ /**
347
+ * Copy a directory's contents into an existing one, keeping symlinks as they
348
+ * are written. A project's journals stay behind: they are the record of its
349
+ * runs, not part of what a run works on, and a copy is where a run is tried.
350
+ */
341
351
  function copyDirInto(srcDir, dstDir) {
342
352
  // realpath: a project directory may itself be a symlink.
343
- cpSync(realpathSync(srcDir), dstDir, { recursive: true, verbatimSymlinks: true });
353
+ const source = realpathSync(srcDir);
354
+ cpSync(source, dstDir, {
355
+ recursive: true,
356
+ verbatimSymlinks: true,
357
+ filter: path => relative(source, path) !== JOURNAL_DIR,
358
+ });
344
359
  }
345
360
  /**
346
361
  * Run fn against a private copy of a directory. What fn does there stays
@@ -363,6 +378,46 @@ async function withStagedCopy(realDir, fn) {
363
378
  function tail(text, max = 20_000) {
364
379
  return text.length <= max ? text : `[… ${text.length - max} earlier characters omitted]\n${text.slice(-max)}`;
365
380
  }
381
+ /** A line as it is shown for a run: under the run's name, if it has one. */
382
+ const tagged = (label, line) => label ? `[${label}] ${line}` : line;
383
+ /** The longest stretch of output held back while waiting for its line to end. */
384
+ const MAX_HELD_LINE = 64 * 1024;
385
+ /** Put a label in front of each line written to a stream. `flush` writes out a last line that had no newline. */
386
+ function labelled(label, write) {
387
+ let held = "";
388
+ const flush = () => {
389
+ if (held)
390
+ write(tagged(label, held) + "\n");
391
+ held = "";
392
+ };
393
+ return {
394
+ sink(chunk) {
395
+ const end = chunk.lastIndexOf("\n");
396
+ if (end === -1) {
397
+ held += chunk;
398
+ if (held.length > MAX_HELD_LINE)
399
+ flush(); // a line with no end in sight is shown in pieces
400
+ return;
401
+ }
402
+ const lines = (held + chunk.slice(0, end)).split("\n");
403
+ held = chunk.slice(end + 1);
404
+ write(lines.map(line => tagged(label, line) + "\n").join(""));
405
+ },
406
+ flush,
407
+ };
408
+ }
409
+ /** How much of each of a program's output streams goes into the journal. */
410
+ const MAX_JOURNALLED_OUTPUT = 64 * 1024;
411
+ /** What identifies a program text without quoting it. */
412
+ function fingerprint(programPath) {
413
+ try {
414
+ const source = readFileSync(programPath);
415
+ return { sha256: createHash("sha256").update(source).digest("hex"), bytes: source.length };
416
+ }
417
+ catch {
418
+ return null; // no program to speak of; the attempt will say so itself
419
+ }
420
+ }
366
421
  const describeFailure = (r) => `program.ts exited with code ${r.exitCode}\nstdout: ${tail(r.stdout)}\nstderr: ${tail(r.stderr)}`;
367
422
  /**
368
423
  * Hand the program its starting state through a private temp file rather than
@@ -384,7 +439,7 @@ function toChildResult(exit) {
384
439
  const { stdout, stderr } = exit;
385
440
  if (exit.timedOut)
386
441
  return { exitCode: 1, stdout, stderr: stderr + "\n[trama] program killed: timeout" };
387
- // Stopped by us after ctx.ready() — going down on SIGTERM is the expected outcome.
442
+ // Stopped by us at the end of a validation — going down on SIGTERM is the expected outcome.
388
443
  if (exit.stopped && (exit.code === 0 || exit.signal === "SIGTERM"))
389
444
  return { exitCode: 0, stdout, stderr };
390
445
  return { exitCode: exit.code ?? 1, stdout, stderr };
@@ -419,26 +474,52 @@ function settle(projectDir, child, terminalSignal) {
419
474
  * (bad project, server or spawn failure) or left state.json unreadable.
420
475
  */
421
476
  async function runProgramOnce(options) {
422
- const { projectDir, backend, timeout, maxIterations, argsOverride, stopOnReady, workspaceDir } = options;
477
+ const { projectDir, backend, timeout, maxIterations, argsOverride, validating, workspaceDir, label, signal, journal } = options;
478
+ const attempt = options.attempt ?? 0;
479
+ if (signal?.aborted)
480
+ return { outcome: null, failure: "The run was stopped before its program started." };
481
+ requireWatchdog();
423
482
  ensureProjectScaffold(projectDir);
424
483
  // Cancels in-flight LLM calls, fetches and observes once the run is over.
425
484
  const runEnded = new AbortController();
426
- // Asks the program to stop once it has been ready for the grace period.
427
- const readyStop = new AbortController();
485
+ // Ends a validation: the program has shown what it had to, and is asked to stop.
486
+ const validated = new AbortController();
428
487
  let readyTimer = null;
429
488
  let terminalSignal = null;
430
489
  const ctx = createContext(projectDir, loadState(projectDir), {
431
490
  maxIterations,
432
491
  argsOverride,
433
- onReady: stopOnReady && (() => {
434
- readyTimer ??= setTimeout(() => readyStop.abort(), stopOnReady.graceMs).unref();
492
+ onReady: validating && (() => {
493
+ readyTimer ??= setTimeout(() => validated.abort(), validating.readyGraceMs).unref();
435
494
  }),
495
+ print: line => console.log(tagged(label, line)),
496
+ });
497
+ journal.note("attempt", {
498
+ attempt,
499
+ // Where it runs — a copy of the project, when a fix is being tried or a candidate validated.
500
+ dir: projectDir,
501
+ program: fingerprint(guardPath(projectDir, "program.ts")),
502
+ iteration: ctx.iteration,
503
+ resumed: ctx.resumed,
436
504
  });
437
505
  // Truncate logs only after preflight succeeds — preserves the prior run's
438
506
  // diagnostics if scaffolding, state loading, or context creation fails.
439
507
  writeFileSync(guardPath(projectDir, join("logs", "latest.jsonl")), "");
440
- // The program's own time. It stops while a run the program started is in flight.
508
+ // The program's own time. It stops while a run the program asked for is in flight.
441
509
  const allowance = createAllowance(timeout);
510
+ // Set when a validation ended because the program asked for another to be run.
511
+ let handedOff = false;
512
+ // Runs the program has asked for and that are still going. They belong to this run.
513
+ const nestedRuns = new Set();
514
+ const workspaces = new Map();
515
+ const workspaceAt = (dir) => {
516
+ let workspace = workspaces.get(dir);
517
+ if (!workspace)
518
+ workspaces.set(dir, workspace = createWorkspace(dir, runEnded.signal));
519
+ return workspace;
520
+ };
521
+ // The workspace of the session this run is part of, if it is part of one.
522
+ const sessionWorkspace = workspaceDir ? workspaceAt(workspaceDir) : null;
442
523
  const tools = createTools(projectDir, runEnded.signal);
443
524
  // Known only to this run's program, through its init file.
444
525
  const token = randomBytes(32).toString("hex");
@@ -447,17 +528,63 @@ async function runProgramOnce(options) {
447
528
  ctx,
448
529
  agent: createAgent(backend, projectDir, runEnded.signal),
449
530
  tools,
450
- workspace: workspaceDir ? createWorkspace(workspaceDir, runEnded.signal) : null,
531
+ workspace: sessionWorkspace,
532
+ workspaceAt,
533
+ journal,
534
+ run: (request, stop, seq) => {
535
+ if (validating) {
536
+ // As far as a validation goes. The call is left unanswered — an answer
537
+ // would only send the program on to do more — until the program,
538
+ // which is being stopped, lets go of it.
539
+ handedOff = true;
540
+ validated.abort();
541
+ return rejectOnAbort(new Promise(() => { }), stop);
542
+ }
543
+ // The program is waiting, not working: its clock stops for as long as
544
+ // the run it asked for lasts, which has a timeout of its own. That run
545
+ // is stopped when this one ends, or when the program no longer wants it.
546
+ const release = allowance.hold();
547
+ const nested = runProgram({ ...request, signal: AbortSignal.any([runEnded.signal, stop]) }, {
548
+ depth: options.depth + 1,
549
+ // The two journals point at each other: this one says which run the call started…
550
+ started: (run, path) => { if (run)
551
+ journal.note("child", { seq, run, journal: path }); },
552
+ // …and that run's journal says which call started it.
553
+ parent: { run: journal.run, journal: journal.path, seq },
554
+ }).finally(() => {
555
+ release();
556
+ nestedRuns.delete(nested);
557
+ });
558
+ nestedRuns.add(nested);
559
+ return nested;
560
+ },
451
561
  // The first terminal signal wins; ctx itself rejects a conflicting second one.
452
562
  onTerminalSignal: result => { terminalSignal ??= result; },
453
- holdClock: () => allowance.hold(),
454
563
  });
564
+ // A participant's output is shown under its name. It is not its parent's
565
+ // output: the runner writes it out itself, wherever in the tree it runs.
566
+ const out = label ? labelled(label, text => process.stdout.write(text)) : null;
567
+ const err = label ? labelled(label, text => process.stderr.write(text)) : null;
455
568
  // The program leads a process group of its own, so that everything it starts is in it.
456
569
  let programGroup;
457
- // If this process is stopped while the program is running, the program is stopped with it.
570
+ // If this process ends while the program is running, the watchdog stops the program.
458
571
  let programSettled = () => { };
572
+ // Asked to stop while its program had not ended. Everything it has in flight
573
+ // goes at once — the runs it asked for among them, so that a tree of runs is
574
+ // stopped together rather than one level after another.
575
+ let programOver = false;
576
+ let stopped = false;
577
+ const stopProgram = () => {
578
+ if (programOver)
579
+ return;
580
+ stopped = true;
581
+ runEnded.abort();
582
+ if (programGroup)
583
+ void stopGroups([programGroup]);
584
+ };
585
+ signal?.addEventListener("abort", stopProgram, { once: true });
459
586
  try {
460
- const child = await withTempDir("trama-init-", async (initDir) => {
587
+ const { child, exited } = await withTempDir("trama-init-", async (initDir) => {
461
588
  const port = await listen(server);
462
589
  const initFile = writeInitFile(initDir, {
463
590
  token,
@@ -465,7 +592,7 @@ async function runProgramOnce(options) {
465
592
  state: ctx.state,
466
593
  iteration: ctx.iteration,
467
594
  maxIterations: ctx.maxIterations,
468
- inSession: workspaceDir !== undefined,
595
+ inSession: sessionWorkspace !== null,
469
596
  resumed: ctx.resumed,
470
597
  yieldReason: ctx.yieldReason,
471
598
  });
@@ -478,26 +605,75 @@ async function runProgramOnce(options) {
478
605
  programGroup = program.pid;
479
606
  if (programGroup)
480
607
  programSettled = stopWithThisProcess(programGroup);
481
- return toChildResult(await superviseChild(program, {
608
+ if (signal?.aborted)
609
+ stopProgram(); // asked to stop while the program was being started
610
+ const exit = await superviseChild(program, {
482
611
  timeout: allowance,
483
- stopSignal: stopOnReady ? readyStop.signal : undefined,
612
+ stopSignal: validating ? validated.signal : undefined,
484
613
  sinks: {
485
- stdout: chunk => { process.stdout.write(chunk); },
486
- stderr: chunk => { process.stderr.write(chunk); },
614
+ stdout: out ? out.sink : chunk => { process.stdout.write(chunk); },
615
+ stderr: err ? err.sink : chunk => { process.stderr.write(chunk); },
487
616
  },
488
- }));
617
+ });
618
+ programOver = true;
619
+ // A validation that reached a hand-off in time was decided there: how the
620
+ // program goes down, cut off in mid-flow, says nothing about it.
621
+ const passedAtHandOff = handedOff && !exit.timedOut;
622
+ if (passedAtHandOff)
623
+ console.log(tagged(label, "[trama] validated up to where it starts another program"));
624
+ return {
625
+ child: passedAtHandOff ? { exitCode: 0, stdout: exit.stdout, stderr: exit.stderr } : toChildResult(exit),
626
+ // How the program's process ended, for the record.
627
+ exited: {
628
+ code: exit.code,
629
+ signal: exit.signal,
630
+ ...(exit.timedOut ? { timedOut: true } : {}),
631
+ // Stopped by the runner at the end of a validation: at a hand-off, or once it had been ready a while.
632
+ ...(exit.stopped ? { validated: handedOff ? "hand-off" : "ready" } : {}),
633
+ },
634
+ };
489
635
  });
490
- return { outcome: settle(projectDir, child, terminalSignal), failure: describeFailure(child) };
636
+ // How the attempt ended goes on record whatever comes of it — also when
637
+ // what the program left behind cannot be made sense of.
638
+ const noteExit = (verdict) => journal.note("exit", {
639
+ attempt,
640
+ ...exited,
641
+ ...(stopped ? { stopped: true } : {}),
642
+ // What the program printed is part of what it did. The end of it, where a failure shows.
643
+ stdout: tail(child.stdout, MAX_JOURNALLED_OUTPUT),
644
+ stderr: tail(child.stderr, MAX_JOURNALLED_OUTPUT),
645
+ ...verdict,
646
+ });
647
+ let outcome;
648
+ try {
649
+ // A program that was stopped did not finish, whatever its exit code
650
+ // says — unless it had already said it was done.
651
+ outcome = stopped && !terminalSignal ? null : settle(projectDir, child, terminalSignal);
652
+ }
653
+ catch (err) {
654
+ noteExit({ error: err instanceof Error ? err.message : String(err) });
655
+ throw err;
656
+ }
657
+ noteExit({ outcome });
658
+ return { outcome, failure: describeFailure(child) };
491
659
  }
492
660
  finally {
493
661
  // The program is gone (or never started). Nothing it started outlives its
494
- // run: cancel the calls it left in flight, and stop what is left of its
495
- // process group and of its shell commands. Only once they are gone is the
496
- // run over — whoever called will merge or delete what they were writing to.
662
+ // run: cancel the calls it left in flight — the runs it asked for among
663
+ // them — and stop what is left of its process group and of its shell
664
+ // commands. Only once they are gone is the run over: whoever called will
665
+ // merge or delete what they were writing to.
666
+ signal?.removeEventListener("abort", stopProgram);
667
+ out?.flush();
668
+ err?.flush();
497
669
  if (readyTimer)
498
670
  clearTimeout(readyTimer);
499
671
  runEnded.abort();
500
- await Promise.all([stopGroups(programGroup ? [programGroup] : []), tools.stopActiveShells()]);
672
+ await Promise.all([
673
+ stopGroups(programGroup ? [programGroup] : []),
674
+ tools.stopActiveShells(),
675
+ Promise.allSettled([...nestedRuns]),
676
+ ]);
501
677
  programSettled();
502
678
  server.closeAllConnections();
503
679
  await closeServer(server).catch(() => { });
@@ -515,30 +691,35 @@ const repairPrompt = (input) => `Fix this program so it runs.\n\n` +
515
691
  * of the project that holds the program it is asked to fix — whatever it reads
516
692
  * is real, whatever it writes is discarded; only the program text it returns
517
693
  * is used. Bounded by its own timeout.
518
- * Returns null (and records why) if no usable fix came back.
694
+ * Returns the fixed program, or why no usable one came back.
519
695
  */
520
- async function requestRepair(options, input, repairErrors) {
696
+ async function requestRepair(options, input) {
697
+ options.journal.note("fix-request", { error: input.error });
521
698
  return withTempDir("trama-repair-", async (tempDir) => {
522
699
  copyDirInto(options.projectDir, tempDir);
523
700
  writeFileSync(guardPath(tempDir, "program.ts"), input.programSource);
524
- const controller = new AbortController();
525
- const timer = setTimeout(() => controller.abort(), options.timeout);
701
+ const timedOut = new AbortController();
702
+ const limit = createAllowance(options.timeout);
703
+ limit.start(() => timedOut.abort());
704
+ const signal = options.signal ? AbortSignal.any([timedOut.signal, options.signal]) : timedOut.signal;
526
705
  try {
527
706
  const fixed = stripCodeFences(await options.backend.ask(repairPrompt(input), {
528
- cwd: tempDir, system: REPAIR_SYSTEM_PROMPT, signal: controller.signal,
707
+ cwd: tempDir, system: REPAIR_SYSTEM_PROMPT, signal,
529
708
  }));
530
709
  if (fixed.trim() === "")
531
710
  throw new Error("The repair returned an empty program.");
532
711
  if (fixed === input.programSource)
533
712
  throw new Error("The repair returned the program unchanged.");
534
- return fixed;
713
+ options.journal.note("fix", { ok: true, source: fixed });
714
+ return { fixed };
535
715
  }
536
716
  catch (err) {
537
- repairErrors.push(err instanceof Error ? err.message : String(err));
538
- return null;
717
+ const error = err instanceof Error ? err.message : String(err);
718
+ options.journal.note("fix", { ok: false, error });
719
+ return { error };
539
720
  }
540
721
  finally {
541
- clearTimeout(timer);
722
+ limit.cancel();
542
723
  }
543
724
  });
544
725
  }
@@ -558,12 +739,12 @@ async function requestRepair(options, input, repairErrors) {
558
739
  * would wait for replies forever. So what a fix writes there is written,
559
740
  * whether or not the fix works: like anything a run wrote before it failed.
560
741
  */
561
- async function tryFix(options, fixed) {
742
+ async function tryFix(options, fixed, attempt) {
562
743
  const { projectDir } = options;
563
744
  const run = await withStagedCopy(projectDir, async (stagedProject) => {
564
745
  writeFileSync(guardPath(stagedProject, "program.ts"), fixed);
565
746
  // If the copy cannot be run at all, or is left unusable, this fix did not work either.
566
- const trial = await runProgramOnce({ ...options, projectDir: stagedProject }).catch((err) => ({
747
+ const trial = await runProgramOnce({ ...options, projectDir: stagedProject, attempt }).catch((err) => ({
567
748
  outcome: null,
568
749
  failure: `The repaired program could not be run: ${err instanceof Error ? err.message : err}`,
569
750
  }));
@@ -582,56 +763,97 @@ async function tryFix(options, fixed) {
582
763
  async function executeProgram(options) {
583
764
  const { projectDir, maxRepairAttempts } = options;
584
765
  const failed = (reason) => ({ result: { status: "failed", reason } });
766
+ // A run that is stopped fails without a repair — there is nothing wrong with
767
+ // the program. Checked after each step; a step that had already reached an
768
+ // outcome keeps it.
769
+ const stopped = () => options.signal?.aborted === true;
770
+ const wasStopped = () => failed("The run was stopped before it finished.");
771
+ if (stopped())
772
+ return wasStopped();
585
773
  const firstRun = await runProgramOnce(options);
586
774
  if (firstRun.outcome)
587
775
  return { result: firstRun.outcome };
776
+ if (stopped())
777
+ return wasStopped();
588
778
  let lastError = firstRun.failure;
589
779
  if (maxRepairAttempts === 0)
590
780
  return failed(`Program failed (repair disabled): ${lastError}`);
591
781
  // Each attempt builds on the previous one's source, though a fix that failed never reached the project.
592
782
  let currentSource = readFileSync(guardPath(projectDir, "program.ts"), "utf-8");
593
- const repairErrors = [];
594
- const repairDetails = () => repairErrors.length > 0
595
- ? `\nRepair errors:\n${repairErrors.map((e, i) => ` [${i + 1}] ${e}`).join("\n")}` : "";
596
- for (let attempt = 0; attempt < maxRepairAttempts; attempt++) {
597
- const fixed = await requestRepair(options, { programSource: currentSource, error: lastError }, repairErrors);
598
- if (!fixed)
599
- return failed(`Failed after ${attempt + 1} repair attempt(s): ${lastError}${repairDetails()}`);
600
- currentSource = fixed;
601
- const run = await tryFix(options, fixed);
783
+ // The program as it was is attempt 0; each fix is the next.
784
+ for (let attempt = 1; attempt <= maxRepairAttempts; attempt++) {
785
+ const fix = await requestRepair(options, { programSource: currentSource, error: lastError });
786
+ if (stopped())
787
+ return wasStopped();
788
+ // Without a fix there is nothing more to try: asking again would be asking the same thing.
789
+ if ("error" in fix) {
790
+ return failed(`Failed after ${attempt} repair attempt(s): ${lastError}\nNo fix came back: ${fix.error}`);
791
+ }
792
+ currentSource = fix.fixed;
793
+ const run = await tryFix(options, fix.fixed, attempt);
602
794
  if (run.outcome)
603
795
  return { result: run.outcome, repair: { attempt, error: lastError } };
796
+ if (stopped())
797
+ return wasStopped();
604
798
  lastError = run.failure;
605
799
  }
606
- return failed(`Failed after ${maxRepairAttempts} repair attempts: ${lastError}${repairDetails()}`);
800
+ return failed(`Failed after ${maxRepairAttempts} repair attempts: ${lastError}`);
801
+ }
802
+ /**
803
+ * Carry out a run under its journal. However it goes, the journal's last
804
+ * record says so: the run's result, or why it could not be carried out.
805
+ */
806
+ async function journalled(journal, run) {
807
+ try {
808
+ const execution = await run();
809
+ journal.note("end", { result: execution.result });
810
+ return execution;
811
+ }
812
+ catch (err) {
813
+ journal.note("end", { error: err instanceof Error ? err.message : String(err) });
814
+ throw err;
815
+ }
816
+ finally {
817
+ journal.close();
818
+ }
607
819
  }
608
820
  // --- Validating a candidate program (used by create and update) ---
609
821
  const VALIDATION_READY_GRACE_MS = 2_000;
610
822
  /**
611
- * Validate a candidate program.ts for a project without touching the project:
612
- * run it (with repair) in a throwaway copy. Returns the program that worked —
823
+ * Validate a candidate program.ts for a project without touching what the
824
+ * project holds: run it (with repair) in a throwaway copy. The one thing left
825
+ * in the project is the journal of the validation. Returns the program that worked —
613
826
  * the candidate itself, or a repaired version of it, with the failure that was
614
827
  * repaired. Throws if it cannot be made to run.
615
828
  *
616
829
  * Only the project's own files are shielded. What the program does beyond
617
- * them — network calls, shell commands, other projects it runs — is real.
830
+ * them — network calls, shell commands, agent calls — is real. A run it asks
831
+ * its runner for is not started: the validation ends where it asks for the
832
+ * first.
618
833
  */
619
834
  export async function validateProgram(projectDir, backend, candidate, options) {
620
- return withTempDir("trama-validate-", async (trialDir) => {
835
+ const { journalRuns = 0, ...limits } = options;
836
+ // Recorded with the project, though run in a copy of it.
837
+ const journal = openJournal(projectDir, journalRuns, { purpose: "validate", ...limits });
838
+ const { result, repair, worked } = await journalled(journal, () => withTempDir("trama-validate-", async (trialDir) => {
621
839
  copyDirInto(projectDir, trialDir);
622
840
  const programPath = guardPath(trialDir, "program.ts");
623
841
  writeFileSync(programPath, candidate);
624
- const { result, repair } = await executeProgram({
625
- ...options,
842
+ const execution = await executeProgram({
843
+ ...limits,
626
844
  projectDir: trialDir,
627
845
  backend,
628
- stopOnReady: { graceMs: VALIDATION_READY_GRACE_MS },
846
+ depth: 0,
847
+ validating: { readyGraceMs: VALIDATION_READY_GRACE_MS },
848
+ journal,
629
849
  });
630
- if (result.status === "failed") {
631
- throw new Error(`Program failed: ${result.reason}`);
632
- }
633
- return { source: readFileSync(programPath, "utf-8"), repairedError: repair?.error };
634
- });
850
+ // The program that worked — the candidate, or what a repair made of it. None, if nothing did.
851
+ const worked = execution.result.status === "failed" ? null : readFileSync(programPath, "utf-8");
852
+ return { ...execution, worked };
853
+ }));
854
+ if (worked === null)
855
+ throw new Error(`Program failed: ${result.reason}`);
856
+ return { source: worked, repairedError: repair?.error };
635
857
  }
636
858
  /**
637
859
  * Make a validated program the project's program.ts and record it as a new
@@ -648,39 +870,35 @@ export function installValidatedProgram(projectDir, validated, reason, prompt) {
648
870
  copyToHistory(projectDir, reason, prompt);
649
871
  }
650
872
  // --- Core execution ---
873
+ /** How deep programs may run programs, and how many runs one runner carries at a time. */
874
+ const MAX_RUN_DEPTH = 16;
875
+ const MAX_RUNS_IN_FLIGHT = 128;
876
+ let runsInFlight = 0;
651
877
  /**
652
- * A run started from inside a program — a session participant, typically — is
653
- * under a timeout of its own. Tell the runner of the program it was started
654
- * from, so that program's clock stops while this run lasts and it is not
655
- * killed for the time its participant was entitled to take.
878
+ * Run a project, in this process: this is what a runner does.
656
879
  *
657
- * Returns what ends the hold. Best-effort: if that runner cannot be reached
658
- * its program's run is over, and this one is about to be stopped with it.
659
- *
660
- * This exists only because the runner of a participant lives inside the
661
- * program that spawned it, where that program's own runner cannot see it. It
662
- * goes away once starting a run is itself a call on the bridge.
880
+ * `askedFor` is set when a program asked for the run (see the "/run/program"
881
+ * call). One runner carries the whole tree of runs, so it is also where the
882
+ * tree is kept from growing without bound.
663
883
  */
664
- function holdParentClock() {
665
- const { TRAMA_PORT: port, TRAMA_INIT: initPath } = process.env;
666
- if (port && initPath) {
667
- try {
668
- return openBridge(port, initPath).hold("/clock/hold");
669
- }
670
- catch { /* not held */ }
884
+ export async function runProgram(options, askedFor) {
885
+ const depth = askedFor?.depth ?? 0;
886
+ if (depth > MAX_RUN_DEPTH) {
887
+ throw new Error(`Not running ${options.projectDir}: programs are running programs more than ${MAX_RUN_DEPTH} deep. ` +
888
+ `A program that runs itself, or two that run each other, never ends.`);
671
889
  }
672
- return () => { };
673
- }
674
- export async function runProgram(options) {
675
- const releaseParentClock = holdParentClock();
890
+ if (runsInFlight >= MAX_RUNS_IN_FLIGHT) {
891
+ throw new Error(`Not running ${options.projectDir}: ${MAX_RUNS_IN_FLIGHT} runs are already in flight.`);
892
+ }
893
+ runsInFlight += 1;
676
894
  try {
677
- return await runProject(options);
895
+ return await runProject(options, depth, askedFor);
678
896
  }
679
897
  finally {
680
- releaseParentClock();
898
+ runsInFlight -= 1;
681
899
  }
682
900
  }
683
- async function runProject(options) {
901
+ async function runProject(options, depth, askedFor) {
684
902
  const { projectDir } = options;
685
903
  if (!existsSync(join(projectDir, "meta.json"))) {
686
904
  throw new Error(`Project not found at ${projectDir}. ` +
@@ -695,7 +913,18 @@ async function runProject(options) {
695
913
  if (!Number.isInteger(maxRepairAttempts) || maxRepairAttempts < 0) {
696
914
  throw new Error(`Invalid maxRepairAttempts: ${maxRepairAttempts}. Must be a non-negative integer.`);
697
915
  }
698
- const { result, repair } = await executeProgram({
916
+ const journal = openJournal(projectDir, config.journalRuns, {
917
+ purpose: "run",
918
+ label: options.label,
919
+ depth,
920
+ parent: askedFor?.parent,
921
+ workspace: options.workspaceDir,
922
+ timeout,
923
+ maxRepairAttempts,
924
+ args: options.args, // last: it is the one field of unknown size
925
+ });
926
+ askedFor?.started(journal.run, journal.path);
927
+ const { result, repair } = await journalled(journal, () => executeProgram({
699
928
  projectDir,
700
929
  backend: createBackend(config),
701
930
  maxRepairAttempts,
@@ -703,17 +932,21 @@ async function runProject(options) {
703
932
  maxIterations: config.defaultMaxIterations,
704
933
  argsOverride: options.args,
705
934
  workspaceDir: options.workspaceDir,
706
- });
935
+ depth,
936
+ label: options.label,
937
+ signal: options.signal,
938
+ journal,
939
+ }));
707
940
  if (repair) {
708
941
  // The program is fixed and has run; failing to write this down must not turn that into an error.
709
942
  try {
710
- const entry = { ts: Date.now(), message: `Repair attempt ${repair.attempt + 1}/${maxRepairAttempts}`, data: { error: repair.error } };
943
+ const entry = { ts: Date.now(), message: `Repair attempt ${repair.attempt}/${maxRepairAttempts}`, data: { error: repair.error } };
711
944
  appendFileSync(guardPath(projectDir, join("logs", "latest.jsonl")), JSON.stringify(entry) + "\n");
712
- console.log(`[trama] Repair attempt ${repair.attempt + 1}/${maxRepairAttempts}`);
945
+ console.log(tagged(options.label, `[trama] Repair attempt ${repair.attempt}/${maxRepairAttempts}`));
713
946
  copyToHistory(projectDir, "repair", repair.error);
714
947
  }
715
948
  catch (err) {
716
- console.warn(`[trama] repair bookkeeping failed: ${err instanceof Error ? err.message : err}`);
949
+ console.warn(tagged(options.label, `[trama] repair bookkeeping failed: ${err instanceof Error ? err.message : err}`));
717
950
  }
718
951
  }
719
952
  return result;