@trama-dev/runtime 0.3.0 → 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.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import type { RunOptions, TramaConfig, ProgramResult } from "./runner-types.js";
2
- import type { AgentBackend } from "./agent-backend.js";
2
+ import { type AgentBackend } from "./agent-backend.js";
3
3
  /**
4
4
  * Everything a project directory needs around program.ts before it can run:
5
5
  * history/ and logs/, an ESM package.json, .gitignore entries, and links to the
@@ -63,7 +63,9 @@ export declare const REPAIR_SYSTEM_PROMPT = "You are a TypeScript repair tool.";
63
63
  * repaired. Throws if it cannot be made to run.
64
64
  *
65
65
  * Only the project's own files are shielded. What the program does beyond
66
- * them — network calls, shell commands, other projects it runs — is real.
66
+ * them — network calls, shell commands, agent calls — is real. A run it asks
67
+ * its runner for is not started: the validation ends where it asks for the
68
+ * first.
67
69
  */
68
70
  export declare function validateProgram(projectDir: string, backend: AgentBackend, candidate: string, options: {
69
71
  timeout: number;
@@ -82,5 +84,13 @@ export declare function installValidatedProgram(projectDir: string, validated: {
82
84
  source: string;
83
85
  repairedError?: string;
84
86
  }, reason: "create" | "update", prompt: string): void;
85
- export declare function runProgram(options: RunOptions): Promise<ProgramResult>;
87
+ /**
88
+ * Run a project, in this process: this is what a runner does.
89
+ *
90
+ * `depth` is how many runs deep this one is — 0 unless a program asked for it
91
+ * (see the "/run/program" call), in which case it is one more than that
92
+ * program's own. One runner carries the whole tree, so it is also where the
93
+ * tree is kept from growing without bound.
94
+ */
95
+ export declare function runProgram(options: RunOptions, depth?: number): Promise<ProgramResult>;
86
96
  export {};
package/dist/runner.js CHANGED
@@ -4,6 +4,7 @@ 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
10
  import { createAgent, stripCodeFences } from "./agent.js";
@@ -11,8 +12,7 @@ import { createTools } from "./tools.js";
11
12
  import { createWorkspace } from "./workspace.js";
12
13
  import { guardPath } from "./path-guard.js";
13
14
  import { createAllowance, stopGroups, superviseChild } from "./child-process.js";
14
- import { openBridge } from "./bridge-client.js";
15
- import { removeTempDir, removeWithThisProcess, stopWithThisProcess } from "./lifetime.js";
15
+ import { removeTempDir, removeWithThisProcess, requireWatchdog, stopWithThisProcess } from "./watchdog.js";
16
16
  import { createIPCServer, listen, closeServer } from "./ipc-server.js";
17
17
  // --- Locating the runtime itself ---
18
18
  /** The installed @trama-dev/runtime package — this file lives in its dist/. */
@@ -193,7 +193,10 @@ export function loadProjectConfig(projectDir) {
193
193
  * everything else is handed one and does not know which it is.
194
194
  */
195
195
  export function createBackend(config) {
196
- return new PiAdapter(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) };
197
200
  }
198
201
  export function loadState(projectDir) {
199
202
  const statePath = guardPath(projectDir, "state.json");
@@ -363,6 +366,34 @@ async function withStagedCopy(realDir, fn) {
363
366
  function tail(text, max = 20_000) {
364
367
  return text.length <= max ? text : `[… ${text.length - max} earlier characters omitted]\n${text.slice(-max)}`;
365
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
+ }
366
397
  const describeFailure = (r) => `program.ts exited with code ${r.exitCode}\nstdout: ${tail(r.stdout)}\nstderr: ${tail(r.stderr)}`;
367
398
  /**
368
399
  * Hand the program its starting state through a private temp file rather than
@@ -384,7 +415,7 @@ function toChildResult(exit) {
384
415
  const { stdout, stderr } = exit;
385
416
  if (exit.timedOut)
386
417
  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.
418
+ // Stopped by us at the end of a validation — going down on SIGTERM is the expected outcome.
388
419
  if (exit.stopped && (exit.code === 0 || exit.signal === "SIGTERM"))
389
420
  return { exitCode: 0, stdout, stderr };
390
421
  return { exitCode: exit.code ?? 1, stdout, stderr };
@@ -419,26 +450,35 @@ function settle(projectDir, child, terminalSignal) {
419
450
  * (bad project, server or spawn failure) or left state.json unreadable.
420
451
  */
421
452
  async function runProgramOnce(options) {
422
- const { projectDir, backend, 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();
423
457
  ensureProjectScaffold(projectDir);
424
458
  // Cancels in-flight LLM calls, fetches and observes once the run is over.
425
459
  const runEnded = new AbortController();
426
- // Asks the program to stop once it has been ready for the grace period.
427
- 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();
428
462
  let readyTimer = null;
429
463
  let terminalSignal = null;
430
464
  const ctx = createContext(projectDir, loadState(projectDir), {
431
465
  maxIterations,
432
466
  argsOverride,
433
- onReady: stopOnReady && (() => {
434
- readyTimer ??= setTimeout(() => readyStop.abort(), stopOnReady.graceMs).unref();
467
+ onReady: validating && (() => {
468
+ readyTimer ??= setTimeout(() => validated.abort(), validating.readyGraceMs).unref();
435
469
  }),
470
+ print: line => console.log(tagged(label, line)),
436
471
  });
437
472
  // Truncate logs only after preflight succeeds — preserves the prior run's
438
473
  // diagnostics if scaffolding, state loading, or context creation fails.
439
474
  writeFileSync(guardPath(projectDir, join("logs", "latest.jsonl")), "");
440
- // The program's own time. It stops while a run the program started is in flight.
475
+ // The program's own time. It stops while a run the program asked for is in flight.
441
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();
442
482
  const tools = createTools(projectDir, runEnded.signal);
443
483
  // Known only to this run's program, through its init file.
444
484
  const token = randomBytes(32).toString("hex");
@@ -448,14 +488,57 @@ async function runProgramOnce(options) {
448
488
  agent: createAgent(backend, projectDir, runEnded.signal),
449
489
  tools,
450
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
+ },
451
517
  // The first terminal signal wins; ctx itself rejects a conflicting second one.
452
518
  onTerminalSignal: result => { terminalSignal ??= result; },
453
- holdClock: () => allowance.hold(),
454
519
  });
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;
455
524
  // The program leads a process group of its own, so that everything it starts is in it.
456
525
  let programGroup;
457
- // If this process is stopped while the program is running, the program is stopped with it.
526
+ // If this process ends while the program is running, the watchdog stops the program.
458
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 });
459
542
  try {
460
543
  const child = await withTempDir("trama-init-", async (initDir) => {
461
544
  const port = await listen(server);
@@ -478,26 +561,46 @@ async function runProgramOnce(options) {
478
561
  programGroup = program.pid;
479
562
  if (programGroup)
480
563
  programSettled = stopWithThisProcess(programGroup);
481
- return toChildResult(await superviseChild(program, {
564
+ if (signal?.aborted)
565
+ stopProgram(); // asked to stop while the program was being started
566
+ const exit = await superviseChild(program, {
482
567
  timeout: allowance,
483
- stopSignal: stopOnReady ? readyStop.signal : undefined,
568
+ stopSignal: validating ? validated.signal : undefined,
484
569
  sinks: {
485
- stdout: chunk => { process.stdout.write(chunk); },
486
- 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); },
487
572
  },
488
- }));
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);
489
581
  });
490
- 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) };
491
586
  }
492
587
  finally {
493
588
  // 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.
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();
497
596
  if (readyTimer)
498
597
  clearTimeout(readyTimer);
499
598
  runEnded.abort();
500
- await Promise.all([stopGroups(programGroup ? [programGroup] : []), tools.stopActiveShells()]);
599
+ await Promise.all([
600
+ stopGroups(programGroup ? [programGroup] : []),
601
+ tools.stopActiveShells(),
602
+ Promise.allSettled([...nestedRuns]),
603
+ ]);
501
604
  programSettled();
502
605
  server.closeAllConnections();
503
606
  await closeServer(server).catch(() => { });
@@ -521,11 +624,13 @@ async function requestRepair(options, input, repairErrors) {
521
624
  return withTempDir("trama-repair-", async (tempDir) => {
522
625
  copyDirInto(options.projectDir, tempDir);
523
626
  writeFileSync(guardPath(tempDir, "program.ts"), input.programSource);
524
- const controller = new AbortController();
525
- 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;
526
631
  try {
527
632
  const fixed = stripCodeFences(await options.backend.ask(repairPrompt(input), {
528
- cwd: tempDir, system: REPAIR_SYSTEM_PROMPT, signal: controller.signal,
633
+ cwd: tempDir, system: REPAIR_SYSTEM_PROMPT, signal,
529
634
  }));
530
635
  if (fixed.trim() === "")
531
636
  throw new Error("The repair returned an empty program.");
@@ -538,7 +643,7 @@ async function requestRepair(options, input, repairErrors) {
538
643
  return null;
539
644
  }
540
645
  finally {
541
- clearTimeout(timer);
646
+ limit.cancel();
542
647
  }
543
648
  });
544
649
  }
@@ -582,9 +687,18 @@ async function tryFix(options, fixed) {
582
687
  async function executeProgram(options) {
583
688
  const { projectDir, maxRepairAttempts } = options;
584
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();
585
697
  const firstRun = await runProgramOnce(options);
586
698
  if (firstRun.outcome)
587
699
  return { result: firstRun.outcome };
700
+ if (stopped())
701
+ return wasStopped();
588
702
  let lastError = firstRun.failure;
589
703
  if (maxRepairAttempts === 0)
590
704
  return failed(`Program failed (repair disabled): ${lastError}`);
@@ -595,12 +709,16 @@ async function executeProgram(options) {
595
709
  ? `\nRepair errors:\n${repairErrors.map((e, i) => ` [${i + 1}] ${e}`).join("\n")}` : "";
596
710
  for (let attempt = 0; attempt < maxRepairAttempts; attempt++) {
597
711
  const fixed = await requestRepair(options, { programSource: currentSource, error: lastError }, repairErrors);
712
+ if (stopped())
713
+ return wasStopped();
598
714
  if (!fixed)
599
715
  return failed(`Failed after ${attempt + 1} repair attempt(s): ${lastError}${repairDetails()}`);
600
716
  currentSource = fixed;
601
717
  const run = await tryFix(options, fixed);
602
718
  if (run.outcome)
603
719
  return { result: run.outcome, repair: { attempt, error: lastError } };
720
+ if (stopped())
721
+ return wasStopped();
604
722
  lastError = run.failure;
605
723
  }
606
724
  return failed(`Failed after ${maxRepairAttempts} repair attempts: ${lastError}${repairDetails()}`);
@@ -614,7 +732,9 @@ const VALIDATION_READY_GRACE_MS = 2_000;
614
732
  * repaired. Throws if it cannot be made to run.
615
733
  *
616
734
  * 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.
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.
618
738
  */
619
739
  export async function validateProgram(projectDir, backend, candidate, options) {
620
740
  return withTempDir("trama-validate-", async (trialDir) => {
@@ -625,7 +745,8 @@ export async function validateProgram(projectDir, backend, candidate, options) {
625
745
  ...options,
626
746
  projectDir: trialDir,
627
747
  backend,
628
- stopOnReady: { graceMs: VALIDATION_READY_GRACE_MS },
748
+ depth: 0,
749
+ validating: { readyGraceMs: VALIDATION_READY_GRACE_MS },
629
750
  });
630
751
  if (result.status === "failed") {
631
752
  throw new Error(`Program failed: ${result.reason}`);
@@ -648,39 +769,35 @@ export function installValidatedProgram(projectDir, validated, reason, prompt) {
648
769
  copyToHistory(projectDir, reason, prompt);
649
770
  }
650
771
  // --- Core execution ---
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;
651
776
  /**
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.
656
- *
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.
777
+ * Run a project, in this process: this is what a runner does.
659
778
  *
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.
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.
663
783
  */
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 */ }
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.`);
671
788
  }
672
- return () => { };
673
- }
674
- export async function runProgram(options) {
675
- const releaseParentClock = holdParentClock();
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;
676
793
  try {
677
- return await runProject(options);
794
+ return await runProject(options, depth);
678
795
  }
679
796
  finally {
680
- releaseParentClock();
797
+ runsInFlight -= 1;
681
798
  }
682
799
  }
683
- async function runProject(options) {
800
+ async function runProject(options, depth) {
684
801
  const { projectDir } = options;
685
802
  if (!existsSync(join(projectDir, "meta.json"))) {
686
803
  throw new Error(`Project not found at ${projectDir}. ` +
@@ -703,17 +820,20 @@ async function runProject(options) {
703
820
  maxIterations: config.defaultMaxIterations,
704
821
  argsOverride: options.args,
705
822
  workspaceDir: options.workspaceDir,
823
+ depth,
824
+ label: options.label,
825
+ signal: options.signal,
706
826
  });
707
827
  if (repair) {
708
828
  // The program is fixed and has run; failing to write this down must not turn that into an error.
709
829
  try {
710
830
  const entry = { ts: Date.now(), message: `Repair attempt ${repair.attempt + 1}/${maxRepairAttempts}`, data: { error: repair.error } };
711
831
  appendFileSync(guardPath(projectDir, join("logs", "latest.jsonl")), JSON.stringify(entry) + "\n");
712
- console.log(`[trama] Repair attempt ${repair.attempt + 1}/${maxRepairAttempts}`);
832
+ console.log(tagged(options.label, `[trama] Repair attempt ${repair.attempt + 1}/${maxRepairAttempts}`));
713
833
  copyToHistory(projectDir, "repair", repair.error);
714
834
  }
715
835
  catch (err) {
716
- 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}`));
717
837
  }
718
838
  }
719
839
  return result;
package/dist/tools.js CHANGED
@@ -3,7 +3,7 @@ import { readFileSync, writeFileSync, mkdirSync } from "fs";
3
3
  import { resolve, dirname } from "path";
4
4
  import { guardPath } from "./path-guard.js";
5
5
  import { signalGroup, stopGroups, superviseChild } from "./child-process.js";
6
- import { stopWithThisProcess } from "./lifetime.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;
@@ -22,10 +22,11 @@ export function createTools(projectDir, signal) {
22
22
  groups.delete(pgid);
23
23
  };
24
24
  // Shell commands run here do not get the bridge's address or the init file
25
- // (which holds its secret). A top-level runner has neither in its
26
- // environment, but a runner inside a program — a session's creator —
27
- // inherits both. (This covers tools.shell only: what the agent backend runs
28
- // on its own takes its environment from this process.)
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.)
29
30
  const { TRAMA_PORT: _port, TRAMA_INIT: _init, ...shellEnv } = process.env;
30
31
  const stopSweeping = () => {
31
32
  if (sweeper)
@@ -1,11 +1,18 @@
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;
1
7
  /**
2
8
  * Register a process group this process started: if this process ends before
3
- * the returned function is called, the group is stopped (see stopGroupsOnExit).
9
+ * the returned function is called, the group is stopped.
4
10
  */
5
11
  export declare function stopWithThisProcess(pgid: number): () => void;
6
12
  /**
7
13
  * Register a temp directory this process created: if this process ends before
8
- * the returned function is called, the directory is removed.
14
+ * the returned function is called, the directory is removed — once the groups
15
+ * that may be writing to it are gone.
9
16
  */
10
17
  export declare function removeWithThisProcess(dir: string): () => void;
11
18
  /** Remove a temp directory. Best-effort: failing to clean up must never change a run's outcome. */
@@ -0,0 +1,167 @@
1
+ // What must not outlive this process: the process groups it started, and the
2
+ // temp directories it made.
3
+ //
4
+ // A program, and every shell command it runs, leads its own process group — so
5
+ // that a timeout can take down everything it started. The cost is that none of
6
+ // them die with the runner. Something has to stop them when the runner goes,
7
+ // and it cannot be the runner: a process that is killed outright, or runs out
8
+ // of memory, or crashes, runs no code on its way out.
9
+ //
10
+ // So it is a process of its own, the watchdog. The runner keeps a pipe to it
11
+ // open, and tells it what it has started and what has ended. When the pipe
12
+ // closes — the runner is gone, however it went — the watchdog stops whatever
13
+ // is still on its list and deletes what is left of the directories. One runner
14
+ // carries every run of a session, so one list covers the whole tree.
15
+ //
16
+ // Nothing here listens for a signal or for the process exiting: the process
17
+ // that hosts a runner keeps its own way of handling both.
18
+ import { spawn } from "child_process";
19
+ import { rmSync } from "fs";
20
+ import { STOP_TIMINGS, onGroupAskedToStop } from "./child-process.js";
21
+ // Run by the watchdog process. It applies the same policy as stopGroups (see
22
+ // child-process.ts): ask, wait out the grace period, kill what is left. A
23
+ // group the runner had already asked is not asked a second time.
24
+ const WATCHDOG = `
25
+ const { rmSync } = require("fs");
26
+ const { grace, settle, poll } = JSON.parse(process.argv[1]);
27
+ const lists = { g: new Set(), d: new Set(), asked: new Set() };
28
+ const alive = (pgid) => { try { process.kill(-pgid, 0); return true; } catch { return false; } };
29
+ const signal = (pgid, name) => { try { process.kill(-pgid, name); } catch {} };
30
+
31
+ let unread = "";
32
+ process.stdin.setEncoding("utf8");
33
+ process.stdin.on("data", (chunk) => {
34
+ unread += chunk;
35
+ for (let end; (end = unread.indexOf("\\n")) !== -1; unread = unread.slice(end + 1)) {
36
+ const [op, list, item] = JSON.parse(unread.slice(0, end));
37
+ lists[list][op === "+" ? "add" : "delete"](item);
38
+ }
39
+ });
40
+
41
+ // The pipe has closed: the runner is gone.
42
+ let leaving = false;
43
+ const takeOver = () => {
44
+ if (leaving) return;
45
+ leaving = true;
46
+ const finish = () => {
47
+ for (const dir of lists.d) { try { rmSync(dir, { recursive: true, force: true }); } catch {} }
48
+ process.exit(0);
49
+ };
50
+ let left = [...lists.g].filter(alive);
51
+ for (const pgid of left) { if (!lists.asked.has(pgid)) signal(pgid, "SIGTERM"); }
52
+ let deadline = performance.now() + grace;
53
+ let killed = false;
54
+ const check = () => {
55
+ // A group seen gone is never signalled again: its id may belong to another by now.
56
+ left = left.filter(alive);
57
+ if (left.length === 0) return finish();
58
+ if (performance.now() < deadline) return;
59
+ if (killed) return finish();
60
+ for (const pgid of left) signal(pgid, "SIGKILL");
61
+ killed = true;
62
+ deadline = performance.now() + settle;
63
+ };
64
+ check();
65
+ setInterval(check, poll);
66
+ };
67
+ process.stdin.on("end", takeOver);
68
+ process.stdin.on("close", takeOver);
69
+ process.stdin.on("error", takeOver);
70
+ `;
71
+ /** What this process has told the watchdog about and not yet taken back. */
72
+ const pending = { g: new Set(), d: new Set(), asked: new Set() };
73
+ let watchdog = null;
74
+ const tell = (to, op, list, item) => {
75
+ to.stdin?.write(JSON.stringify([op, list, item]) + "\n");
76
+ };
77
+ /**
78
+ * Start the watchdog if there is none, and return it — or null if it cannot be
79
+ * started. A watchdog that has itself died is replaced, and told again what is
80
+ * still pending.
81
+ */
82
+ function startWatchdog() {
83
+ if (watchdog)
84
+ return watchdog;
85
+ let child;
86
+ try {
87
+ child = spawn(process.execPath, ["-e", WATCHDOG, JSON.stringify(STOP_TIMINGS)], {
88
+ detached: true, // a signal sent to this process's group must not reach it
89
+ stdio: ["pipe", "ignore", "ignore"],
90
+ });
91
+ }
92
+ catch {
93
+ return null;
94
+ }
95
+ const lost = () => { if (watchdog === child)
96
+ watchdog = null; };
97
+ child.on("error", lost);
98
+ child.on("exit", lost);
99
+ child.stdin?.on("error", lost);
100
+ if (child.pid === undefined)
101
+ return null; // a failed spawn has no pid from the start
102
+ // Neither the watchdog nor the pipe to it keeps this process alive.
103
+ child.unref();
104
+ child.stdin?.unref?.();
105
+ watchdog = child;
106
+ for (const list of ["g", "d", "asked"]) {
107
+ for (const item of pending[list])
108
+ tell(child, "+", list, item);
109
+ }
110
+ return child;
111
+ }
112
+ /**
113
+ * Make sure there is a watchdog before anything is started that would need
114
+ * one. Throws if one cannot be started: running without it would mean leaving
115
+ * processes behind with nobody to stop them.
116
+ */
117
+ export function requireWatchdog() {
118
+ if (!startWatchdog()) {
119
+ throw new Error("Could not start trama's watchdog process, which stops what a run started if the runner dies.");
120
+ }
121
+ }
122
+ /** Keep `item` on the watchdog's list until the returned function is called. */
123
+ function watch(list, item) {
124
+ pending[list].add(item);
125
+ const to = startWatchdog();
126
+ if (to)
127
+ tell(to, "+", list, item);
128
+ return () => {
129
+ if (!pending[list].delete(item))
130
+ return;
131
+ if (watchdog)
132
+ tell(watchdog, "-", list, item);
133
+ };
134
+ }
135
+ /**
136
+ * Register a process group this process started: if this process ends before
137
+ * the returned function is called, the group is stopped.
138
+ */
139
+ export function stopWithThisProcess(pgid) {
140
+ const forget = watch("g", pgid);
141
+ return () => {
142
+ forget();
143
+ asked.get(pgid)?.();
144
+ asked.delete(pgid);
145
+ };
146
+ }
147
+ /** Groups on the watchdog's list that this process has asked to stop, and how to take each off again. */
148
+ const asked = new Map();
149
+ onGroupAskedToStop((pgid) => {
150
+ if (pending.g.has(pgid) && !asked.has(pgid))
151
+ asked.set(pgid, watch("asked", pgid));
152
+ });
153
+ /**
154
+ * Register a temp directory this process created: if this process ends before
155
+ * the returned function is called, the directory is removed — once the groups
156
+ * that may be writing to it are gone.
157
+ */
158
+ export function removeWithThisProcess(dir) {
159
+ return watch("d", dir);
160
+ }
161
+ /** Remove a temp directory. Best-effort: failing to clean up must never change a run's outcome. */
162
+ export function removeTempDir(dir) {
163
+ try {
164
+ rmSync(dir, { recursive: true, force: true });
165
+ }
166
+ catch { /* left for the OS to reap */ }
167
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@trama-dev/runtime",
3
- "version": "0.3.0",
3
+ "version": "0.3.1",
4
4
  "type": "module",
5
5
  "exports": {
6
6
  ".": {