@trama-dev/runtime 0.4.0 → 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.
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,8 +11,11 @@ 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>;
18
21
  /**
package/dist/index.js CHANGED
@@ -5,11 +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";
12
15
  import { printJournals } from "./journal-view.js";
16
+ import { messageOf } from "./errors.js";
13
17
  // --- Running a project, and reaching a workspace ---
14
18
  //
15
19
  // A program never runs another program: it asks its runner to. So these two do
@@ -27,11 +31,9 @@ export async function runProgram(options) {
27
31
  // same as outside a program.
28
32
  const { signal, ...request } = options;
29
33
  const id = randomUUID();
30
- const stop = () => { bridge.call("/run/stop", { id }).catch(() => { }); };
31
- if (signal?.aborted)
32
- stop();
33
- else
34
- signal?.addEventListener("abort", stop, { once: true });
34
+ const offStop = onAbort(signal, () => {
35
+ bridge.call("/run/stop", { id }).catch(() => { });
36
+ });
35
37
  try {
36
38
  return await bridge.call("/run/program", {
37
39
  ...request,
@@ -42,7 +44,7 @@ export async function runProgram(options) {
42
44
  });
43
45
  }
44
46
  finally {
45
- signal?.removeEventListener("abort", stop);
47
+ offStop();
46
48
  }
47
49
  }
48
50
  /** The shared workspace in a directory, created if it does not exist: read, write, list, observe. */
@@ -50,8 +52,7 @@ export function createWorkspace(dir) {
50
52
  const bridge = parentBridge();
51
53
  if (!bridge)
52
54
  return workspaceHere(dir);
53
- const absolute = resolve(dir);
54
- 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
55
56
  return remoteWorkspace(bridge.call, absolute);
56
57
  }
57
58
  // --- Example programs (included in system prompt during create/update) ---
@@ -105,7 +106,7 @@ for (let i = ctx.iteration; i < ctx.maxIterations; i++) {
105
106
  }
106
107
 
107
108
  await tools.write("target.ts", code);
108
- await ctx.done({ finalMetric: bestMetric });
109
+ await ctx.done({ finalMetric: Number.isFinite(bestMetric) ? bestMetric : null });
109
110
 
110
111
  // Example D: Long-running server.
111
112
  // Call ctx.ready() only after the server is actually listening.
@@ -160,25 +161,44 @@ export function resolveProject(name) {
160
161
  return dir;
161
162
  }
162
163
  // --- Helpers ---
163
- /** Ask in an empty throwaway directory, so the agent's tools cannot write into the real project. */
164
- async function isolatedAsk(backend, prompt, system) {
165
- 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;
166
175
  }
167
- const validationOptions = (config) => ({
176
+ const validationOptions = (config, signal) => ({
168
177
  timeout: config.defaultTimeout,
169
178
  maxRepairAttempts: config.maxRepairAttempts,
170
179
  maxIterations: config.defaultMaxIterations,
171
180
  journalRuns: config.journalRuns,
181
+ signal,
172
182
  });
173
183
  // --- Public API ---
174
184
  export async function createProject(name, prompt, options) {
175
185
  validateProjectName(name);
186
+ throwIfAborted(options?.signal);
176
187
  const projectDir = join(projectsDir(), name);
177
188
  let keepProjectOnFailure = false;
178
- if (existsSync(projectDir)) {
179
- 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);
180
193
  }
181
- mkdirSync(projectDir, { recursive: true });
194
+ catch (err) {
195
+ if (err.code === "EEXIST")
196
+ throw new Error(`Project "${name}" already exists.`);
197
+ throw err;
198
+ }
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);
182
202
  try {
183
203
  ensureProjectScaffold(projectDir);
184
204
  const config = loadConfig();
@@ -194,56 +214,60 @@ export async function createProject(name, prompt, options) {
194
214
  writeFileSync(join(projectDir, "meta.json"), JSON.stringify(meta, null, 2));
195
215
  const backend = createBackend(config);
196
216
  console.log(`Generating program for "${name}"...`);
197
- 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();
198
219
  // From here on the project is kept even if validation fails, so the
199
220
  // generated program can be inspected and fixed by hand.
200
- writeFileSync(join(projectDir, "program.ts"), candidate);
221
+ writeFileSync(guardPath(projectDir, "program.ts"), candidate);
201
222
  keepProjectOnFailure = true;
202
223
  console.log("Validating program...");
203
- const validated = await validateProgram(projectDir, backend, candidate, validationOptions(config));
224
+ const validated = await validateProgram(projectDir, backend, candidate, validationOptions(config, options?.signal));
225
+ stillTheProject();
204
226
  installValidatedProgram(projectDir, validated, "create", prompt);
205
227
  console.log(`Created ${name}. Run with: trama run ${name}`);
206
228
  }
207
229
  catch (err) {
208
- if (!keepProjectOnFailure) {
230
+ if (!keepProjectOnFailure && identityOf(projectDir) === made) {
209
231
  rmSync(projectDir, { recursive: true, force: true });
210
232
  }
211
233
  throw err;
212
234
  }
213
235
  }
214
- export async function updateProject(name, prompt) {
236
+ export async function updateProject(name, prompt, options) {
215
237
  const projectDir = resolveProject(name);
216
- // A hand-written project may never have been run: give it history/ and the rest first.
217
- ensureProjectScaffold(projectDir);
218
- const programPath = guardPath(projectDir, "program.ts");
219
- const originalSource = readFileSync(programPath, "utf-8");
220
- const state = loadState(projectDir);
221
- const meta = JSON.parse(readFileSync(guardPath(projectDir, "meta.json"), "utf-8"));
222
- const config = loadProjectConfig(projectDir);
223
- const backend = createBackend(config);
224
- const systemPrompt = getSystemPrompt() +
225
- `\n\nOriginal prompt: ${meta.input.prompt}` +
226
- `\n\nCurrent program.ts:\n${originalSource}` +
227
- (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);
228
245
  // The new program is generated and validated off to the side. The project is
229
246
  // only written to once there is a program that works, so a failed update has
230
247
  // nothing to undo.
231
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)}` : "");
232
261
  console.log(`Updating "${name}"...`);
233
- 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();
234
264
  console.log("Validating updated program...");
235
- const validated = await validateProgram(projectDir, backend, candidate, validationOptions(config));
236
- try {
237
- installValidatedProgram(projectDir, validated, "update", prompt);
238
- }
239
- catch (err) {
240
- writeFileSync(programPath, originalSource); // recording the version failed: don't leave an unrecorded program behind
241
- throw err;
242
- }
265
+ const validated = await validateProgram(projectDir, backend, candidate, validationOptions(config, options?.signal));
266
+ stillTheProject();
267
+ installValidatedProgram(projectDir, validated, "update", prompt);
243
268
  }
244
269
  catch (err) {
245
- throw new Error(`Update failed — the project is unchanged.\n` +
246
- `${err instanceof Error ? err.message : err}`);
270
+ throw unchanged(err);
247
271
  }
248
272
  console.log(`Updated ${name}. Run with: trama run ${name}`);
249
273
  }
@@ -264,7 +288,7 @@ export async function listProjects() {
264
288
  let prompt = "";
265
289
  let modified = "";
266
290
  try {
267
- const meta = JSON.parse(readFileSync(guardPath(projectDir, "meta.json"), "utf-8"));
291
+ const meta = readProjectMeta(projectDir);
268
292
  prompt = meta.input?.prompt ?? "";
269
293
  if (prompt.length > 60)
270
294
  prompt = prompt.slice(0, 57) + "...";
@@ -280,12 +304,19 @@ export async function listProjects() {
280
304
  }
281
305
  export async function showLogs(name) {
282
306
  const projectDir = resolveProject(name);
283
- const logsPath = guardPath(projectDir, join("logs", "latest.jsonl"));
284
- if (!existsSync(logsPath)) {
285
- console.log("No logs found.");
286
- 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;
287
318
  }
288
- const content = readFileSync(logsPath, "utf-8").trim();
319
+ const content = raw.trim();
289
320
  if (!content) {
290
321
  console.log("No log entries.");
291
322
  return;
@@ -1,5 +1,6 @@
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";
4
5
  import type { Journal } from "./journal.js";
5
6
  export interface IpcBackends {
@@ -9,7 +10,7 @@ export interface IpcBackends {
9
10
  * page the user happens to have open — could otherwise send commands to.
10
11
  */
11
12
  token: string;
12
- ctx: Ctx;
13
+ ctx: RunContext;
13
14
  agent: Agent;
14
15
  tools: Tools;
15
16
  /** The workspace of the session the program is running in — null when it is in none. */
@@ -23,10 +24,9 @@ export interface IpcBackends {
23
24
  run(request: RunRequest, stop: AbortSignal, seq: number): Promise<ProgramResult>;
24
25
  /** Where every call, and how it ended, is written down. */
25
26
  journal: Journal;
26
- /** Called once ctx.done() or ctx.yield() has been persisted for this run. */
27
- onTerminalSignal(result: ProgramResult): void;
28
27
  }
29
28
  export declare function createIPCServer(backends: IpcBackends): Server;
30
29
  /** Start listening on an ephemeral loopback port and return it. */
31
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.) */
32
32
  export declare function closeServer(server: Server): Promise<void>;