@trama-dev/runtime 0.2.2 → 0.3.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/runner.js CHANGED
@@ -4,20 +4,27 @@ import { join, dirname } from "path";
4
4
  import { homedir, tmpdir } from "os";
5
5
  import { fileURLToPath } from "url";
6
6
  import { 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
- import { createAgent } from "./agent.js";
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 { signalGroup, superviseChild } from "./child-process.js";
14
- import { removeTempDir, untilSettled } from "./lifetime.js";
14
+ import { createAllowance, stopGroups, superviseChild } from "./child-process.js";
15
+ import { removeTempDir, removeWithThisProcess, requireWatchdog, stopWithThisProcess } from "./watchdog.js";
15
16
  import { createIPCServer, listen, closeServer } from "./ipc-server.js";
16
17
  // --- Locating the runtime itself ---
17
18
  /** The installed @trama-dev/runtime package — this file lives in its dist/. */
18
19
  const RUNTIME_PACKAGE_DIR = dirname(dirname(fileURLToPath(import.meta.url)));
19
- /** tsx executes program.ts. Resolved through the module system, so any install layout works. */
20
- const TSX_CLI = fileURLToPath(import.meta.resolve("tsx/cli"));
20
+ /**
21
+ * tsx lets node run program.ts. Resolved through the module system, so any
22
+ * install layout works. It is loaded into the program's own node process
23
+ * rather than run as the `tsx` command, which puts a process of its own in
24
+ * front of the program: one that kills the program some 60 ms after a SIGTERM
25
+ * it has not acted on, and reports its death by signal as an exit code.
26
+ */
27
+ const TSX_LOADER = import.meta.resolve("tsx");
21
28
  /**
22
29
  * The @trama-dev packages a program.ts can import, and where they are installed.
23
30
  * The runtime always; the session layer when it is installed alongside (as it
@@ -181,6 +188,16 @@ export function loadProjectConfig(projectDir) {
181
188
  config.provider = meta.provider;
182
189
  return config;
183
190
  }
191
+ /**
192
+ * What does the LLM work for a project. The only place that picks a backend:
193
+ * everything else is handed one and does not know which it is.
194
+ */
195
+ export function createBackend(config) {
196
+ const backend = new PiAdapter(config);
197
+ // The interface promises that a cancelled call rejects, and a run's end
198
+ // waits on that. Every backend is held to it here, rather than trusted with it.
199
+ return { ask: (prompt, call) => rejectOnAbort(backend.ask(prompt, call), call.signal) };
200
+ }
184
201
  export function loadState(projectDir) {
185
202
  const statePath = guardPath(projectDir, "state.json");
186
203
  if (!existsSync(statePath))
@@ -260,7 +277,7 @@ const sameStat = (a, b) => a.size === b.size && a.mtimeMs === b.mtimeMs;
260
277
  /**
261
278
  * Merge what a run did to a staged copy back into the real directory, with a
262
279
  * three-way check so that nothing changed in the real directory meanwhile —
263
- * by another session participant, or by the user — is overwritten.
280
+ * by the user, or by another run of the same project — is overwritten.
264
281
  *
265
282
  * @param stagedDir - the copy after the run (source of changes)
266
283
  * @param realDir - the real directory (destination)
@@ -314,7 +331,7 @@ export function commitStagedChanges(stagedDir, realDir, stagedBefore, realSeed)
314
331
  /** Run fn in a temp directory, clean up afterwards regardless of outcome — including this process being stopped. */
315
332
  export async function withTempDir(prefix, fn) {
316
333
  const dir = mkdtempSync(join(tmpdir(), prefix));
317
- const settled = untilSettled(() => removeTempDir(dir));
334
+ const settled = removeWithThisProcess(dir);
318
335
  try {
319
336
  return await fn(dir);
320
337
  }
@@ -349,6 +366,34 @@ async function withStagedCopy(realDir, fn) {
349
366
  function tail(text, max = 20_000) {
350
367
  return text.length <= max ? text : `[… ${text.length - max} earlier characters omitted]\n${text.slice(-max)}`;
351
368
  }
369
+ /** A line as it is shown for a run: under the run's name, if it has one. */
370
+ const tagged = (label, line) => label ? `[${label}] ${line}` : line;
371
+ /** The longest stretch of output held back while waiting for its line to end. */
372
+ const MAX_HELD_LINE = 64 * 1024;
373
+ /** Put a label in front of each line written to a stream. `flush` writes out a last line that had no newline. */
374
+ function labelled(label, write) {
375
+ let held = "";
376
+ const flush = () => {
377
+ if (held)
378
+ write(tagged(label, held) + "\n");
379
+ held = "";
380
+ };
381
+ return {
382
+ sink(chunk) {
383
+ const end = chunk.lastIndexOf("\n");
384
+ if (end === -1) {
385
+ held += chunk;
386
+ if (held.length > MAX_HELD_LINE)
387
+ flush(); // a line with no end in sight is shown in pieces
388
+ return;
389
+ }
390
+ const lines = (held + chunk.slice(0, end)).split("\n");
391
+ held = chunk.slice(end + 1);
392
+ write(lines.map(line => tagged(label, line) + "\n").join(""));
393
+ },
394
+ flush,
395
+ };
396
+ }
352
397
  const describeFailure = (r) => `program.ts exited with code ${r.exitCode}\nstdout: ${tail(r.stdout)}\nstderr: ${tail(r.stderr)}`;
353
398
  /**
354
399
  * Hand the program its starting state through a private temp file rather than
@@ -370,7 +415,7 @@ function toChildResult(exit) {
370
415
  const { stdout, stderr } = exit;
371
416
  if (exit.timedOut)
372
417
  return { exitCode: 1, stdout, stderr: stderr + "\n[trama] program killed: timeout" };
373
- // Stopped by us after ctx.ready() — going down on SIGTERM is the expected outcome.
418
+ // Stopped by us at the end of a validation — going down on SIGTERM is the expected outcome.
374
419
  if (exit.stopped && (exit.code === 0 || exit.signal === "SIGTERM"))
375
420
  return { exitCode: 0, stdout, stderr };
376
421
  return { exitCode: exit.code ?? 1, stdout, stderr };
@@ -405,38 +450,95 @@ function settle(projectDir, child, terminalSignal) {
405
450
  * (bad project, server or spawn failure) or left state.json unreadable.
406
451
  */
407
452
  async function runProgramOnce(options) {
408
- const { projectDir, adapter, timeout, maxIterations, argsOverride, stopOnReady, workspaceDir } = options;
453
+ const { projectDir, backend, timeout, maxIterations, argsOverride, validating, workspaceDir, label, signal } = options;
454
+ if (signal?.aborted)
455
+ return { outcome: null, failure: "The run was stopped before its program started." };
456
+ requireWatchdog();
409
457
  ensureProjectScaffold(projectDir);
410
458
  // Cancels in-flight LLM calls, fetches and observes once the run is over.
411
459
  const runEnded = new AbortController();
412
- // Asks the program to stop once it has been ready for the grace period.
413
- const readyStop = new AbortController();
460
+ // Ends a validation: the program has shown what it had to, and is asked to stop.
461
+ const validated = new AbortController();
414
462
  let readyTimer = null;
415
463
  let terminalSignal = null;
416
464
  const ctx = createContext(projectDir, loadState(projectDir), {
417
465
  maxIterations,
418
466
  argsOverride,
419
- onReady: stopOnReady && (() => {
420
- readyTimer ??= setTimeout(() => readyStop.abort(), stopOnReady.graceMs).unref();
467
+ onReady: validating && (() => {
468
+ readyTimer ??= setTimeout(() => validated.abort(), validating.readyGraceMs).unref();
421
469
  }),
470
+ print: line => console.log(tagged(label, line)),
422
471
  });
423
472
  // Truncate logs only after preflight succeeds — preserves the prior run's
424
473
  // diagnostics if scaffolding, state loading, or context creation fails.
425
474
  writeFileSync(guardPath(projectDir, join("logs", "latest.jsonl")), "");
475
+ // The program's own time. It stops while a run the program asked for is in flight.
476
+ const allowance = createAllowance(timeout);
477
+ // Set when a validation ended because the program asked for another to be run.
478
+ let handedOff = false;
479
+ // Runs the program has asked for and that are still going. They belong to this run.
480
+ const nestedRuns = new Set();
481
+ const workspaces = new Map();
426
482
  const tools = createTools(projectDir, runEnded.signal);
427
483
  // Known only to this run's program, through its init file.
428
484
  const token = randomBytes(32).toString("hex");
429
485
  const server = createIPCServer({
430
486
  token,
431
487
  ctx,
432
- agent: createAgent(adapter, runEnded.signal),
488
+ agent: createAgent(backend, projectDir, runEnded.signal),
433
489
  tools,
434
490
  workspace: workspaceDir ? createWorkspace(workspaceDir, runEnded.signal) : null,
491
+ workspaceAt: (dir) => {
492
+ let workspace = workspaces.get(dir);
493
+ if (!workspace)
494
+ workspaces.set(dir, workspace = createWorkspace(dir, runEnded.signal));
495
+ return workspace;
496
+ },
497
+ run: (request, stop) => {
498
+ if (validating) {
499
+ // As far as a validation goes. The call is left unanswered — an answer
500
+ // would only send the program on to do more — until the program,
501
+ // which is being stopped, lets go of it.
502
+ handedOff = true;
503
+ validated.abort();
504
+ return rejectOnAbort(new Promise(() => { }), stop);
505
+ }
506
+ // The program is waiting, not working: its clock stops for as long as
507
+ // the run it asked for lasts, which has a timeout of its own. That run
508
+ // is stopped when this one ends, or when the program no longer wants it.
509
+ const release = allowance.hold();
510
+ const nested = runProgram({ ...request, signal: AbortSignal.any([runEnded.signal, stop]) }, options.depth + 1).finally(() => {
511
+ release();
512
+ nestedRuns.delete(nested);
513
+ });
514
+ nestedRuns.add(nested);
515
+ return nested;
516
+ },
435
517
  // The first terminal signal wins; ctx itself rejects a conflicting second one.
436
518
  onTerminalSignal: result => { terminalSignal ??= result; },
437
519
  });
438
- // If this process is stopped while the program is running, take the program down with it.
439
- let programStopped = () => { };
520
+ // A participant's output is shown under its name. It is not its parent's
521
+ // output: the runner writes it out itself, wherever in the tree it runs.
522
+ const out = label ? labelled(label, text => process.stdout.write(text)) : null;
523
+ const err = label ? labelled(label, text => process.stderr.write(text)) : null;
524
+ // The program leads a process group of its own, so that everything it starts is in it.
525
+ let programGroup;
526
+ // If this process ends while the program is running, the watchdog stops the program.
527
+ let programSettled = () => { };
528
+ // Asked to stop while its program had not ended. Everything it has in flight
529
+ // goes at once — the runs it asked for among them, so that a tree of runs is
530
+ // stopped together rather than one level after another.
531
+ let programOver = false;
532
+ let stopped = false;
533
+ const stopProgram = () => {
534
+ if (programOver)
535
+ return;
536
+ stopped = true;
537
+ runEnded.abort();
538
+ if (programGroup)
539
+ void stopGroups([programGroup]);
540
+ };
541
+ signal?.addEventListener("abort", stopProgram, { once: true });
440
542
  try {
441
543
  const child = await withTempDir("trama-init-", async (initDir) => {
442
544
  const port = await listen(server);
@@ -450,53 +552,86 @@ async function runProgramOnce(options) {
450
552
  resumed: ctx.resumed,
451
553
  yieldReason: ctx.yieldReason,
452
554
  });
453
- const program = spawn(process.execPath, [TSX_CLI, guardPath(projectDir, "program.ts")], {
555
+ const program = spawn(process.execPath, ["--import", TSX_LOADER, guardPath(projectDir, "program.ts")], {
454
556
  cwd: projectDir,
455
557
  env: { ...process.env, TRAMA_PORT: String(port), TRAMA_INIT: initFile },
456
558
  stdio: ["ignore", "pipe", "pipe"],
457
559
  detached: true,
458
560
  });
459
- const pgid = program.pid;
460
- if (pgid)
461
- programStopped = untilSettled(() => signalGroup(pgid, "SIGKILL"));
462
- return toChildResult(await superviseChild(program, {
463
- timeout,
464
- stopSignal: stopOnReady ? readyStop.signal : undefined,
561
+ programGroup = program.pid;
562
+ if (programGroup)
563
+ programSettled = stopWithThisProcess(programGroup);
564
+ if (signal?.aborted)
565
+ stopProgram(); // asked to stop while the program was being started
566
+ const exit = await superviseChild(program, {
567
+ timeout: allowance,
568
+ stopSignal: validating ? validated.signal : undefined,
465
569
  sinks: {
466
- stdout: chunk => { process.stdout.write(chunk); },
467
- stderr: chunk => { process.stderr.write(chunk); },
570
+ stdout: out ? out.sink : chunk => { process.stdout.write(chunk); },
571
+ stderr: err ? err.sink : chunk => { process.stderr.write(chunk); },
468
572
  },
469
- }));
573
+ });
574
+ programOver = true;
575
+ // A validation that reached a hand-off in time was decided there.
576
+ if (handedOff && !exit.timedOut) {
577
+ console.log(tagged(label, "[trama] validated up to where it starts another program"));
578
+ return { exitCode: 0, stdout: exit.stdout, stderr: exit.stderr };
579
+ }
580
+ return toChildResult(exit);
470
581
  });
471
- return { outcome: settle(projectDir, child, terminalSignal), failure: describeFailure(child) };
582
+ // A program that was stopped did not finish, whatever its exit code says —
583
+ // unless it had already said it was done.
584
+ const outcome = stopped && !terminalSignal ? null : settle(projectDir, child, terminalSignal);
585
+ return { outcome, failure: describeFailure(child) };
472
586
  }
473
587
  finally {
474
- // The program is gone (or never started): cancel what it left in flight,
475
- // kill shells it left running in the background, and drop its connections.
476
- programStopped();
588
+ // The program is gone (or never started). Nothing it started outlives its
589
+ // run: cancel the calls it left in flight — the runs it asked for among
590
+ // them — and stop what is left of its process group and of its shell
591
+ // commands. Only once they are gone is the run over: whoever called will
592
+ // merge or delete what they were writing to.
593
+ signal?.removeEventListener("abort", stopProgram);
594
+ out?.flush();
595
+ err?.flush();
477
596
  if (readyTimer)
478
597
  clearTimeout(readyTimer);
479
598
  runEnded.abort();
480
- tools.killActiveShells();
599
+ await Promise.all([
600
+ stopGroups(programGroup ? [programGroup] : []),
601
+ tools.stopActiveShells(),
602
+ Promise.allSettled([...nestedRuns]),
603
+ ]);
604
+ programSettled();
481
605
  server.closeAllConnections();
482
606
  await closeServer(server).catch(() => { });
483
607
  }
484
608
  }
609
+ /** The instructions a request for a fix is made under. (Exported so the tests' stand-in LLM can tell one from any other call.) */
610
+ export const REPAIR_SYSTEM_PROMPT = "You are a TypeScript repair tool.";
611
+ const repairPrompt = (input) => `Fix this program so it runs.\n\n` +
612
+ `Runtime types:\n${RUNTIME_TYPES}\n\n` +
613
+ `Broken program:\n${input.programSource}\n\n` +
614
+ `Error:\n${input.error}\n\n` +
615
+ `Output ONLY the fixed program. No explanation.`;
485
616
  /**
486
- * Ask the LLM for a fix. The repair agent has tools, so it works in a
487
- * throwaway copy of the project that holds the program it is asked to fix —
488
- * whatever it reads is real, whatever it writes is discarded; only the program
489
- * text it returns is used. Bounded by its own timeout.
617
+ * Ask the LLM for a fix. The agent has tools, so it works in a throwaway copy
618
+ * of the project that holds the program it is asked to fix — whatever it reads
619
+ * is real, whatever it writes is discarded; only the program text it returns
620
+ * is used. Bounded by its own timeout.
490
621
  * Returns null (and records why) if no usable fix came back.
491
622
  */
492
623
  async function requestRepair(options, input, repairErrors) {
493
624
  return withTempDir("trama-repair-", async (tempDir) => {
494
625
  copyDirInto(options.projectDir, tempDir);
495
626
  writeFileSync(guardPath(tempDir, "program.ts"), input.programSource);
496
- const controller = new AbortController();
497
- const timer = setTimeout(() => controller.abort(), options.timeout);
627
+ const timedOut = new AbortController();
628
+ const limit = createAllowance(options.timeout);
629
+ limit.start(() => timedOut.abort());
630
+ const signal = options.signal ? AbortSignal.any([timedOut.signal, options.signal]) : timedOut.signal;
498
631
  try {
499
- const fixed = await options.adapter.withCwd(tempDir).repair({ ...input, runtimeTypes: RUNTIME_TYPES }, controller.signal);
632
+ const fixed = stripCodeFences(await options.backend.ask(repairPrompt(input), {
633
+ cwd: tempDir, system: REPAIR_SYSTEM_PROMPT, signal,
634
+ }));
500
635
  if (fixed.trim() === "")
501
636
  throw new Error("The repair returned an empty program.");
502
637
  if (fixed === input.programSource)
@@ -508,39 +643,37 @@ async function requestRepair(options, input, repairErrors) {
508
643
  return null;
509
644
  }
510
645
  finally {
511
- clearTimeout(timer);
646
+ limit.cancel();
512
647
  }
513
648
  });
514
649
  }
515
650
  /**
516
- * Try a proposed fix: run it on a private copy of the project (and of the
517
- * shared workspace). Only if it works does anything reach the real ones — the
518
- * fix becomes program.ts, and what the run wrote is merged back. A fix that
519
- * fails, or a runner that is stopped half-way, leaves the project exactly as
520
- * it was, because it was never touched.
651
+ * Try a proposed fix.
652
+ *
653
+ * The project is the program's own, so the fix runs on a private copy of it.
654
+ * Only if it works does anything reach the real one — the fix becomes
655
+ * program.ts, and what the run wrote is merged back. A fix that fails, or a
656
+ * runner that is stopped half-way, leaves the project exactly as it was,
657
+ * because it was never touched: its state is only ever written by code that
658
+ * is, or becomes, its program.
659
+ *
660
+ * The shared workspace is not copied. It is how the participants of a session
661
+ * talk to each other, and a program that is being fixed still has to be heard
662
+ * and answered — a fix that wrote its requests where nobody could see them
663
+ * would wait for replies forever. So what a fix writes there is written,
664
+ * whether or not the fix works: like anything a run wrote before it failed.
521
665
  */
522
666
  async function tryFix(options, fixed) {
523
- const { projectDir, workspaceDir } = options;
524
- const inStagedProject = (stagedWorkspace) => withStagedCopy(projectDir, async (stagedProject) => {
667
+ const { projectDir } = options;
668
+ const run = await withStagedCopy(projectDir, async (stagedProject) => {
525
669
  writeFileSync(guardPath(stagedProject, "program.ts"), fixed);
526
- let run;
527
- try {
528
- run = await runProgramOnce({
529
- ...options, projectDir: stagedProject, adapter: options.adapter.withCwd(stagedProject), workspaceDir: stagedWorkspace,
530
- });
531
- }
532
- catch (err) {
533
- // The copy could not be run at all, or was left unusable. Either way this fix did not work.
534
- run = { outcome: null, failure: `The repaired program could not be run: ${err instanceof Error ? err.message : err}` };
535
- }
536
- return { commit: run.outcome !== null, value: run };
670
+ // If the copy cannot be run at all, or is left unusable, this fix did not work either.
671
+ const trial = await runProgramOnce({ ...options, projectDir: stagedProject }).catch((err) => ({
672
+ outcome: null,
673
+ failure: `The repaired program could not be run: ${err instanceof Error ? err.message : err}`,
674
+ }));
675
+ return { commit: trial.outcome !== null, value: trial };
537
676
  });
538
- const run = workspaceDir
539
- ? await withStagedCopy(workspaceDir, async (stagedWorkspace) => {
540
- const value = await inStagedProject(stagedWorkspace);
541
- return { commit: value.outcome !== null, value };
542
- })
543
- : await inStagedProject(undefined);
544
677
  // The merge above carries over what the run changed; the fix itself was
545
678
  // written before the run started, so it is installed explicitly.
546
679
  if (run.outcome)
@@ -554,9 +687,18 @@ async function tryFix(options, fixed) {
554
687
  async function executeProgram(options) {
555
688
  const { projectDir, maxRepairAttempts } = options;
556
689
  const failed = (reason) => ({ result: { status: "failed", reason } });
690
+ // A run that is stopped fails without a repair — there is nothing wrong with
691
+ // the program. Checked after each step; a step that had already reached an
692
+ // outcome keeps it.
693
+ const stopped = () => options.signal?.aborted === true;
694
+ const wasStopped = () => failed("The run was stopped before it finished.");
695
+ if (stopped())
696
+ return wasStopped();
557
697
  const firstRun = await runProgramOnce(options);
558
698
  if (firstRun.outcome)
559
699
  return { result: firstRun.outcome };
700
+ if (stopped())
701
+ return wasStopped();
560
702
  let lastError = firstRun.failure;
561
703
  if (maxRepairAttempts === 0)
562
704
  return failed(`Program failed (repair disabled): ${lastError}`);
@@ -567,12 +709,16 @@ async function executeProgram(options) {
567
709
  ? `\nRepair errors:\n${repairErrors.map((e, i) => ` [${i + 1}] ${e}`).join("\n")}` : "";
568
710
  for (let attempt = 0; attempt < maxRepairAttempts; attempt++) {
569
711
  const fixed = await requestRepair(options, { programSource: currentSource, error: lastError }, repairErrors);
712
+ if (stopped())
713
+ return wasStopped();
570
714
  if (!fixed)
571
715
  return failed(`Failed after ${attempt + 1} repair attempt(s): ${lastError}${repairDetails()}`);
572
716
  currentSource = fixed;
573
717
  const run = await tryFix(options, fixed);
574
718
  if (run.outcome)
575
719
  return { result: run.outcome, repair: { attempt, error: lastError } };
720
+ if (stopped())
721
+ return wasStopped();
576
722
  lastError = run.failure;
577
723
  }
578
724
  return failed(`Failed after ${maxRepairAttempts} repair attempts: ${lastError}${repairDetails()}`);
@@ -586,9 +732,11 @@ const VALIDATION_READY_GRACE_MS = 2_000;
586
732
  * repaired. Throws if it cannot be made to run.
587
733
  *
588
734
  * Only the project's own files are shielded. What the program does beyond
589
- * them — network calls, shell commands, other projects it runs — is real.
735
+ * them — network calls, shell commands, agent calls — is real. A run it asks
736
+ * its runner for is not started: the validation ends where it asks for the
737
+ * first.
590
738
  */
591
- export async function validateProgram(projectDir, adapter, candidate, options) {
739
+ export async function validateProgram(projectDir, backend, candidate, options) {
592
740
  return withTempDir("trama-validate-", async (trialDir) => {
593
741
  copyDirInto(projectDir, trialDir);
594
742
  const programPath = guardPath(trialDir, "program.ts");
@@ -596,8 +744,9 @@ export async function validateProgram(projectDir, adapter, candidate, options) {
596
744
  const { result, repair } = await executeProgram({
597
745
  ...options,
598
746
  projectDir: trialDir,
599
- adapter: adapter.withCwd(trialDir),
600
- stopOnReady: { graceMs: VALIDATION_READY_GRACE_MS },
747
+ backend,
748
+ depth: 0,
749
+ validating: { readyGraceMs: VALIDATION_READY_GRACE_MS },
601
750
  });
602
751
  if (result.status === "failed") {
603
752
  throw new Error(`Program failed: ${result.reason}`);
@@ -620,7 +769,35 @@ export function installValidatedProgram(projectDir, validated, reason, prompt) {
620
769
  copyToHistory(projectDir, reason, prompt);
621
770
  }
622
771
  // --- Core execution ---
623
- export async function runProgram(options) {
772
+ /** How deep programs may run programs, and how many runs one runner carries at a time. */
773
+ const MAX_RUN_DEPTH = 16;
774
+ const MAX_RUNS_IN_FLIGHT = 128;
775
+ let runsInFlight = 0;
776
+ /**
777
+ * Run a project, in this process: this is what a runner does.
778
+ *
779
+ * `depth` is how many runs deep this one is — 0 unless a program asked for it
780
+ * (see the "/run/program" call), in which case it is one more than that
781
+ * program's own. One runner carries the whole tree, so it is also where the
782
+ * tree is kept from growing without bound.
783
+ */
784
+ export async function runProgram(options, depth = 0) {
785
+ if (depth > MAX_RUN_DEPTH) {
786
+ throw new Error(`Not running ${options.projectDir}: programs are running programs more than ${MAX_RUN_DEPTH} deep. ` +
787
+ `A program that runs itself, or two that run each other, never ends.`);
788
+ }
789
+ if (runsInFlight >= MAX_RUNS_IN_FLIGHT) {
790
+ throw new Error(`Not running ${options.projectDir}: ${MAX_RUNS_IN_FLIGHT} runs are already in flight.`);
791
+ }
792
+ runsInFlight += 1;
793
+ try {
794
+ return await runProject(options, depth);
795
+ }
796
+ finally {
797
+ runsInFlight -= 1;
798
+ }
799
+ }
800
+ async function runProject(options, depth) {
624
801
  const { projectDir } = options;
625
802
  if (!existsSync(join(projectDir, "meta.json"))) {
626
803
  throw new Error(`Project not found at ${projectDir}. ` +
@@ -637,23 +814,26 @@ export async function runProgram(options) {
637
814
  }
638
815
  const { result, repair } = await executeProgram({
639
816
  projectDir,
640
- adapter: new PiAdapter(config, projectDir),
817
+ backend: createBackend(config),
641
818
  maxRepairAttempts,
642
819
  timeout,
643
820
  maxIterations: config.defaultMaxIterations,
644
821
  argsOverride: options.args,
645
822
  workspaceDir: options.workspaceDir,
823
+ depth,
824
+ label: options.label,
825
+ signal: options.signal,
646
826
  });
647
827
  if (repair) {
648
828
  // The program is fixed and has run; failing to write this down must not turn that into an error.
649
829
  try {
650
830
  const entry = { ts: Date.now(), message: `Repair attempt ${repair.attempt + 1}/${maxRepairAttempts}`, data: { error: repair.error } };
651
831
  appendFileSync(guardPath(projectDir, join("logs", "latest.jsonl")), JSON.stringify(entry) + "\n");
652
- console.log(`[trama] Repair attempt ${repair.attempt + 1}/${maxRepairAttempts}`);
832
+ console.log(tagged(options.label, `[trama] Repair attempt ${repair.attempt + 1}/${maxRepairAttempts}`));
653
833
  copyToHistory(projectDir, "repair", repair.error);
654
834
  }
655
835
  catch (err) {
656
- console.warn(`[trama] repair bookkeeping failed: ${err instanceof Error ? err.message : err}`);
836
+ console.warn(tagged(options.label, `[trama] repair bookkeeping failed: ${err instanceof Error ? err.message : err}`));
657
837
  }
658
838
  }
659
839
  return result;
package/dist/tools.d.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import type { Tools } from "./types.js";
2
2
  export interface ToolsWithCleanup extends Tools {
3
- /** Kill every shell command still running, and anything they left in the background. */
4
- killActiveShells(): void;
3
+ /** Stop every shell command still running, and anything they left in the background. Resolves when they are gone. */
4
+ stopActiveShells(): Promise<void>;
5
5
  }
6
6
  export declare function createTools(projectDir: string, signal?: AbortSignal): ToolsWithCleanup;
package/dist/tools.js CHANGED
@@ -2,8 +2,8 @@ import { spawn } from "child_process";
2
2
  import { readFileSync, writeFileSync, mkdirSync } from "fs";
3
3
  import { resolve, dirname } from "path";
4
4
  import { guardPath } from "./path-guard.js";
5
- import { signalGroup, superviseChild } from "./child-process.js";
6
- import { untilSettled } from "./lifetime.js";
5
+ import { signalGroup, stopGroups, superviseChild } from "./child-process.js";
6
+ import { stopWithThisProcess } from "./watchdog.js";
7
7
  const MAX_FETCH_BODY = 10 * 1024 * 1024; // 10 MB
8
8
  const DEFAULT_SHELL_TIMEOUT = 30_000;
9
9
  const GROUP_SWEEP_MS = 250;
@@ -13,7 +13,7 @@ export function createTools(projectDir, signal) {
13
13
  // starts stay killable after the shell itself exits. A group is tracked from
14
14
  // spawn until it has no members left. `shellExited` marks groups whose shell
15
15
  // has exited — only those are probed, since a group that is still starting
16
- // up may not be visible yet. `forget` tells the process-lifetime guard the
16
+ // up may not be visible yet. `forget` tells the watchdog the
17
17
  // group no longer needs killing if this process dies.
18
18
  const groups = new Map();
19
19
  let sweeper = null;
@@ -21,9 +21,12 @@ export function createTools(projectDir, signal) {
21
21
  groups.get(pgid)?.forget();
22
22
  groups.delete(pgid);
23
23
  };
24
- // Shell commands must not see the bridge's address or the init file (which
25
- // holds its secret). A top-level runner has neither in its environment, but
26
- // a runner inside a program — a session's creator — inherits both.
24
+ // Shell commands run here do not get the bridge's address or the init file
25
+ // (which holds its secret). A runner normally has neither in its
26
+ // environment; it does when it is working inside a program — which create
27
+ // and update still do when a program calls them. (This covers tools.shell
28
+ // only: what the agent backend runs on its own takes its environment from
29
+ // this process.)
27
30
  const { TRAMA_PORT: _port, TRAMA_INIT: _init, ...shellEnv } = process.env;
28
31
  const stopSweeping = () => {
29
32
  if (sweeper)
@@ -47,7 +50,7 @@ export function createTools(projectDir, signal) {
47
50
  const markShellExited = (pgid) => {
48
51
  const group = groups.get(pgid);
49
52
  if (!group)
50
- return; // already killed by killActiveShells
53
+ return; // already stopped by stopActiveShells
51
54
  group.shellExited = true;
52
55
  if (!sweeper) {
53
56
  sweeper = setInterval(sweep, GROUP_SWEEP_MS);
@@ -55,11 +58,11 @@ export function createTools(projectDir, signal) {
55
58
  }
56
59
  };
57
60
  return {
58
- killActiveShells() {
59
- for (const pgid of [...groups.keys()]) {
60
- signalGroup(pgid, "SIGKILL");
61
+ async stopActiveShells() {
62
+ const pgids = [...groups.keys()];
63
+ await stopGroups(pgids);
64
+ for (const pgid of pgids)
61
65
  untrack(pgid);
62
- }
63
66
  stopSweeping();
64
67
  },
65
68
  async read(path) {
@@ -88,7 +91,7 @@ export function createTools(projectDir, signal) {
88
91
  });
89
92
  const pgid = child.pid;
90
93
  if (pgid) {
91
- groups.set(pgid, { shellExited: false, forget: untilSettled(() => signalGroup(pgid, "SIGKILL")) });
94
+ groups.set(pgid, { shellExited: false, forget: stopWithThisProcess(pgid) });
92
95
  }
93
96
  try {
94
97
  const exit = await superviseChild(child, { timeout: options.timeout ?? DEFAULT_SHELL_TIMEOUT });
@@ -0,0 +1,19 @@
1
+ /**
2
+ * Make sure there is a watchdog before anything is started that would need
3
+ * one. Throws if one cannot be started: running without it would mean leaving
4
+ * processes behind with nobody to stop them.
5
+ */
6
+ export declare function requireWatchdog(): void;
7
+ /**
8
+ * Register a process group this process started: if this process ends before
9
+ * the returned function is called, the group is stopped.
10
+ */
11
+ export declare function stopWithThisProcess(pgid: number): () => void;
12
+ /**
13
+ * Register a temp directory this process created: if this process ends before
14
+ * the returned function is called, the directory is removed — once the groups
15
+ * that may be writing to it are gone.
16
+ */
17
+ export declare function removeWithThisProcess(dir: string): () => void;
18
+ /** Remove a temp directory. Best-effort: failing to clean up must never change a run's outcome. */
19
+ export declare function removeTempDir(dir: string): void;