@trama-dev/runtime 0.5.0 → 0.6.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
@@ -5,18 +5,19 @@ import { homedir, tmpdir } from "os";
5
5
  import { fileURLToPath } from "url";
6
6
  import { createHash, randomBytes } from "crypto";
7
7
  import { onAbort, rejectOnAbort } from "./abort.js";
8
+ import { checkedBudget, createMeter } from "./budget.js";
8
9
  import { PiAdapter } from "./pi-adapter.js";
9
10
  import { LATEST_LOG_PATH, appendLogEntry, createContext } from "./context.js";
10
11
  import { createAgent, stripCodeFences } from "./agent.js";
11
12
  import { createTools } from "./tools.js";
12
13
  import { createWorkspace } from "./workspace.js";
13
14
  import { guardPath, identityOf, projectAt, realRootOf, sameProjectAs, wayTo } from "./path-guard.js";
14
- import { copyTree, entryAt, mergeTree, pathAsListed, readTree } from "./tree.js";
15
+ import { copyTree, differences, entryAt, mergeTree, pathAsListed, readTree } from "./tree.js";
15
16
  import { stageFile } from "./replace-file.js";
16
17
  import { readProjectMeta } from "./meta.js";
17
18
  import { describeJson, isJsonObject } from "./serializable.js";
18
- import { createAllowance, superviseChild } from "./child-process.js";
19
- import { removeTempDir, removeWithThisProcess, requireWatchdog, stopGroups, stopWithThisProcess } from "./stopping.js";
19
+ import { checkedEnv, createAllowance, superviseChild } from "./child-process.js";
20
+ import { KILL_GRACE_MS, removeTempDir, removeWithThisProcess, requireWatchdog, stopGroups, stopWithThisProcess } from "./stopping.js";
20
21
  import { createIPCServer, listen, closeServer } from "./ipc-server.js";
21
22
  import { journalEntriesOf, openJournal } from "./journal.js";
22
23
  import { messageOf } from "./errors.js";
@@ -152,6 +153,7 @@ export function loadConfig() {
152
153
  defaultTimeout: 300_000,
153
154
  defaultMaxIterations: 100,
154
155
  journalRuns: 20,
156
+ agentChanges: "keep",
155
157
  };
156
158
  let raw;
157
159
  try {
@@ -188,12 +190,20 @@ function checkedConfig(merged, source) {
188
190
  [Number.isFinite(merged.defaultTimeout) && merged.defaultTimeout > 0, `"defaultTimeout" must be a positive number (got ${merged.defaultTimeout})`],
189
191
  [pint(merged.defaultMaxIterations), `"defaultMaxIterations" must be a positive integer (got ${merged.defaultMaxIterations})`],
190
192
  [Number.isInteger(merged.journalRuns) && merged.journalRuns >= 0, `"journalRuns" must be a non-negative integer (got ${merged.journalRuns})`],
193
+ [merged.agentChanges === "keep" || merged.agentChanges === "discard", `"agentChanges" must be "keep" or "discard" (got ${JSON.stringify(merged.agentChanges)})`],
191
194
  ];
192
195
  for (const [ok, msg] of checks) {
193
196
  if (!ok)
194
197
  throw new Error(`Invalid ${source}: ${msg}`);
195
198
  }
196
- return merged;
199
+ if (merged.budget === undefined)
200
+ return merged;
201
+ try {
202
+ return { ...merged, budget: checkedBudget(merged.budget, `"budget"`) };
203
+ }
204
+ catch (err) {
205
+ throw new Error(`Invalid ${source}: ${messageOf(err)}`);
206
+ }
197
207
  }
198
208
  /** The global config, with the model/provider a project was created with taking precedence. */
199
209
  export function loadProjectConfig(projectDir, meta = readProjectMeta(projectDir)) {
@@ -210,13 +220,119 @@ export function loadProjectConfig(projectDir, meta = readProjectMeta(projectDir)
210
220
  /**
211
221
  * What does the LLM work for a project. The only place that picks a backend:
212
222
  * everything else is handed one and does not know which it is.
223
+ *
224
+ * It is also where what is asked of a model is counted, and held to a
225
+ * budget (`meter`): every call passes here, whoever makes it. A call that
226
+ * comes when the budget is spent is refused; one under way is stopped where
227
+ * its agent would ask the model again — what the model was asked before
228
+ * that is used, and what it was answering is let finish. `spent` is told
229
+ * why, the first time either happens.
213
230
  */
214
- export function createBackend(config) {
215
- const backend = new PiAdapter(config);
216
- // The interface promises that a cancelled call rejects, and a run's end
217
- // waits on that. Every backend is held to it here, rather than trusted with it.
218
- return { ask: (prompt, call) => rejectOnAbort(backend.ask(prompt, call), call.signal) };
231
+ export function createBackend(config, meter = createMeter(), spent = () => { }, env) {
232
+ // (`env`: the variables of the run whose calls these are — its agents' too, as they are its program's and its commands'.)
233
+ const backend = new PiAdapter(config, env);
234
+ // The calls that were cancelled.
235
+ const cutOff = new Set();
236
+ // Why a call was first refused, or stopped, for the budget.
237
+ let refused;
238
+ const overBudget = (why) => {
239
+ if (refused === undefined)
240
+ spent(why);
241
+ refused ??= why;
242
+ return new Error(why);
243
+ };
244
+ return {
245
+ spent: () => meter.spent(),
246
+ refused: () => refused,
247
+ counts: () => meter.capped(),
248
+ // The interface promises that a cancelled call rejects, and a run's end
249
+ // waits on that. Every backend is held to it here, rather than trusted with it.
250
+ async ask(prompt, call) {
251
+ let account;
252
+ try {
253
+ account = meter.admit();
254
+ }
255
+ catch (err) {
256
+ throw overBudget(messageOf(err));
257
+ }
258
+ // Stops the call where the budget is reached while it is under way.
259
+ const over = new AbortController();
260
+ let why;
261
+ const signal = call.signal ? AbortSignal.any([call.signal, over.signal]) : over.signal;
262
+ const work = backend.ask(prompt, {
263
+ ...call,
264
+ signal,
265
+ sofar(usage, answered) {
266
+ const reached = account.sofar(usage);
267
+ call.sofar?.(usage, answered);
268
+ // A call that is over keeps what it ended with — its answer, or its own failure: what would be
269
+ // asked beside it is not asked, and that is all. (It is a request refused for the budget all the
270
+ // same, and said as one.)
271
+ if (answered) {
272
+ const spent = why ?? reached;
273
+ if (spent === undefined)
274
+ return true;
275
+ overBudget(spent);
276
+ return false;
277
+ }
278
+ // (Once it is to stop, it is to stop — whatever is said of it after.)
279
+ why ??= reached;
280
+ if (why === undefined)
281
+ return true;
282
+ over.abort();
283
+ return false;
284
+ },
285
+ // (What the call has used is counted from when it is known: nothing is stopped for it here — a reply that
286
+ // has come is not taken back — but whatever is asked next, by this call or another, is asked against it.)
287
+ had(usage) {
288
+ account.sofar(usage);
289
+ call.had?.(usage);
290
+ },
291
+ used(usage) {
292
+ account.sofar(usage);
293
+ call.used?.(usage);
294
+ },
295
+ });
296
+ const off = onAbort(signal, () => { cutOff.add(work); });
297
+ // What the call used is counted as its own until the backend has let go of it — which
298
+ // is when it has said the last of it — however long ago whoever asked was answered.
299
+ const settled = () => {
300
+ off();
301
+ account.close();
302
+ };
303
+ work.then(settled, settled);
304
+ try {
305
+ return await rejectOnAbort(work, signal);
306
+ }
307
+ catch (err) {
308
+ // (Stopped by whoever asked, it was stopped by them, whatever the budget had come to.)
309
+ throw why !== undefined && !call.signal?.aborted ? overBudget(why) : err;
310
+ }
311
+ },
312
+ close: () => backend.close(),
313
+ async letGo() {
314
+ let giveUp;
315
+ await Promise.race([
316
+ Promise.allSettled(cutOff),
317
+ new Promise(resolve => { giveUp = setTimeout(resolve, KILL_GRACE_MS); }),
318
+ ]);
319
+ clearTimeout(giveUp);
320
+ },
321
+ };
219
322
  }
323
+ /** The budgets of which it has been said that they are spent. */
324
+ const saidSpent = new WeakSet();
325
+ /**
326
+ * Say that a budget is spent, once for the budget — whoever comes up against
327
+ * it first: the run's own backend, or the backend of a project being made
328
+ * for the run's program, of which there may be many.
329
+ */
330
+ export const saysOnce = (meter, say) => (why) => {
331
+ if (saidSpent.has(meter))
332
+ return;
333
+ saidSpent.add(meter);
334
+ say(why);
335
+ };
220
336
  export function loadState(projectDir) {
221
337
  const statePath = guardPath(projectDir, "state.json");
222
338
  let raw;
@@ -363,13 +479,103 @@ function whereMade(place) {
363
479
  return dir;
364
480
  }
365
481
  /**
366
- * Make, in `privateDir`, a copy of a project to try a program in: what the
367
- * project is and holds (see copyTree), with `program` as its program.ts.
368
- * Returns where the copy is, and what the project was when it was copied.
482
+ * Put a program where a copy of a project has its program.ts — whatever the
483
+ * directory it goes in allows: a copy is where programs are tried and
484
+ * replaced. The new file allows what `mode` says or, where that is not said,
485
+ * what the one it takes the place of allows — and its owner to replace it.
486
+ * Throws where a directory is in the place of the program: `root` is the
487
+ * project the copy is of, for saying so.
488
+ */
489
+ function putProgram(copyDir, root, program, mode) {
490
+ const place = guardPath(copyDir, "program.ts");
491
+ const had = statSync(place, { throwIfNoEntry: false });
492
+ if (had?.isDirectory())
493
+ throw new Error(`No program can be tried in a copy of ${root}: its program.ts is a directory.`);
494
+ inDirOfCopy(whereMade(place), () => stageFile(copyDir, "program.ts", program, mode ?? (had && (had.mode | 0o200))).commit());
495
+ }
496
+ /**
497
+ * All that makes a directory's program.ts lead to its program, as the
498
+ * directory stands: the name, each link and each directory on the way, the
499
+ * file — each by what it is (see Entry), which is asked of the place,
500
+ * whatever its directory lists or allows.
501
+ */
502
+ const programParts = (dir) => wayTo(dir, "program.ts").flatMap((place) => {
503
+ const entry = entryAt(place);
504
+ return entry && entry.kind !== "other" ? [entry.id] : [];
505
+ });
506
+ function standAmong(root, privateDir) {
507
+ const among = dirname(root);
508
+ let names;
509
+ try {
510
+ names = readdirSync(among);
511
+ }
512
+ catch {
513
+ return { among, names: [] };
514
+ }
515
+ const put = names.filter((name) => {
516
+ const beside = join(among, name);
517
+ // (Not the directory all this is made in, where that is beside the project: it would stand beside itself.)
518
+ if (beside === privateDir)
519
+ return false;
520
+ try {
521
+ symlinkSync(beside, join(privateDir, name));
522
+ return true;
523
+ }
524
+ catch {
525
+ return false;
526
+ }
527
+ });
528
+ return { among, names: put };
529
+ }
530
+ /**
531
+ * What was done beside a copy that is not thereby done beside its project:
532
+ * each name made there, and each of those put there (see standAmong) that is
533
+ * gone, or is something else now — another link among them. Told as what did
534
+ * not arrive is told: the path — from the project — and why.
535
+ */
536
+ function strandedBeside(copy, beside) {
537
+ const dir = dirname(realRootOf(copy));
538
+ const put = new Set(beside.names);
539
+ const stranded = [];
540
+ /** Whether a name put there is still the link that was put there. */
541
+ const asPut = (name) => {
542
+ try {
543
+ return readlinkSync(join(dir, name)) === join(beside.among, name);
544
+ }
545
+ catch {
546
+ return false;
547
+ }
548
+ };
549
+ try {
550
+ for (const name of readdirSync(dir)) {
551
+ if (name === basename(copy) || put.has(name))
552
+ continue;
553
+ stranded.push({ path: `../${name}`, why: "it was made beside the copy that was worked in, and goes with it: beside the project there is no such thing" });
554
+ }
555
+ for (const name of beside.names) {
556
+ if (asPut(name))
557
+ continue;
558
+ stranded.push({ path: `../${name}`, why: "it was removed, or something else put there, beside the copy that was worked in: beside the project it is as it was" });
559
+ }
560
+ }
561
+ catch { /* what cannot be looked at has nothing told of it */ }
562
+ return stranded.sort((a, b) => (a.path < b.path ? -1 : a.path > b.path ? 1 : 0));
563
+ }
564
+ /**
565
+ * Make, in `privateDir`, a copy of a project — to try a program in, or for an
566
+ * agent to look at and work in: what the project is and holds (see copyTree),
567
+ * with `program` as its program.ts where one is given. Returns where the
568
+ * copy is, what the project was when it was copied, and the names put beside
569
+ * the copy for what is beside the project.
369
570
  *
370
571
  * The copy allows what the project allows, to everybody: so it is made in a
371
572
  * directory that is this runner's alone, and is nobody else's to come to. It
372
- * has the project's name there.
573
+ * has the project's name there, and what is beside the project beside it (see
574
+ * standAmong) — nothing else is to be in that directory. Where what is
575
+ * copied is itself a copy of a project — as where a candidate is validated
576
+ * in the project as an agent prepared it — `among` names the project: what
577
+ * is beside the copy is what is beside that, and nothing an agent made
578
+ * beside its own.
373
579
  *
374
580
  * The project's journals are not carried over: they are the record of its
375
581
  * runs, not part of what a run works on, and a copy is where a run is tried.
@@ -385,10 +591,12 @@ function whereMade(place) {
385
591
  * whyNotReplaceable). A project with a directory where its program should be
386
592
  * has no place for one, and is not copied to try one in.
387
593
  */
388
- function copyProjectWith(projectDir, privateDir, program) {
594
+ export function copyProjectWith(projectDir, privateDir, program, among = projectDir) {
389
595
  const root = projectAt(projectDir);
390
- const copyDir = join(realRootOf(privateDir), basename(root) || "project");
596
+ const itsOwn = realRootOf(privateDir);
597
+ const copyDir = join(itsOwn, basename(root) || "project");
391
598
  mkdirSync(copyDir);
599
+ const beside = standAmong(projectAt(among), itsOwn);
392
600
  const journals = journalEntriesOf(root);
393
601
  const theCopy = identityOf(copyDir);
394
602
  const held = copyTree(root, copyDir, (at, entry) => {
@@ -399,19 +607,16 @@ function copyProjectWith(projectDir, privateDir, program) {
399
607
  }
400
608
  return journals.has(entry.id);
401
609
  });
402
- const place = guardPath(copyDir, "program.ts");
403
- const had = statSync(place, { throwIfNoEntry: false });
404
- if (had?.isDirectory())
405
- throw new Error(`No program can be tried in a copy of ${root}: its program.ts is a directory.`);
406
- inDirOfCopy(whereMade(place), () => stageFile(copyDir, "program.ts", program, had && (had.mode | 0o200)).commit());
407
- return { copy: copyDir, held };
610
+ if (program !== undefined)
611
+ putProgram(copyDir, root, program);
612
+ return { copy: copyDir, held, beside };
408
613
  }
409
614
  /** The end of a long output — where the error is — with a note of how much was dropped. */
410
615
  function tail(text, max = 20_000) {
411
616
  return text.length <= max ? text : `[… ${text.length - max} earlier characters omitted]\n${text.slice(-max)}`;
412
617
  }
413
618
  /** A line as it is shown for a run: under the run's name, if it has one. */
414
- const tagged = (label, line) => label ? `[${label}] ${line}` : line;
619
+ export const tagged = (label, line) => label ? `[${label}] ${line}` : line;
415
620
  /** The longest stretch of output held back while waiting for its line to end. */
416
621
  const MAX_HELD_LINE = 64 * 1024;
417
622
  /** Put a label in front of each line written to a stream. `flush` writes out a last line that had no newline. */
@@ -539,7 +744,7 @@ async function runProgramOnce(options) {
539
744
  writeFileSync(guardPath(projectDir, LATEST_LOG_PATH), "");
540
745
  // The program's own time. It stops while a run the program asked for is in flight.
541
746
  const allowance = createAllowance(timeout);
542
- // Set when a validation ended because the program asked for another to be run.
747
+ // Set when a validation ended because the program asked for another to be run, or for a project to be made or changed.
543
748
  let handedOff = false;
544
749
  // Runs the program has asked for and that are still going. They belong to this run.
545
750
  const nestedRuns = new Set();
@@ -552,9 +757,19 @@ async function runProgramOnce(options) {
552
757
  };
553
758
  // The workspace of the session this run is part of, if it is part of one.
554
759
  const sessionWorkspace = workspaceDir ? workspaceAt(workspaceDir) : null;
555
- const tools = createTools(projectDir, runEnded.signal);
760
+ const tools = createTools(projectDir, runEnded.signal, options.env);
761
+ // As far as a validation goes: the program asks its runner for what would be real — a run, a project
762
+ // made. The call is left unanswered — an answer would only send the program on to do more — until
763
+ // the program, which is being stopped, lets go of it.
764
+ const handOff = (what, stop) => {
765
+ handedOff = what;
766
+ validated.abort();
767
+ return rejectOnAbort(new Promise(() => { }), stop);
768
+ };
556
769
  // Known only to this run's program, through its init file.
557
770
  const token = randomBytes(32).toString("hex");
771
+ // Whether the program's process has ended. (Nothing is an answer to it after that, and it is no longer there to stop.)
772
+ let programOver = false;
558
773
  const server = createIPCServer({
559
774
  token,
560
775
  ctx,
@@ -563,27 +778,47 @@ async function runProgramOnce(options) {
563
778
  workspace: sessionWorkspace,
564
779
  workspaceAt,
565
780
  journal,
566
- run: (request, stop, seq) => {
567
- if (validating) {
568
- // As far as a validation goes. The call is left unanswered — an answer
569
- // would only send the program on to do more — until the program,
570
- // which is being stopped, lets go of it.
571
- handedOff = true;
572
- validated.abort();
573
- return rejectOnAbort(new Promise(() => { }), stop);
781
+ programOver: () => programOver,
782
+ make: (request, stop, seq) => {
783
+ if (validating)
784
+ return handOff("has a project made or changed", stop);
785
+ if (!options.making) {
786
+ throw new Error("This runner was not given a way to make projects: createProject and updateProject are carried out where a run is started by way of @trama-dev/runtime/runner.");
574
787
  }
788
+ // The run's own, as a run it asks for is: under its budget, with its variables, stopped when it
789
+ // ends or when the program no longer wants it, and not over before this is. (But the program's
790
+ // clock goes on: what it has made is its own work, with no timeout but the program's.)
791
+ const made = options.making(request, {
792
+ signal: AbortSignal.any([runEnded.signal, stop]),
793
+ above: options.meter,
794
+ label,
795
+ env: options.env,
796
+ parent: { run: journal.run, journal: journal.path, seq },
797
+ // (What it starts is a validation: of the program the project is made with.)
798
+ started: (run, path) => { if (run)
799
+ journal.note("child", { seq, run, journal: path, purpose: "validate" }); },
800
+ }).finally(() => { nestedRuns.delete(made); });
801
+ nestedRuns.add(made);
802
+ return made;
803
+ },
804
+ run: (request, stop, seq) => {
805
+ if (validating)
806
+ return handOff("starts another program", stop);
575
807
  // The program is waiting, not working: its clock stops for as long as
576
808
  // the run it asked for lasts, which has a timeout of its own. That run
577
809
  // is stopped when this one ends, or when the program no longer wants it.
578
810
  const release = allowance.hold();
579
- const nested = runProgram({ ...request, signal: AbortSignal.any([runEnded.signal, stop]) }, {
811
+ // What this run was started with, the run it asks for has too — and what it is given besides.
812
+ const env = options.env || request.env ? { ...options.env, ...request.env } : undefined;
813
+ const nested = runProgram({ ...request, env, signal: AbortSignal.any([runEnded.signal, stop]) }, {
580
814
  depth: options.depth + 1,
581
815
  // The two journals point at each other: this one says which run the call started…
582
816
  started: (run, path) => { if (run)
583
817
  journal.note("child", { seq, run, journal: path }); },
584
818
  // …and that run's journal says which call started it.
585
819
  parent: { run: journal.run, journal: journal.path, seq },
586
- }).finally(() => {
820
+ above: options.meter,
821
+ }, options.making).finally(() => {
587
822
  release();
588
823
  nestedRuns.delete(nested);
589
824
  });
@@ -602,7 +837,6 @@ async function runProgramOnce(options) {
602
837
  // Asked to stop while its program had not ended. Everything it has in flight
603
838
  // goes at once — the runs it asked for among them, so that a tree of runs is
604
839
  // stopped together rather than one level after another.
605
- let programOver = false;
606
840
  let stopped = false;
607
841
  const stopProgram = () => {
608
842
  if (programOver)
@@ -628,7 +862,7 @@ async function runProgramOnce(options) {
628
862
  });
629
863
  const program = spawn(process.execPath, ["--import", TSX_LOADER, guardPath(projectDir, "program.ts")], {
630
864
  cwd: projectDir,
631
- env: { ...process.env, TRAMA_PORT: String(port), TRAMA_INIT: initFile },
865
+ env: { ...process.env, ...options.env, TRAMA_PORT: String(port), TRAMA_INIT: initFile },
632
866
  stdio: ["ignore", "pipe", "pipe"],
633
867
  detached: true,
634
868
  });
@@ -650,7 +884,7 @@ async function runProgramOnce(options) {
650
884
  // program goes down, cut off in mid-flow, says nothing about it.
651
885
  const passedAtHandOff = handedOff && !exit.timedOut;
652
886
  if (passedAtHandOff)
653
- console.log(tagged(label, "[trama] validated up to where it starts another program"));
887
+ console.log(tagged(label, `[trama] validated up to where it ${handedOff}`));
654
888
  return {
655
889
  child: passedAtHandOff ? { exitCode: 0, stdout: exit.stdout, stderr: exit.stderr } : toChildResult(exit),
656
890
  // How the program's process ended, for the record.
@@ -712,55 +946,140 @@ async function runProgramOnce(options) {
712
946
  /** The instructions a request for a fix is made under. (Exported so the tests' stand-in LLM can tell one from any other call.) */
713
947
  export const REPAIR_SYSTEM_PROMPT = "You are a TypeScript repair tool.";
714
948
  const repairPrompt = (input) => `Fix this program so it runs.\n\n` +
715
- `Runtime types:\n${RUNTIME_TYPES}\n\n` +
949
+ `You are working in a copy of the project's directory, where the program is program.ts. ` +
950
+ (input.kept
951
+ ? `If what is wrong is in the project and not in the program — a package that is not installed, a file the program needs that is missing or wrong — put it right here: ` +
952
+ `what you change in this directory is kept, with the program you answer with, if that program then runs. If it does not, none of it is.\n`
953
+ : `Nothing you change in this directory is kept: the program you answer with is all that is taken from you.\n`) +
954
+ (input.journal ? `The record of the run that failed — each call the program made, and what came back — is at ${input.journal}, a line of JSON for each.\n` : "") +
955
+ `\nRuntime types:\n${RUNTIME_TYPES}\n\n` +
716
956
  `Broken program:\n${input.programSource}\n\n` +
717
957
  `Error:\n${input.error}\n\n` +
718
- `Output ONLY the fixed program. No explanation.`;
958
+ `Output ONLY the fixed program${input.kept ? ": the whole of it, also where it is the project that needed fixing" : ""}. No explanation.`;
959
+ /**
960
+ * A question to ask of a copy an agent has worked in: whether what is at its
961
+ * path is still the directory that was read (`was`). An agent can move its
962
+ * copy away and leave a link there, or nothing: what is done next is done in
963
+ * the copy, not in what a link leads to, nor in a directory made anew.
964
+ */
965
+ const sameCopyAs = (copy, was) => () => {
966
+ const there = entryAt(copy), itself = was.get(".");
967
+ if (!(there?.kind === "dir" && itself?.kind === "dir" && there.id === itself.id)) {
968
+ throw new Error("the copy that was worked in is no longer where it was made: it was moved away, or something else put in its place");
969
+ }
970
+ };
971
+ function fixIn(copy) {
972
+ const root = realRootOf(copy);
973
+ return {
974
+ root,
975
+ name: pathAsListed(copy, join(root, "program.ts")) ?? "program.ts",
976
+ allowed: statSync(guardPath(copy, "program.ts")).mode,
977
+ parts: programParts(copy),
978
+ };
979
+ }
980
+ /** Make a copy of a project to ask for a fix in, or to try one in: with `program` as its program. */
981
+ function stageProject(projectDir, privateDir, program) {
982
+ const { copy, held, beside } = copyProjectWith(projectDir, privateDir, program);
983
+ const place = guardPath(copy, "program.ts");
984
+ const before = readTree(copy);
985
+ const fix = fixIn(copy);
986
+ return {
987
+ copy, held, beside, before, intact: sameCopyAs(copy, before), fix,
988
+ program: { parts: fix.parts, place, listed: pathAsListed(copy, place), allowed: fix.allowed },
989
+ };
990
+ }
991
+ /** How many of the paths an agent changed are written down, or shown. */
992
+ const MAX_PATHS_NOTED = 200;
993
+ const MAX_PATHS_SHOWN = 10;
994
+ export const shownPaths = (paths) => paths.slice(0, MAX_PATHS_SHOWN).join(", ") + (paths.length > MAX_PATHS_SHOWN ? ", …" : "");
719
995
  /**
720
- * Ask the LLM for a fix. The agent has tools, so it works in a throwaway copy
721
- * of the project that holds the program it is asked to fix — whatever it reads
722
- * is real, whatever it writes is discarded; only the program text it returns
723
- * is used. Bounded by its own timeout.
724
- * Returns the fixed program, or why no usable one came back.
996
+ * Ask the LLM for a fix. The agent has tools, so it works in a copy of the
997
+ * project that holds the program it is asked to fix. What it reads there is
998
+ * as the project has it. Bounded by its own timeout.
999
+ *
1000
+ * What it changes there is part of the fix — the copy is the one the fix is
1001
+ * then tried in, and what was done in it reaches the project with the fix or
1002
+ * not at all (see tryFix) — unless that is not to be (`agentChanges`), or
1003
+ * the run is a validation: of a validation nothing is kept but the program,
1004
+ * so a fix that leaned on what its agent did beside it would be installed
1005
+ * without it. There the fix is the program alone, and the agent is told so.
1006
+ *
1007
+ * The program is the text it returns, whatever it did to program.ts: where
1008
+ * its work is kept, that text is put where program.ts leads as it left it,
1009
+ * allowing what the program allowed.
1010
+ *
1011
+ * Returns the fixed program — with the copy it is to be tried in, where that
1012
+ * is this one; or with why it cannot be tried in this one, where the agent
1013
+ * left it with no place for a program, not to be read, or moved it away: the
1014
+ * fix is then the program alone, as where nothing else is kept — or why no
1015
+ * usable fix came back.
725
1016
  */
726
- async function requestRepair(options, input) {
1017
+ async function requestRepair(options, input, privateDir) {
727
1018
  options.journal.note("fix-request", { error: input.error });
728
- return withTempDir("trama-repair-", async (privateDir) => {
729
- const timedOut = new AbortController();
730
- const limit = createAllowance(options.timeout);
731
- const signal = options.signal ? AbortSignal.any([timedOut.signal, options.signal]) : timedOut.signal;
732
- try {
733
- const { copy } = copyProjectWith(options.projectDir, privateDir, input.programSource);
734
- limit.start(() => timedOut.abort());
735
- const fixed = stripCodeFences(await options.backend.ask(repairPrompt(input), {
736
- cwd: copy, system: REPAIR_SYSTEM_PROMPT, signal,
737
- }));
738
- if (fixed.trim() === "")
739
- throw new Error("The repair returned an empty program.");
1019
+ const timedOut = new AbortController();
1020
+ const limit = createAllowance(options.timeout);
1021
+ const signal = options.signal ? AbortSignal.any([timedOut.signal, options.signal]) : timedOut.signal;
1022
+ try {
1023
+ const kept = options.agentChanges !== "discard" && !options.validating;
1024
+ const staged = stageProject(options.projectDir, privateDir, input.programSource);
1025
+ limit.start(() => timedOut.abort());
1026
+ const fixed = stripCodeFences(await options.backend.ask(repairPrompt({ ...input, journal: options.journal.path, kept }), {
1027
+ cwd: staged.copy, system: REPAIR_SYSTEM_PROMPT, signal,
1028
+ used: (usage) => options.journal.used("fix", usage),
1029
+ }));
1030
+ if (fixed.trim() === "")
1031
+ throw new Error("The repair returned an empty program.");
1032
+ if (!kept) {
740
1033
  if (fixed === input.programSource)
741
1034
  throw new Error("The repair returned the program unchanged.");
742
1035
  options.journal.note("fix", { ok: true, source: fixed });
743
1036
  return { fixed };
744
1037
  }
1038
+ let changed = [], unusable;
1039
+ try {
1040
+ staged.intact();
1041
+ putProgram(staged.copy, options.projectDir, fixed, staged.program.allowed);
1042
+ staged.fix = fixIn(staged.copy);
1043
+ staged.changed = changed = differences(staged.before, readTree(staged.copy, true)).filter((path) => path !== staged.program.listed);
1044
+ }
745
1045
  catch (err) {
746
- const error = messageOf(err);
747
- options.journal.note("fix", { ok: false, error });
748
- return { error };
1046
+ unusable = messageOf(err);
749
1047
  }
750
- finally {
751
- limit.cancel();
1048
+ // A fix is the program, or the project, or both. One that is neither is the failure over again.
1049
+ if (fixed === input.programSource && changed.length === 0) {
1050
+ throw new Error(`The repair returned the program unchanged${unusable === undefined ? ", and changed nothing else in the project" : ""}.`);
752
1051
  }
753
- });
1052
+ options.journal.note("fix", {
1053
+ ok: true,
1054
+ ...(changed.length > 0 ? { changed: changed.slice(0, MAX_PATHS_NOTED) } : {}),
1055
+ ...(changed.length > MAX_PATHS_NOTED ? { changedInAll: changed.length } : {}),
1056
+ alone: unusable,
1057
+ source: fixed,
1058
+ });
1059
+ return unusable === undefined ? { fixed, staged } : { fixed, unusable };
1060
+ }
1061
+ catch (err) {
1062
+ const error = messageOf(err);
1063
+ options.journal.note("fix", { ok: false, error });
1064
+ return { error };
1065
+ }
1066
+ finally {
1067
+ limit.cancel();
1068
+ }
754
1069
  }
755
1070
  /**
756
- * Try a proposed fix.
1071
+ * Try a proposed fix, in a copy of the project that has it for its program.
757
1072
  *
758
- * The project is the program's own, so the fix runs on a private copy of it.
759
- * Only if it works does anything reach the real one — the fix becomes
760
- * program.ts, and what its run did is merged back. A fix that fails, or a
761
- * runner that is stopped while one is tried, leaves the project exactly as
762
- * it was, because it was never touched: its state is only ever written by
763
- * code that is, or becomes, its program.
1073
+ * The project is the program's own, so the fix runs on a private copy of it:
1074
+ * the one the agent worked in when it was asked for the fix, with what the
1075
+ * agent did there — or one made for the trial, where what the agent did is
1076
+ * not kept. Only if it works does anything reach the real one — the
1077
+ * fix becomes program.ts, and what was done in the copy is merged back: by
1078
+ * the agent, and by the run. A fix that fails, or a runner that is stopped
1079
+ * while one is tried, leaves the project exactly as it was, because it was
1080
+ * never touched: its state is only ever written by code that is, or
1081
+ * becomes, its program — and its other files, besides, by an agent whose fix
1082
+ * then ran.
764
1083
  *
765
1084
  * The shared workspace is not copied. It is how the participants of a session
766
1085
  * talk to each other, and a program that is being fixed still has to be heard
@@ -768,101 +1087,96 @@ async function requestRepair(options, input) {
768
1087
  * would wait for replies forever. So what a fix writes there is written,
769
1088
  * whether or not the fix works: like anything a run wrote before it failed.
770
1089
  */
771
- async function tryFix(options, fixed, attempt) {
1090
+ async function tryFix(options, staged, fixed, attempt) {
772
1091
  const { projectDir } = options;
773
- return withTempDir("trama-staged-", async (privateDir) => {
774
- // What the project held when it was copied: what its places are compared with when the run's work is merged in.
775
- const { copy: stagedProject, held } = copyProjectWith(projectDir, privateDir, fixed);
776
- // Taken with the fix in place: what differs from this afterwards is what the run did.
777
- const before = readTree(stagedProject);
778
- // The fix in the copy, as the copy has it: under which name, at which place — which is the place of
779
- // the project's program in the project — and what it allows there.
780
- const fixAt = guardPath(stagedProject, "program.ts");
781
- const copyRoot = realRootOf(stagedProject);
782
- const itsName = pathAsListed(stagedProject, join(copyRoot, "program.ts")) ?? "program.ts";
783
- const itsPlace = pathAsListed(stagedProject, fixAt);
784
- const allowed = statSync(fixAt).mode;
785
- // And all that makes program.ts lead to it, as the copy stands: the name, each link and each directory on
786
- // the way, the file — each by what it is, which is asked of the place, whatever its directory lists or allows.
787
- const programIs = () => wayTo(stagedProject, "program.ts").flatMap((place) => {
788
- const entry = entryAt(place);
789
- return entry && entry.kind !== "other" ? [entry.id] : [];
790
- });
791
- const was = programIs();
792
- // If the copy cannot be run at all, or is left unusable, this fix did not work either.
793
- const trial = await runProgramOnce({ ...options, projectDir: stagedProject, attempt }).catch((err) => ({
794
- outcome: null,
795
- failure: `The repaired program could not be run: ${messageOf(err)}`,
796
- }));
797
- if (trial.outcome === null)
798
- return trial;
799
- // The fix worked, and becomes the project's program — as it ran, first,
800
- // and in one move; only then is what its run did merged in. What the run
801
- // did to its own file is among that: a program may rewrite itself, give
802
- // itself other permissions, make program.ts lead elsewhere, and here as
803
- // in any run what it made of itself is what it is. (So a runner stopped
804
- // between the two leaves the fix beside the state it started from: the
805
- // program that would do the same again, not the one it turns into.)
806
- //
807
- // The project is to have a program afterwards. One that removed itself —
808
- // the system finds nothing at program.ts, however a link left there words
809
- // the way to it — is still the fix that ran: a file of its name is put
810
- // back where the run ended (the name itself, not what the link leads to).
811
- // A run that left something there that cannot be read as a program has
812
- // not left a project that has one, and was no fix.
813
- let is;
814
- try {
815
- if (statSync(join(copyRoot, itsName), { throwIfNoEntry: false })) {
816
- programIn(stagedProject);
817
- }
818
- else {
819
- inDirOfCopy(copyRoot, () => {
820
- rmSync(join(copyRoot, itsName), { force: true });
821
- stageFile(stagedProject, itsName, fixed, allowed).commit();
822
- });
823
- }
824
- is = programIs();
825
- }
826
- catch (err) {
827
- return {
828
- outcome: null,
829
- failure: `The repaired program ran, but left no program.ts that can be read: ${messageOf(err)}`,
830
- };
831
- }
832
- // If it cannot be put in place, that is an error, and it is thrown from
833
- // here with nothing of the run in the project: a state the old program
834
- // did not write, beside the old program, is worse than either. Nor is it
835
- // put into another directory that is at the project's path by now: the
836
- // project is the directory that was copied, which the copy knows by what
837
- // it is.
838
- const projectRoot = realRootOf(projectDir);
839
- const copied = held.get("."), there = entryAt(projectRoot);
840
- if (there && copied?.kind === "dir" && !(there.kind === "dir" && there.id === copied.id)) {
841
- throw new Error(`The program cannot be replaced: what is at ${projectRoot} is not the project the fix was tried on.`);
1092
+ const { copy: stagedProject, held, before } = staged;
1093
+ const itsPlace = staged.program.listed;
1094
+ // The fix in the copy, as the copy has it: under which name, what it allows there, and all that makes program.ts lead to it.
1095
+ const { root: copyRoot, name: itsName, allowed, parts: was } = staged.fix;
1096
+ const programIs = () => programParts(stagedProject);
1097
+ // If the copy cannot be run at all, or is left unusable, this fix did not work either.
1098
+ const trial = await runProgramOnce({ ...options, projectDir: stagedProject, attempt }).catch((err) => ({
1099
+ outcome: null,
1100
+ failure: `The repaired program could not be run: ${messageOf(err)}`,
1101
+ }));
1102
+ if (trial.outcome === null)
1103
+ return trial;
1104
+ // The fix worked, and becomes the project's program — as it ran, first,
1105
+ // and in one move; only then is what its run did merged in. What the run
1106
+ // did to its own file is among that: a program may rewrite itself, give
1107
+ // itself other permissions, make program.ts lead elsewhere, and here as
1108
+ // in any run what it made of itself is what it is. (So a runner stopped
1109
+ // between the two leaves the fix beside the state it started from: the
1110
+ // program that would do the same again, not the one it turns into.)
1111
+ //
1112
+ // The project is to have a program afterwards. One that removed itself —
1113
+ // the system finds nothing at program.ts, however a link left there words
1114
+ // the way to it — is still the fix that ran: a file of its name is put
1115
+ // back where the run ended (the name itself, not what the link leads to).
1116
+ // A run that left something there that cannot be read as a program has
1117
+ // not left a project that has one, and was no fix.
1118
+ let is;
1119
+ try {
1120
+ if (statSync(join(copyRoot, itsName), { throwIfNoEntry: false })) {
1121
+ programIn(stagedProject);
842
1122
  }
843
- const program = stageProgram(projectDir, fixed);
844
- program.commit();
845
- // The project now holds, where its program was, what the copy held there before the run — and the merge is
846
- // told so: that is what the place is taken to have held when the copy was made. (If that is still the
847
- // place program.ts leads to: where somebody has pointed it elsewhere meanwhile, the seed knows nothing new.)
848
- const installed = entryAt(program.destination);
849
- const samePlace = relative(projectRoot, program.destination) === relative(copyRoot, fixAt);
850
- if (itsPlace !== undefined && installed && samePlace)
851
- held.set(itsPlace, installed);
852
- // What the run made of its program is one thing, with what it was: the name, and what the name leads through
853
- // and to. If part of that does not arrive — or a part the run left alone is not, in the project, as it was —
854
- // none of it is carried over: a link without what it leads to, or the file gone from where the project's
855
- // program.ts still leads, would be a project with no program. The project then keeps the fix as it ran.
856
- const unmerged = mergeTree(stagedProject, projectDir, before, held, [[...new Set([...was, ...is])]]);
857
- if (unmerged.length > 0) {
858
- // The run is done and its program installed; what it did that is not in the project is said, not passed over.
859
- options.journal.note("unmerged", { attempt, files: unmerged });
860
- console.warn(tagged(options.label, `[trama] ${unmerged.length} change(s) the repaired run made did not reach the project:`));
861
- for (const { path, why } of unmerged)
862
- console.warn(tagged(options.label, `[trama] ${path} — ${why}`));
1123
+ else {
1124
+ inDirOfCopy(copyRoot, () => {
1125
+ rmSync(join(copyRoot, itsName), { force: true });
1126
+ stageFile(stagedProject, itsName, fixed, allowed).commit();
1127
+ });
863
1128
  }
864
- return trial;
865
- });
1129
+ is = programIs();
1130
+ }
1131
+ catch (err) {
1132
+ return {
1133
+ outcome: null,
1134
+ failure: `The repaired program ran, but left no program.ts that can be read: ${messageOf(err)}`,
1135
+ };
1136
+ }
1137
+ // If it cannot be put in place, that is an error, and it is thrown from
1138
+ // here with nothing of the run in the project: a state the old program
1139
+ // did not write, beside the old program, is worse than either. Nor is it
1140
+ // put into another directory that is at the project's path by now: the
1141
+ // project is the directory that was copied, which the copy knows by what
1142
+ // it is.
1143
+ const projectRoot = realRootOf(projectDir);
1144
+ const copied = held.get("."), there = entryAt(projectRoot);
1145
+ if (there && copied?.kind === "dir" && !(there.kind === "dir" && there.id === copied.id)) {
1146
+ throw new Error(`The program cannot be replaced: what is at ${projectRoot} is not the project the fix was tried on.`);
1147
+ }
1148
+ const program = stageProgram(projectDir, fixed);
1149
+ program.commit();
1150
+ // The project now holds, where its program was, what the copy held there before the run — and the merge is
1151
+ // told so: that is what the place is taken to have held when the copy was made. (If that is still the
1152
+ // place program.ts leads to: where somebody has pointed it elsewhere meanwhile, the seed knows nothing new.)
1153
+ const installed = entryAt(program.destination);
1154
+ const samePlace = relative(projectRoot, program.destination) === relative(copyRoot, staged.program.place);
1155
+ if (itsPlace !== undefined && installed && samePlace)
1156
+ held.set(itsPlace, installed);
1157
+ // What the agent and the run made of the program is one thing, with what it was: the name, and what the
1158
+ // name leads through and to. If part of that does not arrive — or a part that was left alone is not, in the
1159
+ // project, as it was — none of it is carried over: a link without what it leads to, or the file gone from where
1160
+ // the project's program.ts still leads, would be a project with no program. The project then keeps the fix as it ran.
1161
+ // (What it was before the agent worked is named too: that is the file the reading the merge compares with has
1162
+ // at the program's place, and by it that place is known for a part where the run removed what was there.)
1163
+ const unmerged = [
1164
+ ...mergeTree(stagedProject, projectDir, before, held, [[...new Set([...staged.program.parts, ...was, ...is])]]),
1165
+ // (Of a program that is only being validated nothing is told here: the copy it is validated in goes, with all of this.)
1166
+ ...(options.validating ? [] : strandedBeside(stagedProject, staged.beside)),
1167
+ ];
1168
+ // What the agent changed beside the program is said: it is in the project now, but for what is told of below.
1169
+ if (staged.changed?.length) {
1170
+ console.log(tagged(options.label, `[trama] the agent asked for the fix changed ${staged.changed.length} path(s) beside the program: ${shownPaths(staged.changed)}`));
1171
+ }
1172
+ if (unmerged.length > 0) {
1173
+ // The run is done and its program installed; what was done that is not in the project is said, not passed over.
1174
+ options.journal.note("unmerged", { attempt, files: unmerged });
1175
+ console.warn(tagged(options.label, `[trama] ${unmerged.length} change(s) the repair made did not reach the project:`));
1176
+ for (const { path, why } of unmerged)
1177
+ console.warn(tagged(options.label, `[trama] ${path} — ${why}`));
1178
+ }
1179
+ return trial;
866
1180
  }
867
1181
  /**
868
1182
  * Run a program to an outcome. If it crashes, ask the LLM to repair it and try
@@ -901,40 +1215,75 @@ async function executeProgram(options) {
901
1215
  // The program as it was is attempt 0; each fix is the next.
902
1216
  for (let attempt = 1; attempt <= maxRepairAttempts; attempt++) {
903
1217
  stillTheProject();
904
- const fix = await requestRepair(options, { programSource: currentSource, error: lastError });
905
- if (stopped())
1218
+ // A fix is asked of a model: where no more may be, none is asked for, and nothing is got ready for one.
1219
+ const spent = options.backend.spent?.();
1220
+ if (spent !== undefined) {
1221
+ return failed(`${attempt === 1 ? "Program failed, and no repair was tried" : `Failed after ${attempt - 1} repair attempt(s), and no further repair was tried`}. ${spent}\n${lastError}`);
1222
+ }
1223
+ const source = currentSource, error = lastError;
1224
+ // One copy of the project for the attempt: the fix is asked for in it, and tried in it.
1225
+ const tried = await withTempDir("trama-repair-", async (privateDir) => {
1226
+ const fix = await requestRepair(options, { programSource: source, error }, privateDir);
1227
+ if (stopped())
1228
+ return null;
1229
+ stillTheProject();
1230
+ if ("error" in fix)
1231
+ return fix;
1232
+ const { fixed, staged, unusable } = fix;
1233
+ if (unusable !== undefined) {
1234
+ console.warn(tagged(options.label, `[trama] the fix is tried by itself, and nothing else its agent did is kept: the copy the agent worked in cannot be used (${unusable})`));
1235
+ }
1236
+ // Where what the agent changed is not kept, the fix is tried in a copy the agent was never in.
1237
+ const run = staged
1238
+ ? await tryFix(options, staged, fixed, attempt)
1239
+ : await withTempDir("trama-staged-", (apart) => tryFix(options, stageProject(projectDir, apart, fixed), fixed, attempt));
1240
+ return { fixed, run };
1241
+ });
1242
+ if (tried === null)
906
1243
  return wasStopped();
907
- stillTheProject();
908
1244
  // Without a fix there is nothing more to try: asking again would be asking the same thing.
909
- if ("error" in fix) {
910
- return failed(`Failed after ${attempt} repair attempt(s): ${lastError}\nNo fix came back: ${fix.error}`);
1245
+ if ("error" in tried) {
1246
+ return failed(`Failed after ${attempt} repair attempt(s): ${lastError}\nNo fix came back: ${tried.error}`);
911
1247
  }
912
- currentSource = fix.fixed;
913
- const run = await tryFix(options, fix.fixed, attempt);
914
- if (run.outcome)
915
- return { result: run.outcome, repair: { attempt, error: lastError } };
1248
+ currentSource = tried.fixed;
1249
+ if (tried.run.outcome)
1250
+ return { result: tried.run.outcome, repair: { attempt, error: lastError } };
916
1251
  if (stopped())
917
1252
  return wasStopped();
918
- lastError = run.failure;
1253
+ lastError = tried.run.failure;
919
1254
  }
920
1255
  return failed(`Failed after ${maxRepairAttempts} repair attempts: ${lastError}`);
921
1256
  }
922
1257
  /**
923
1258
  * Carry out a run under its journal. However it goes, the journal's last
924
- * record says so: the run's result, or why it could not be carried out.
1259
+ * record says so: the run's result, or why it could not be carried out —
1260
+ * after the agent calls that were cut off on the way have said what they
1261
+ * used. (A run that is not recorded, and whose backend holds what calls use
1262
+ * to nothing, has nothing to wait for.) Where the budget the backend counts
1263
+ * in is spent by then — or a call was refused or stopped for it on the way —
1264
+ * the record before the last says that.
925
1265
  */
926
- async function journalled(journal, run) {
1266
+ async function journalled(journal, backend, run) {
1267
+ let end = {};
927
1268
  try {
928
- const execution = await run();
929
- journal.note("end", { result: execution.result });
1269
+ const execution = await run(backend);
1270
+ end = { result: execution.result };
930
1271
  return execution;
931
1272
  }
932
1273
  catch (err) {
933
- journal.note("end", { error: messageOf(err) });
1274
+ end = { error: messageOf(err) };
934
1275
  throw err;
935
1276
  }
936
1277
  finally {
1278
+ if (journal.run || backend.counts?.())
1279
+ await backend.letGo();
1280
+ const spent = backend.spent?.() ?? backend.refused?.();
1281
+ if (spent !== undefined)
1282
+ journal.note("budget", { spent });
1283
+ journal.note("end", end);
937
1284
  journal.close();
1285
+ // Nothing a run started outlives it: nor what served its agent calls.
1286
+ await backend.close?.();
938
1287
  }
939
1288
  }
940
1289
  // --- Validating a candidate program (used by create and update) ---
@@ -946,23 +1295,65 @@ const VALIDATION_READY_GRACE_MS = 2_000;
946
1295
  * the candidate itself, or a repaired version of it, with the failure that was
947
1296
  * repaired. Throws if it cannot be made to run.
948
1297
  *
1298
+ * `as` names a directory that is the project as it is to be once the
1299
+ * program is in it — the copy the agent that wrote the program worked in,
1300
+ * with what it made there (see Prepared). The copy the program is run in is
1301
+ * then a copy of that, which is no more touched than the project is, and it
1302
+ * stands among what the project stands among.
1303
+ *
1304
+ * A repair made here is of the program alone (see requestRepair): the copy a
1305
+ * candidate runs in goes whole, with whatever was done in it.
1306
+ *
1307
+ * Where the agent left its copy so that no copy can be made of it — a file
1308
+ * nobody may read, say — the candidate is validated in the project as it is,
1309
+ * as it would be were nothing of the agent's kept: and `alone` says why,
1310
+ * for then nothing of the agent's is to be kept. (A caller that knows of such
1311
+ * a reason beforehand gives it as `alone`, with no `as`.) That is said when
1312
+ * it is found, whatever then comes of the candidate.
1313
+ *
949
1314
  * Only the project's own files are shielded. What the program does beyond
950
1315
  * them — network calls, shell commands, agent calls — is real. A run it asks
951
1316
  * its runner for is not started: the validation ends where it asks for the
952
1317
  * first.
953
1318
  */
954
1319
  export async function validateProgram(projectDir, backend, candidate, options) {
955
- const { journalRuns = 0, signal, ...limits } = options;
956
- // Recorded with the project, though run in a copy of it.
957
- const journal = openJournal(projectDir, journalRuns, { purpose: "validate", ...limits });
958
- const { result, repair, left } = await journalled(journal, () => withTempDir("trama-validate-", async (privateDir) => {
959
- const { copy: trialDir } = copyProjectWith(projectDir, privateDir, candidate);
1320
+ const { journalRuns = 0, signal, as = projectDir, timeout, maxRepairAttempts, maxIterations, label, env, askedFor } = options;
1321
+ // (What is written down, and handed on, is what a validation is known to take: nothing else that came with it.)
1322
+ const limits = { timeout, maxRepairAttempts, maxIterations };
1323
+ // Recorded with the project, though run in a copy of it. `budget` is for the record: the backend is what holds to it.
1324
+ const journal = openJournal(projectDir, journalRuns, {
1325
+ purpose: "validate", label, parent: askedFor?.parent, ...limits, budget: options.budget, env: env && Object.keys(env),
1326
+ });
1327
+ askedFor?.started(journal.run, journal.path);
1328
+ // What writing the candidate used is on record with its validation: it happened in no run, and has no journal of its own.
1329
+ for (const usage of options.wrote ?? [])
1330
+ journal.used("generate", usage);
1331
+ let alone;
1332
+ const byItself = (why) => {
1333
+ alone = why;
1334
+ console.warn(tagged(label, `[trama] the program is validated by itself, and nothing else its agent did is kept: the copy the agent worked in cannot be used (${why})`));
1335
+ };
1336
+ if (options.alone !== undefined)
1337
+ byItself(options.alone);
1338
+ const validatedIn = (prepared) => withTempDir("trama-validate-", async (privateDir) => {
1339
+ let trialDir;
1340
+ try {
1341
+ trialDir = copyProjectWith(prepared, privateDir, candidate, projectDir).copy;
1342
+ }
1343
+ catch (err) {
1344
+ if (prepared === projectDir)
1345
+ throw err;
1346
+ byItself(messageOf(err));
1347
+ return null;
1348
+ }
960
1349
  const execution = await executeProgram({
961
1350
  ...limits,
962
1351
  projectDir: trialDir,
963
1352
  backend,
964
1353
  depth: 0,
965
1354
  validating: { readyGraceMs: VALIDATION_READY_GRACE_MS },
1355
+ label,
1356
+ env,
966
1357
  signal,
967
1358
  journal,
968
1359
  });
@@ -978,10 +1369,70 @@ export async function validateProgram(projectDir, backend, candidate, options) {
978
1369
  const reason = `The program ran, but left no program.ts that can be read: ${messageOf(err)}`;
979
1370
  return { ...execution, result: { status: "failed", reason }, left: candidate };
980
1371
  }
981
- }));
1372
+ });
1373
+ const { result, repair, left } = await journalled(journal, backend, async () => (await validatedIn(as)) ?? (await validatedIn(projectDir)));
982
1374
  if (result.status === "failed")
983
1375
  throw new Error(`Program failed: ${result.reason}`);
984
- return { source: left, repairedError: repair?.error };
1376
+ return { source: left, repairedError: repair?.error, ...(alone === undefined ? {} : { alone }) };
1377
+ }
1378
+ export function prepareProject(projectDir, privateDir) {
1379
+ const { copy, held, beside } = copyProjectWith(projectDir, privateDir);
1380
+ const before = readTree(copy);
1381
+ const intact = sameCopyAs(copy, before);
1382
+ const root = realRootOf(copy);
1383
+ const name = join(root, "program.ts");
1384
+ /** The paths of the copy that are its program's, as it stands: the name, and what it leads through and to — but for directories, which hold other things too. */
1385
+ const programAt = () => [name, ...wayTo(copy, "program.ts")]
1386
+ .flatMap((place) => (entryAt(place)?.kind === "dir" ? [] : pathAsListed(copy, place) ?? []));
1387
+ /**
1388
+ * The way from the name to the program, as it stands: each place on it, and
1389
+ * what kind of thing is there — but that a file, or nothing yet, is all one:
1390
+ * either is a place a program can be put. (What a link says is not asked:
1391
+ * where it leads is the places that follow.)
1392
+ */
1393
+ const way = () => [name, ...wayTo(copy, "program.ts")].map((place) => {
1394
+ const there = entryAt(place);
1395
+ return `${relative(root, place)} ${there === undefined || there.kind === "file" ? "" : there.kind}`;
1396
+ }).join("\n");
1397
+ // What the name was, the way from it, and the program's places: before the agent worked, and as the agent left them.
1398
+ const nameWas = entryAt(name);
1399
+ const wayWas = way();
1400
+ const places = programAt();
1401
+ return {
1402
+ copy,
1403
+ ready() {
1404
+ intact();
1405
+ places.push(...programAt());
1406
+ const nameIs = entryAt(name);
1407
+ const asItWas = nameIs?.kind === "link" ? nameWas?.kind === "link" && nameWas.text === nameIs.text : nameWas?.kind !== "link";
1408
+ if (!asItWas) {
1409
+ inDirOfCopy(root, () => {
1410
+ rmSync(name, { force: true });
1411
+ if (nameWas?.kind === "link")
1412
+ symlinkSync(nameWas.text, name);
1413
+ });
1414
+ }
1415
+ if (way() !== wayWas)
1416
+ throw new Error("program.ts does not lead, in the copy that was worked in, where it led before: a program validated there would not be the program where it is installed");
1417
+ },
1418
+ keep() {
1419
+ intact();
1420
+ // (With what is closed opened for the reading: a copy was made of this one to validate in, but not of all
1421
+ // of it — what is left out of a copy, a directory of journals, was not looked into.)
1422
+ const after = readTree(copy, true);
1423
+ // At the program's places — where they were, where the agent left them, and where they are now that the
1424
+ // name is as it was (which a directory may list in other letters than it did) — the copy is taken to have
1425
+ // been as it is: nothing was done there that is to arrive.
1426
+ for (const path of [...places, ...programAt()]) {
1427
+ const there = after.get(path);
1428
+ if (there)
1429
+ before.set(path, there);
1430
+ else
1431
+ before.delete(path);
1432
+ }
1433
+ return { changed: differences(before, after), unmerged: [...mergeTree(copy, projectDir, before, held), ...strandedBeside(copy, beside)] };
1434
+ },
1435
+ };
985
1436
  }
986
1437
  /** A project's program text — null if it has none. Throws if what is in its place is no file. */
987
1438
  function programIn(projectDir) {
@@ -1092,7 +1543,7 @@ let runsInFlight = 0;
1092
1543
  * call). One runner carries the whole tree of runs, so it is also where the
1093
1544
  * tree is kept from growing without bound.
1094
1545
  */
1095
- export async function runProgram(options, askedFor) {
1546
+ export async function runProgram(options, askedFor, making) {
1096
1547
  const depth = askedFor?.depth ?? 0;
1097
1548
  if (depth > MAX_RUN_DEPTH) {
1098
1549
  throw new Error(`Not running ${options.projectDir}: programs are running programs more than ${MAX_RUN_DEPTH} deep. ` +
@@ -1103,13 +1554,13 @@ export async function runProgram(options, askedFor) {
1103
1554
  }
1104
1555
  runsInFlight += 1;
1105
1556
  try {
1106
- return await runProject(options, depth, askedFor);
1557
+ return await runProject(options, depth, askedFor, making);
1107
1558
  }
1108
1559
  finally {
1109
1560
  runsInFlight -= 1;
1110
1561
  }
1111
1562
  }
1112
- async function runProject(options, depth, askedFor) {
1563
+ async function runProject(options, depth, askedFor, making) {
1113
1564
  const { projectDir } = options;
1114
1565
  if (!existsSync(join(projectDir, "meta.json"))) {
1115
1566
  throw new Error(`Project not found at ${projectDir}. ` +
@@ -1124,6 +1575,10 @@ async function runProject(options, depth, askedFor) {
1124
1575
  if (!Number.isInteger(maxRepairAttempts) || maxRepairAttempts < 0) {
1125
1576
  throw new Error(`Invalid maxRepairAttempts: ${maxRepairAttempts}. Must be a non-negative integer.`);
1126
1577
  }
1578
+ const env = options.env == null ? undefined : checkedEnv(options.env);
1579
+ // Its own budget — the config's, for a run nobody's program asked for and that was given none — under the budgets above it.
1580
+ const budget = options.budget != null ? checkedBudget(options.budget) : askedFor ? undefined : config.budget;
1581
+ const meter = createMeter(budget, askedFor?.above);
1127
1582
  const journal = openJournal(projectDir, config.journalRuns, {
1128
1583
  purpose: "run",
1129
1584
  label: options.label,
@@ -1132,13 +1587,19 @@ async function runProject(options, depth, askedFor) {
1132
1587
  workspace: options.workspaceDir,
1133
1588
  timeout,
1134
1589
  maxRepairAttempts,
1590
+ budget,
1591
+ // (The names: what the variables hold is not for a journal.)
1592
+ env: env && Object.keys(env),
1135
1593
  args: options.args, // last: it is the one field of unknown size
1136
1594
  });
1137
1595
  askedFor?.started(journal.run, journal.path);
1138
1596
  const stillTheProject = sameProjectAs(projectDir);
1139
- const { result, repair } = await journalled(journal, () => executeProgram({
1597
+ const outOfBudget = (why) => console.warn(tagged(options.label, `[trama] ${why}`));
1598
+ const { result, repair } = await journalled(journal, createBackend(config, meter, saysOnce(meter, outOfBudget), env), (backend) => executeProgram({
1140
1599
  projectDir,
1141
- backend: createBackend(config),
1600
+ backend,
1601
+ meter,
1602
+ making,
1142
1603
  maxRepairAttempts,
1143
1604
  timeout,
1144
1605
  maxIterations: config.defaultMaxIterations,
@@ -1146,6 +1607,8 @@ async function runProject(options, depth, askedFor) {
1146
1607
  workspaceDir: options.workspaceDir,
1147
1608
  depth,
1148
1609
  label: options.label,
1610
+ env,
1611
+ agentChanges: config.agentChanges,
1149
1612
  signal: options.signal,
1150
1613
  journal,
1151
1614
  }));