@trama-dev/runtime 0.3.1 → 0.5.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.
Files changed (47) hide show
  1. package/README.md +4 -3
  2. package/dist/abort.d.ts +12 -0
  3. package/dist/abort.js +31 -0
  4. package/dist/agent-backend.d.ts +0 -6
  5. package/dist/agent-backend.js +1 -21
  6. package/dist/agent.d.ts +16 -1
  7. package/dist/agent.js +108 -35
  8. package/dist/bridge-client.js +44 -14
  9. package/dist/child-process.d.ts +1 -20
  10. package/dist/child-process.js +11 -86
  11. package/dist/client.d.ts +2 -1
  12. package/dist/client.js +5 -15
  13. package/dist/context.d.ts +36 -7
  14. package/dist/context.js +83 -92
  15. package/dist/errors.d.ts +2 -0
  16. package/dist/errors.js +2 -0
  17. package/dist/index.d.ts +12 -1
  18. package/dist/index.js +93 -53
  19. package/dist/ipc-server.d.ts +12 -6
  20. package/dist/ipc-server.js +124 -136
  21. package/dist/journal-view.d.ts +9 -0
  22. package/dist/journal-view.js +139 -0
  23. package/dist/journal.d.ts +70 -0
  24. package/dist/journal.js +454 -0
  25. package/dist/meta.d.ts +18 -0
  26. package/dist/meta.js +29 -0
  27. package/dist/path-guard.d.ts +128 -19
  28. package/dist/path-guard.js +384 -68
  29. package/dist/pi-adapter.d.ts +7 -6
  30. package/dist/pi-adapter.js +15 -26
  31. package/dist/replace-file.d.ts +31 -0
  32. package/dist/replace-file.js +75 -0
  33. package/dist/runner-types.d.ts +2 -0
  34. package/dist/runner.d.ts +37 -37
  35. package/dist/runner.js +565 -239
  36. package/dist/serializable.d.ts +10 -4
  37. package/dist/serializable.js +56 -31
  38. package/dist/{watchdog.d.ts → stopping.d.ts} +15 -0
  39. package/dist/stopping.js +268 -0
  40. package/dist/tools.js +44 -13
  41. package/dist/tree.d.ts +234 -0
  42. package/dist/tree.js +1409 -0
  43. package/dist/types.d.ts +6 -3
  44. package/dist/workspace.d.ts +7 -0
  45. package/dist/workspace.js +93 -104
  46. package/package.json +2 -2
  47. package/dist/watchdog.js +0 -167
package/dist/context.d.ts CHANGED
@@ -1,12 +1,41 @@
1
1
  import type { Ctx } from "./types.js";
2
+ import type { ProgramResult } from "./runner-types.js";
3
+ /** Where a project's structured run log lives, relative to the project root. */
4
+ export declare const LATEST_LOG_PATH: string;
5
+ /** Append one structured JSONL entry to a run log file. `data` is what the program's side made of what it was given (see toLogData). */
6
+ export declare function appendLogEntry(logsPath: string, message: string, data?: unknown): void;
2
7
  /**
3
- * The runner-side ctx: owns state.json and the run log for one run of a
4
- * program. The program's own `ctx` (client.ts) forwards to this over IPC.
8
+ * The runner's side of a program's `ctx`: what the program is told when it
9
+ * starts, and where its state file and run log are written while it runs
10
+ * (once it is over, the runner settles both: see runProgramOnce). The
11
+ * program's own `ctx` (client.ts) forwards to this over IPC.
5
12
  *
6
- * This is the one place the ctx lifecycle rules are enforced (ready once,
7
- * done once, done and yield mutually exclusive) — the client only forwards.
8
- *
9
- * Bookkeeping lives in ctx.state under reserved `__trama_*` keys:
13
+ * The state is the program's. It is handed over with each call that persists
14
+ * it and is not kept here: there is one copy of it in the program, and one on
15
+ * disk.
16
+ */
17
+ export interface RunContext {
18
+ readonly input: Ctx["input"];
19
+ readonly maxIterations: number;
20
+ /** Whether this run takes up from a yield, and the reason that yield gave. */
21
+ readonly resumed: boolean;
22
+ readonly yieldReason: string | null;
23
+ /** How many times the state has been persisted — in this run and the ones before it. */
24
+ readonly iteration: number;
25
+ /** How the program ended the run: null until it has called done() or yield(). */
26
+ readonly ended: ProgramResult | null;
27
+ log(message: string, data?: unknown): void;
28
+ /** The first call is logged and passed on to `onReady`; any other does nothing. */
29
+ ready(data?: Record<string, unknown>): void;
30
+ /** Persist the program's state as it is now. Returns the iteration that makes it. */
31
+ checkpoint(state: Record<string, unknown>): number;
32
+ /** Persist the state and end the run as done. Returns the iteration it ended on. */
33
+ done(state: Record<string, unknown>, result?: unknown): number;
34
+ /** Persist the state, with the mark the next run resumes from, and end the run as yielded. */
35
+ yield(state: Record<string, unknown>, reason: string): void;
36
+ }
37
+ /**
38
+ * Bookkeeping lives in the state file under reserved `__trama_*` keys:
10
39
  * `__trama_iteration` (progress counter) and `__trama_yield` (set while the
11
40
  * program is suspended, cleared when it next advances).
12
41
  */
@@ -16,4 +45,4 @@ export declare function createContext(projectDir: string, initialState: Record<s
16
45
  onReady?: (data?: Record<string, unknown>) => void;
17
46
  /** Where the run's log lines are shown as they are written. Defaults to the console. */
18
47
  print?: (line: string) => void;
19
- }): Ctx;
48
+ }): RunContext;
package/dist/context.js CHANGED
@@ -1,118 +1,109 @@
1
- import { readFileSync, writeFileSync, appendFileSync } from "fs";
1
+ import { writeFileSync, appendFileSync } from "fs";
2
2
  import { join } from "path";
3
- import { assertSerializable } from "./serializable.js";
3
+ import { assertSerializable, isJsonObject } from "./serializable.js";
4
4
  import { guardPath } from "./path-guard.js";
5
+ import { readProjectMeta } from "./meta.js";
6
+ /** Where a project's structured run log lives, relative to the project root. */
7
+ export const LATEST_LOG_PATH = join("logs", "latest.jsonl");
8
+ /** Append one structured JSONL entry to a run log file. `data` is what the program's side made of what it was given (see toLogData). */
9
+ export function appendLogEntry(logsPath, message, data) {
10
+ const entry = { ts: Date.now(), message, data: data ?? null };
11
+ appendFileSync(logsPath, JSON.stringify(entry) + "\n");
12
+ }
5
13
  /**
6
- * The runner-side ctx: owns state.json and the run log for one run of a
7
- * program. The program's own `ctx` (client.ts) forwards to this over IPC.
8
- *
9
- * This is the one place the ctx lifecycle rules are enforced (ready once,
10
- * done once, done and yield mutually exclusive) — the client only forwards.
11
- *
12
- * Bookkeeping lives in ctx.state under reserved `__trama_*` keys:
14
+ * Bookkeeping lives in the state file under reserved `__trama_*` keys:
13
15
  * `__trama_iteration` (progress counter) and `__trama_yield` (set while the
14
16
  * program is suspended, cleared when it next advances).
15
17
  */
16
18
  export function createContext(projectDir, initialState, options) {
17
- const logsPath = guardPath(projectDir, join("logs", "latest.jsonl"));
18
- const statePath = guardPath(projectDir, "state.json");
19
- const meta = JSON.parse(readFileSync(guardPath(projectDir, "meta.json"), "utf-8"));
20
- let donePromise = null;
21
- let readyCalled = false;
22
- let terminalSignal = null;
23
- const input = options?.argsOverride
19
+ // Where the state and the log go is asked each time one is written, not once: the program
20
+ // can change what is there while it runs. Asked here too, so that a project that will not
21
+ // do is refused before its program is started.
22
+ const logsPath = () => guardPath(projectDir, LATEST_LOG_PATH);
23
+ const statePath = () => guardPath(projectDir, "state.json");
24
+ logsPath();
25
+ statePath();
26
+ const meta = readProjectMeta(projectDir);
27
+ // The input is the project's own: it is handed on as the file has it.
28
+ const input = (options?.argsOverride
24
29
  ? { ...meta.input, args: { ...(meta.input.args ?? {}), ...options.argsOverride } }
25
- : meta.input;
30
+ : meta.input);
26
31
  // A yield marker left by the previous run means this run is its resumption.
27
- const yieldMarker = initialState.__trama_yield;
32
+ const rawYield = initialState.__trama_yield;
33
+ const yieldMarker = isJsonObject(rawYield) && typeof rawYield.reason === "string" ? { reason: rawYield.reason } : null;
28
34
  const savedIteration = initialState.__trama_iteration;
29
- /** Write ctx.state to disk and advance the iteration counter. */
30
- const persist = (ctx) => {
31
- const nextIteration = ctx.iteration + 1;
32
- ctx.state.__trama_iteration = nextIteration;
33
- writeFileSync(statePath, JSON.stringify(ctx.state, null, 2));
34
- ctx.iteration = nextIteration;
35
+ let iteration = typeof savedIteration === "number" && Number.isInteger(savedIteration) && savedIteration >= 0
36
+ ? savedIteration : 0;
37
+ let readyCalled = false;
38
+ let ended = null;
39
+ const writeLog = (message, data) => {
40
+ appendLogEntry(logsPath(), message, data);
41
+ (options?.print ?? console.log)(`[trama] ${message}`);
42
+ };
43
+ /**
44
+ * The one way a state reaches the state file, and the one place the rules of
45
+ * a run's ending are kept. A run ends once, by done() or by yield(). After
46
+ * that its state is settled: the same ending said again does nothing, and
47
+ * any other call that would write the state is refused — it would take back
48
+ * what the run ended on, the mark the next run resumes from included.
49
+ *
50
+ * `ending` is how the call ends the run, if it does. Returns false for a call
51
+ * that had nothing left to do.
52
+ */
53
+ const persist = (call, state, ending) => {
54
+ if (ended) {
55
+ if (ending?.status === ended.status)
56
+ return false;
57
+ const endedBy = ended.status === "done" ? "done" : "yield";
58
+ throw new Error(`Cannot call ctx.${call}() after ctx.${endedBy}() — the run has ended, and its state is settled.`);
59
+ }
60
+ assertSerializable(state, "ctx.state");
61
+ const record = { ...state, __trama_iteration: iteration + 1 };
62
+ if (ending?.status === "yielded")
63
+ record.__trama_yield = { reason: ending.reason };
64
+ else
65
+ delete record.__trama_yield; // the program has moved on from its last yield
66
+ writeFileSync(statePath(), JSON.stringify(record, null, 2));
67
+ // Settled only once persisted: a call that failed leaves every call open.
68
+ iteration += 1;
69
+ ended = ending ?? null;
70
+ return true;
71
+ };
72
+ /** Persistence is the critical part: a log line that cannot be written must not turn a completed ending into an error. */
73
+ const logEnding = (message, data) => {
74
+ try {
75
+ writeLog(message, data);
76
+ }
77
+ catch { /* best-effort */ }
35
78
  };
36
79
  return {
37
80
  input,
38
- state: { ...initialState },
39
- iteration: typeof savedIteration === "number" && Number.isInteger(savedIteration) && savedIteration >= 0
40
- ? savedIteration : 0,
41
81
  maxIterations: options?.maxIterations ?? 100,
42
82
  resumed: yieldMarker != null,
43
83
  yieldReason: yieldMarker?.reason ?? null,
44
- async log(message, data) {
45
- let safeData = data ?? null;
46
- try {
47
- JSON.stringify(safeData);
48
- }
49
- catch {
50
- safeData = { __trama_unserializable: String(data) };
51
- }
52
- const entry = { ts: Date.now(), message, data: safeData };
53
- appendFileSync(logsPath, JSON.stringify(entry) + "\n");
54
- (options?.print ?? console.log)(`[trama] ${message}`);
55
- },
56
- async ready(data) {
84
+ get iteration() { return iteration; },
85
+ get ended() { return ended; },
86
+ log: writeLog,
87
+ ready(data) {
57
88
  if (readyCalled)
58
89
  return;
59
- await this.log("ready", data);
90
+ writeLog("ready", data);
60
91
  options?.onReady?.(data);
61
92
  readyCalled = true;
62
93
  },
63
- async checkpoint() {
64
- assertSerializable(this.state, "ctx.state");
65
- delete this.state.__trama_yield; // the program has moved on from its last yield
66
- persist(this);
94
+ checkpoint(state) {
95
+ persist("checkpoint", state);
96
+ return iteration;
67
97
  },
68
- async done(result) {
69
- if (terminalSignal === "yielded") {
70
- throw new Error("Cannot call ctx.done() after ctx.yield() — yield already signaled.");
71
- }
72
- // A completed done() is a no-op; one still in flight is shared.
73
- if (donePromise)
74
- return donePromise;
75
- // Claimed while in flight so a yield() cannot slip in alongside it.
76
- terminalSignal = "done";
77
- const run = async () => {
78
- await this.checkpoint();
79
- // Persistence is the critical part; a log failure must not turn a
80
- // completed done() into an error.
81
- try {
82
- await this.log("done", result);
83
- }
84
- catch { /* best-effort */ }
85
- };
86
- donePromise = run();
87
- try {
88
- await donePromise;
89
- }
90
- catch (err) {
91
- // Nothing was persisted, so nothing is settled: done() or yield() may be called again.
92
- donePromise = null;
93
- terminalSignal = null;
94
- throw err;
95
- }
98
+ done(state, result) {
99
+ if (persist("done", state, { status: "done", result: result ?? undefined }))
100
+ logEnding("done", result);
101
+ return iteration;
96
102
  },
97
- async yield(reason) {
98
- if (terminalSignal === "done") {
99
- throw new Error("Cannot call ctx.yield() after ctx.done() — done already signaled.");
100
- }
101
- // The client exits the process after its first successful yield; here a
102
- // repeated call is simply a no-op.
103
- if (terminalSignal !== "yielded") {
104
- assertSerializable(this.state, "ctx.state");
105
- this.state.__trama_yield = { reason };
106
- persist(this);
107
- // Settled only once persisted — a failed yield() leaves done() and yield() both open.
108
- terminalSignal = "yielded";
109
- try {
110
- await this.log("yield", { reason });
111
- }
112
- catch { /* best-effort */ }
113
- }
114
- // Exiting is the client's job: this returns so the IPC handler can answer first.
115
- return undefined;
103
+ // Exiting is the program's job: this returns so that the call can be answered first.
104
+ yield(state, reason) {
105
+ if (persist("yield", state, { status: "yielded", reason }))
106
+ logEnding("yield", { reason });
116
107
  },
117
108
  };
118
109
  }
@@ -0,0 +1,2 @@
1
+ /** What went wrong, in words: an error's message, and anything else that was thrown as it reads. */
2
+ export declare const messageOf: (err: unknown) => string;
package/dist/errors.js ADDED
@@ -0,0 +1,2 @@
1
+ /** What went wrong, in words: an error's message, and anything else that was thrown as it reads. */
2
+ export const messageOf = (err) => (err instanceof Error ? err.message : String(err));
package/dist/index.d.ts CHANGED
@@ -11,7 +11,18 @@ export declare function resolveProject(name: string): string;
11
11
  export declare function createProject(name: string, prompt: string, options?: {
12
12
  model?: string;
13
13
  args?: Record<string, unknown>;
14
+ signal?: AbortSignal;
15
+ }): Promise<void>;
16
+ export declare function updateProject(name: string, prompt: string, options?: {
17
+ signal?: AbortSignal;
14
18
  }): Promise<void>;
15
- export declare function updateProject(name: string, prompt: string): Promise<void>;
16
19
  export declare function listProjects(): Promise<void>;
17
20
  export declare function showLogs(name: string): Promise<void>;
21
+ /**
22
+ * Show what a run of a project did, from its journal: the latest run, or the
23
+ * one named. With `list`, show which runs have a journal instead.
24
+ */
25
+ export declare function showJournal(name: string, options?: {
26
+ run?: string;
27
+ list?: boolean;
28
+ }): Promise<void>;
package/dist/index.js CHANGED
@@ -5,10 +5,15 @@ import { join, resolve } from "path";
5
5
  import { homedir } from "os";
6
6
  import { piVersion } from "./pi-adapter.js";
7
7
  import { stripCodeFences } from "./agent.js";
8
- import { loadConfig, loadProjectConfig, loadState, createBackend, validateProgram, installValidatedProgram, withTempDir, ensureProjectScaffold, RUNTIME_TYPES, runProgram as runHere, } from "./runner.js";
9
- import { createWorkspace as workspaceHere } from "./workspace.js";
8
+ import { onAbort, throwIfAborted } from "./abort.js";
9
+ import { LATEST_LOG_PATH } from "./context.js";
10
+ import { readProjectMeta } from "./meta.js";
11
+ import { loadConfig, loadProjectConfig, loadState, createBackend, validateProgram, installValidatedProgram, withTempDir, ensureProjectScaffold, RUNTIME_TYPES, runProgram as runHere, whyNotReplaceable, } from "./runner.js";
12
+ import { createWorkspace as workspaceHere, ensureWorkspaceDir } from "./workspace.js";
10
13
  import { parentBridge, remoteWorkspace } from "./bridge-client.js";
11
- import { guardPath } from "./path-guard.js";
14
+ import { guardPath, identityOf, sameProjectAs } from "./path-guard.js";
15
+ import { printJournals } from "./journal-view.js";
16
+ import { messageOf } from "./errors.js";
12
17
  // --- Running a project, and reaching a workspace ---
13
18
  //
14
19
  // A program never runs another program: it asks its runner to. So these two do
@@ -26,11 +31,9 @@ export async function runProgram(options) {
26
31
  // same as outside a program.
27
32
  const { signal, ...request } = options;
28
33
  const id = randomUUID();
29
- const stop = () => { bridge.call("/run/stop", { id }).catch(() => { }); };
30
- if (signal?.aborted)
31
- stop();
32
- else
33
- signal?.addEventListener("abort", stop, { once: true });
34
+ const offStop = onAbort(signal, () => {
35
+ bridge.call("/run/stop", { id }).catch(() => { });
36
+ });
34
37
  try {
35
38
  return await bridge.call("/run/program", {
36
39
  ...request,
@@ -41,7 +44,7 @@ export async function runProgram(options) {
41
44
  });
42
45
  }
43
46
  finally {
44
- signal?.removeEventListener("abort", stop);
47
+ offStop();
45
48
  }
46
49
  }
47
50
  /** The shared workspace in a directory, created if it does not exist: read, write, list, observe. */
@@ -49,8 +52,7 @@ export function createWorkspace(dir) {
49
52
  const bridge = parentBridge();
50
53
  if (!bridge)
51
54
  return workspaceHere(dir);
52
- const absolute = resolve(dir);
53
- mkdirSync(absolute, { recursive: true }); // it exists from here on, as it does outside a program
55
+ const absolute = ensureWorkspaceDir(dir); // it exists from here on, as it does outside a program
54
56
  return remoteWorkspace(bridge.call, absolute);
55
57
  }
56
58
  // --- Example programs (included in system prompt during create/update) ---
@@ -104,7 +106,7 @@ for (let i = ctx.iteration; i < ctx.maxIterations; i++) {
104
106
  }
105
107
 
106
108
  await tools.write("target.ts", code);
107
- await ctx.done({ finalMetric: bestMetric });
109
+ await ctx.done({ finalMetric: Number.isFinite(bestMetric) ? bestMetric : null });
108
110
 
109
111
  // Example D: Long-running server.
110
112
  // Call ctx.ready() only after the server is actually listening.
@@ -159,24 +161,44 @@ export function resolveProject(name) {
159
161
  return dir;
160
162
  }
161
163
  // --- Helpers ---
162
- /** Ask in an empty throwaway directory, so the agent's tools cannot write into the real project. */
163
- async function isolatedAsk(backend, prompt, system) {
164
- return withTempDir("trama-gen-", (cwd) => backend.ask(prompt, { cwd, system }));
164
+ /**
165
+ * Ask for a program — in an empty throwaway directory, so the agent's tools
166
+ * cannot write into the real project — and take what comes back for one only
167
+ * if something does: no program is not a program that does nothing.
168
+ */
169
+ async function generateProgram(backend, prompt, system, signal) {
170
+ const program = stripCodeFences(await withTempDir("trama-gen-", (cwd) => backend.ask(prompt, { cwd, system, signal })));
171
+ throwIfAborted(signal);
172
+ if (program === "")
173
+ throw new Error("The model answered with no program.");
174
+ return program;
165
175
  }
166
- const validationOptions = (config) => ({
176
+ const validationOptions = (config, signal) => ({
167
177
  timeout: config.defaultTimeout,
168
178
  maxRepairAttempts: config.maxRepairAttempts,
169
179
  maxIterations: config.defaultMaxIterations,
180
+ journalRuns: config.journalRuns,
181
+ signal,
170
182
  });
171
183
  // --- Public API ---
172
184
  export async function createProject(name, prompt, options) {
173
185
  validateProjectName(name);
186
+ throwIfAborted(options?.signal);
174
187
  const projectDir = join(projectsDir(), name);
175
188
  let keepProjectOnFailure = false;
176
- if (existsSync(projectDir)) {
177
- throw new Error(`Project "${name}" already exists.`);
189
+ mkdirSync(projectsDir(), { recursive: true });
190
+ try {
191
+ // Made here, and only here: whatever bears the name already — a project, a file, a link to nothing — is in the way.
192
+ mkdirSync(projectDir);
193
+ }
194
+ catch (err) {
195
+ if (err.code === "EEXIST")
196
+ throw new Error(`Project "${name}" already exists.`);
197
+ throw err;
178
198
  }
179
- mkdirSync(projectDir, { recursive: true });
199
+ // The directory made just now is the project: what is done from here on is done to it, and it alone is taken away again.
200
+ const made = identityOf(projectDir);
201
+ const stillTheProject = sameProjectAs(projectDir);
180
202
  try {
181
203
  ensureProjectScaffold(projectDir);
182
204
  const config = loadConfig();
@@ -192,56 +214,60 @@ export async function createProject(name, prompt, options) {
192
214
  writeFileSync(join(projectDir, "meta.json"), JSON.stringify(meta, null, 2));
193
215
  const backend = createBackend(config);
194
216
  console.log(`Generating program for "${name}"...`);
195
- const candidate = stripCodeFences(await isolatedAsk(backend, `${prompt}\n\nOutput ONLY the TypeScript program. No markdown fences. No explanation.`, getSystemPrompt()));
217
+ const candidate = await generateProgram(backend, `${prompt}\n\nOutput ONLY the TypeScript program. No markdown fences. No explanation.`, getSystemPrompt(), options?.signal);
218
+ stillTheProject();
196
219
  // From here on the project is kept even if validation fails, so the
197
220
  // generated program can be inspected and fixed by hand.
198
- writeFileSync(join(projectDir, "program.ts"), candidate);
221
+ writeFileSync(guardPath(projectDir, "program.ts"), candidate);
199
222
  keepProjectOnFailure = true;
200
223
  console.log("Validating program...");
201
- const validated = await validateProgram(projectDir, backend, candidate, validationOptions(config));
224
+ const validated = await validateProgram(projectDir, backend, candidate, validationOptions(config, options?.signal));
225
+ stillTheProject();
202
226
  installValidatedProgram(projectDir, validated, "create", prompt);
203
227
  console.log(`Created ${name}. Run with: trama run ${name}`);
204
228
  }
205
229
  catch (err) {
206
- if (!keepProjectOnFailure) {
230
+ if (!keepProjectOnFailure && identityOf(projectDir) === made) {
207
231
  rmSync(projectDir, { recursive: true, force: true });
208
232
  }
209
233
  throw err;
210
234
  }
211
235
  }
212
- export async function updateProject(name, prompt) {
236
+ export async function updateProject(name, prompt, options) {
213
237
  const projectDir = resolveProject(name);
214
- // A hand-written project may never have been run: give it history/ and the rest first.
215
- ensureProjectScaffold(projectDir);
216
- const programPath = guardPath(projectDir, "program.ts");
217
- const originalSource = readFileSync(programPath, "utf-8");
218
- const state = loadState(projectDir);
219
- const meta = JSON.parse(readFileSync(guardPath(projectDir, "meta.json"), "utf-8"));
220
- const config = loadProjectConfig(projectDir);
221
- const backend = createBackend(config);
222
- const systemPrompt = getSystemPrompt() +
223
- `\n\nOriginal prompt: ${meta.input.prompt}` +
224
- `\n\nCurrent program.ts:\n${originalSource}` +
225
- (Object.keys(state).length > 0 ? `\n\nCurrent state:\n${JSON.stringify(state, null, 2)}` : "");
238
+ const unchanged = (why) => new Error(`Update failed — the program is unchanged.\n${messageOf(why)}`);
239
+ const stillTheProject = sameProjectAs(projectDir);
240
+ // Asked before anything else is done, the project's own preparation included: an update's only
241
+ // use is to replace the program, and where that cannot be done there is nothing to prepare for.
242
+ const refusal = whyNotReplaceable(projectDir);
243
+ if (refusal)
244
+ throw unchanged(refusal);
226
245
  // The new program is generated and validated off to the side. The project is
227
246
  // only written to once there is a program that works, so a failed update has
228
247
  // nothing to undo.
229
248
  try {
249
+ throwIfAborted(options?.signal);
250
+ // A hand-written project may never have been run: give it history/ and the rest first.
251
+ ensureProjectScaffold(projectDir);
252
+ const originalSource = readFileSync(guardPath(projectDir, "program.ts"), "utf-8");
253
+ const state = loadState(projectDir);
254
+ const meta = readProjectMeta(projectDir);
255
+ const config = loadProjectConfig(projectDir, meta);
256
+ const backend = createBackend(config);
257
+ const systemPrompt = getSystemPrompt() +
258
+ `\n\nOriginal prompt: ${meta.input.prompt}` +
259
+ `\n\nCurrent program.ts:\n${originalSource}` +
260
+ (Object.keys(state).length > 0 ? `\n\nCurrent state:\n${JSON.stringify(state, null, 2)}` : "");
230
261
  console.log(`Updating "${name}"...`);
231
- const candidate = stripCodeFences(await isolatedAsk(backend, `${prompt}\n\nOutput the complete updated program.ts. No partial patches. No markdown fences. No explanation.`, systemPrompt));
262
+ const candidate = await generateProgram(backend, `${prompt}\n\nOutput the complete updated program.ts. No partial patches. No markdown fences. No explanation.`, systemPrompt, options?.signal);
263
+ stillTheProject();
232
264
  console.log("Validating updated program...");
233
- const validated = await validateProgram(projectDir, backend, candidate, validationOptions(config));
234
- try {
235
- installValidatedProgram(projectDir, validated, "update", prompt);
236
- }
237
- catch (err) {
238
- writeFileSync(programPath, originalSource); // recording the version failed: don't leave an unrecorded program behind
239
- throw err;
240
- }
265
+ const validated = await validateProgram(projectDir, backend, candidate, validationOptions(config, options?.signal));
266
+ stillTheProject();
267
+ installValidatedProgram(projectDir, validated, "update", prompt);
241
268
  }
242
269
  catch (err) {
243
- throw new Error(`Update failed — the project is unchanged.\n` +
244
- `${err instanceof Error ? err.message : err}`);
270
+ throw unchanged(err);
245
271
  }
246
272
  console.log(`Updated ${name}. Run with: trama run ${name}`);
247
273
  }
@@ -262,7 +288,7 @@ export async function listProjects() {
262
288
  let prompt = "";
263
289
  let modified = "";
264
290
  try {
265
- const meta = JSON.parse(readFileSync(guardPath(projectDir, "meta.json"), "utf-8"));
291
+ const meta = readProjectMeta(projectDir);
266
292
  prompt = meta.input?.prompt ?? "";
267
293
  if (prompt.length > 60)
268
294
  prompt = prompt.slice(0, 57) + "...";
@@ -278,12 +304,19 @@ export async function listProjects() {
278
304
  }
279
305
  export async function showLogs(name) {
280
306
  const projectDir = resolveProject(name);
281
- const logsPath = guardPath(projectDir, join("logs", "latest.jsonl"));
282
- if (!existsSync(logsPath)) {
283
- console.log("No logs found.");
284
- return;
307
+ const logsPath = guardPath(projectDir, LATEST_LOG_PATH);
308
+ let raw;
309
+ try {
310
+ raw = readFileSync(logsPath, "utf-8");
311
+ }
312
+ catch (err) {
313
+ if (err.code === "ENOENT") {
314
+ console.log("No logs found.");
315
+ return;
316
+ }
317
+ throw err;
285
318
  }
286
- const content = readFileSync(logsPath, "utf-8").trim();
319
+ const content = raw.trim();
287
320
  if (!content) {
288
321
  console.log("No log entries.");
289
322
  return;
@@ -300,3 +333,10 @@ export async function showLogs(name) {
300
333
  }
301
334
  }
302
335
  }
336
+ /**
337
+ * Show what a run of a project did, from its journal: the latest run, or the
338
+ * one named. With `list`, show which runs have a journal instead.
339
+ */
340
+ export async function showJournal(name, options = {}) {
341
+ printJournals(resolveProject(name), name, options);
342
+ }
@@ -1,6 +1,8 @@
1
1
  import { type Server } from "http";
2
- import type { Ctx, Agent, Tools, Workspace } from "./types.js";
2
+ import type { Agent, Tools, Workspace } from "./types.js";
3
+ import type { RunContext } from "./context.js";
3
4
  import type { ProgramResult, RunRequest } from "./runner-types.js";
5
+ import type { Journal } from "./journal.js";
4
6
  export interface IpcBackends {
5
7
  /**
6
8
  * The secret only this run's program knows. Every request must present it:
@@ -8,19 +10,23 @@ export interface IpcBackends {
8
10
  * page the user happens to have open — could otherwise send commands to.
9
11
  */
10
12
  token: string;
11
- ctx: Ctx;
13
+ ctx: RunContext;
12
14
  agent: Agent;
13
15
  tools: Tools;
14
16
  /** The workspace of the session the program is running in — null when it is in none. */
15
17
  workspace: Workspace | null;
16
18
  /** A workspace by directory, for a program that created a session rather than joined one. */
17
19
  workspaceAt(dir: string): Workspace;
18
- /** Run another project on the program's behalf, until it ends or `stop` says to stop it. */
19
- run(request: RunRequest, stop: AbortSignal): Promise<ProgramResult>;
20
- /** Called once ctx.done() or ctx.yield() has been persisted for this run. */
21
- onTerminalSignal(result: ProgramResult): void;
20
+ /**
21
+ * Run another project on the program's behalf, until it ends or `stop` says
22
+ * to stop it. `seq` is the position of the call that asked for it.
23
+ */
24
+ run(request: RunRequest, stop: AbortSignal, seq: number): Promise<ProgramResult>;
25
+ /** Where every call, and how it ended, is written down. */
26
+ journal: Journal;
22
27
  }
23
28
  export declare function createIPCServer(backends: IpcBackends): Server;
24
29
  /** Start listening on an ephemeral loopback port and return it. */
25
30
  export declare function listen(server: Server): Promise<number>;
31
+ /** Stop listening, and wait until it has. (The one thing a server can say against it is that it was not listening.) */
26
32
  export declare function closeServer(server: Server): Promise<void>;