@trama-dev/runtime 0.4.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.
Files changed (56) 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 +127 -7
  5. package/dist/agent-backend.js +38 -19
  6. package/dist/agent-host.d.ts +50 -0
  7. package/dist/agent-host.js +97 -0
  8. package/dist/agent-hosts.d.ts +14 -0
  9. package/dist/agent-hosts.js +321 -0
  10. package/dist/agent.d.ts +26 -3
  11. package/dist/agent.js +165 -43
  12. package/dist/bridge-client.d.ts +6 -0
  13. package/dist/bridge-client.js +69 -16
  14. package/dist/budget.d.ts +52 -0
  15. package/dist/budget.js +118 -0
  16. package/dist/child-process.d.ts +18 -0
  17. package/dist/child-process.js +38 -9
  18. package/dist/client.d.ts +2 -1
  19. package/dist/client.js +9 -19
  20. package/dist/context.d.ts +36 -7
  21. package/dist/context.js +83 -92
  22. package/dist/errors.d.ts +2 -0
  23. package/dist/errors.js +2 -0
  24. package/dist/index.d.ts +7 -2
  25. package/dist/index.js +254 -88
  26. package/dist/ipc-server.d.ts +14 -5
  27. package/dist/ipc-server.js +174 -144
  28. package/dist/journal-view.d.ts +2 -0
  29. package/dist/journal-view.js +52 -7
  30. package/dist/journal.d.ts +27 -9
  31. package/dist/journal.js +216 -79
  32. package/dist/meta.d.ts +18 -0
  33. package/dist/meta.js +29 -0
  34. package/dist/model-relay.d.ts +130 -0
  35. package/dist/model-relay.js +339 -0
  36. package/dist/path-guard.d.ts +128 -19
  37. package/dist/path-guard.js +384 -68
  38. package/dist/pi-adapter.d.ts +35 -9
  39. package/dist/pi-adapter.js +865 -66
  40. package/dist/replace-file.d.ts +31 -0
  41. package/dist/replace-file.js +75 -0
  42. package/dist/runner-types.d.ts +35 -0
  43. package/dist/runner.d.ts +202 -30
  44. package/dist/runner.js +949 -273
  45. package/dist/serializable.d.ts +10 -4
  46. package/dist/serializable.js +56 -31
  47. package/dist/stopping.d.ts +37 -3
  48. package/dist/stopping.js +167 -21
  49. package/dist/tools.d.ts +2 -1
  50. package/dist/tools.js +90 -21
  51. package/dist/tree.d.ts +241 -0
  52. package/dist/tree.js +1431 -0
  53. package/dist/types.d.ts +106 -15
  54. package/dist/workspace.d.ts +7 -0
  55. package/dist/workspace.js +93 -104
  56. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -5,53 +5,64 @@ 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";
10
- import { parentBridge, remoteWorkspace } from "./bridge-client.js";
11
- import { guardPath } from "./path-guard.js";
12
- import { printJournals } from "./journal-view.js";
13
- // --- Running a project, and reaching a workspace ---
8
+ import { onAbort, throwIfAborted } from "./abort.js";
9
+ import { createMeter } from "./budget.js";
10
+ import { LATEST_LOG_PATH } from "./context.js";
11
+ import { readProjectMeta } from "./meta.js";
12
+ import { loadConfig, loadProjectConfig, loadState, createBackend, validateProgram, installValidatedProgram, withTempDir, prepareProject, shownPaths, ensureProjectScaffold, RUNTIME_TYPES, runProgram as runHere, whyNotReplaceable, tagged, saysOnce, } from "./runner.js";
13
+ import { createWorkspace as workspaceHere, ensureWorkspaceDir } from "./workspace.js";
14
+ import { parentBridge, remoteWorkspace, withOptions } from "./bridge-client.js";
15
+ import { guardPath, identityOf, sameProjectAs } from "./path-guard.js";
16
+ import { printJournals, spentIn } from "./journal-view.js";
17
+ import { messageOf } from "./errors.js";
18
+ // --- Running a project, making one, and reaching a workspace ---
14
19
  //
15
- // A program never runs another program: it asks its runner to. So these two do
16
- // their work in this process only when this process is not itself a program.
17
- // Inside one they are calls on the bridge, carried out by the one runner that
18
- // owns every run in the tree — which is how it can time them, stop them, and
19
- // see them.
20
- /** Run a project to an outcome: done, yielded, or failed. */
21
- export async function runProgram(options) {
22
- const bridge = parentBridge();
23
- if (!bridge)
24
- return runHere(options);
25
- // A signal cannot cross the bridge, but what it says can: the runner is told
26
- // to stop the run, and this call still waits for the run to be over — the
27
- // same as outside a program.
28
- const { signal, ...request } = options;
20
+ // A program never runs another program, nor makes or changes a project: it
21
+ // asks its runner to. So these do their work in this process only when this
22
+ // process is not itself a program. Inside one they are calls on the bridge,
23
+ // carried out by the one runner that owns every run in the tree — which is
24
+ // how it can time them, stop them, count what they use, and see them.
25
+ /**
26
+ * Ask this program's runner for something that lasts as long as the call
27
+ * does — a run, a project made. A signal cannot cross the bridge, but what
28
+ * it says can: the runner is told to stop it, and this call still waits for
29
+ * it to be over — the same as outside a program.
30
+ */
31
+ async function overBridge(bridge, endpoint, asked, signal) {
29
32
  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 });
33
+ const offStop = onAbort(signal, () => {
34
+ bridge.call("/run/stop", { id }).catch(() => { });
35
+ });
35
36
  try {
36
- return await bridge.call("/run/program", {
37
- ...request,
38
- id,
39
- // The runner does not share this program's working directory.
40
- projectDir: resolve(request.projectDir),
41
- workspaceDir: request.workspaceDir && resolve(request.workspaceDir),
42
- });
37
+ return await bridge.call(endpoint, withOptions({ id }, asked));
43
38
  }
44
39
  finally {
45
- signal?.removeEventListener("abort", stop);
40
+ offStop();
46
41
  }
47
42
  }
43
+ /** How this runner makes or changes a project for a program that asks it to (see Making). */
44
+ const making = (request, asked) => request.kind === "create"
45
+ ? createHere(request.name, request.prompt, { model: request.model, args: request.args, signal: asked.signal }, asked)
46
+ : updateHere(request.name, request.prompt, { signal: asked.signal }, asked);
47
+ /** Run a project to an outcome: done, yielded, or failed. */
48
+ export async function runProgram(options) {
49
+ const bridge = parentBridge();
50
+ if (!bridge)
51
+ return runHere(options, undefined, making);
52
+ const { signal, ...request } = options;
53
+ return overBridge(bridge, "/run/program", {
54
+ ...request,
55
+ // The runner does not share this program's working directory.
56
+ projectDir: resolve(request.projectDir),
57
+ workspaceDir: request.workspaceDir && resolve(request.workspaceDir),
58
+ }, signal);
59
+ }
48
60
  /** The shared workspace in a directory, created if it does not exist: read, write, list, observe. */
49
61
  export function createWorkspace(dir) {
50
62
  const bridge = parentBridge();
51
63
  if (!bridge)
52
64
  return workspaceHere(dir);
53
- const absolute = resolve(dir);
54
- mkdirSync(absolute, { recursive: true }); // it exists from here on, as it does outside a program
65
+ const absolute = ensureWorkspaceDir(dir); // it exists from here on, as it does outside a program
55
66
  return remoteWorkspace(bridge.call, absolute);
56
67
  }
57
68
  // --- Example programs (included in system prompt during create/update) ---
@@ -105,7 +116,7 @@ for (let i = ctx.iteration; i < ctx.maxIterations; i++) {
105
116
  }
106
117
 
107
118
  await tools.write("target.ts", code);
108
- await ctx.done({ finalMetric: bestMetric });
119
+ await ctx.done({ finalMetric: Number.isFinite(bestMetric) ? bestMetric : null });
109
120
 
110
121
  // Example D: Long-running server.
111
122
  // Call ctx.ready() only after the server is actually listening.
@@ -134,12 +145,19 @@ process.on("SIGINT", () => {
134
145
  });
135
146
 
136
147
  await new Promise<void>(() => {});`;
137
- function getSystemPrompt() {
148
+ function getSystemPrompt(kept) {
138
149
  return (`You are generating a TypeScript program for the trama runtime.\n\n` +
139
150
  `If the program is long-running (for example an HTTP server), call ctx.ready(...) after startup completes and handle SIGTERM/SIGINT for clean shutdown.\n\n` +
140
151
  `The workspace object is available when running in a session (shared artifact I/O between agents). ` +
141
152
  `ctx.yield(reason) suspends the program cooperatively — persists state and exits. ` +
142
153
  `ctx.resumed is true if this run follows a yield; ctx.yieldReason has the reason.\n\n` +
154
+ `You are working in a copy of the project's directory, which is where the program will run: ` +
155
+ `where the task speaks of the project's files, look at them. ` +
156
+ (kept
157
+ ? `What the program needs beside it — a package installed, a module it imports, a file it reads — ` +
158
+ `you can make here: it is kept, with the program, if the program then passes its validation. ` +
159
+ `The program itself is what you answer with, whatever you wrote to program.ts here.\n\n`
160
+ : `Nothing you write here is kept — only the program you answer with.\n\n`) +
143
161
  `Runtime API:\n${RUNTIME_TYPES}\n\n` +
144
162
  `Examples:\n${EXAMPLE_PROGRAMS}`);
145
163
  }
@@ -160,25 +178,147 @@ export function resolveProject(name) {
160
178
  return dir;
161
179
  }
162
180
  // --- 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 }));
181
+ /**
182
+ * Ask for a program for a project — in a copy of the project (see Prepared),
183
+ * so that the agent can look at what the program is to work with and make
184
+ * what it needs, and its tools do not write into the real one — and take
185
+ * what comes back for a program only if something does: no program is not a
186
+ * program that does nothing.
187
+ */
188
+ async function generateProgram(backend, prepared, prompt, system, wrote, signal, label) {
189
+ let reply;
190
+ try {
191
+ reply = await backend.ask(prompt, { cwd: prepared.copy, system, signal, used: (usage) => { wrote.push(usage); } });
192
+ }
193
+ finally {
194
+ // What it took is said whatever came of it: it is on record only with a validation, and there may be none.
195
+ // (A call that was cut off — stopped, or by the budget — says what it took once its backend has let go of it.)
196
+ await backend.letGo();
197
+ if (wrote.length > 0)
198
+ console.log(tagged(label, `[trama] writing the program used ${spentIn(wrote)}`));
199
+ }
200
+ const program = stripCodeFences(reply);
201
+ throwIfAborted(signal);
202
+ if (program === "")
203
+ throw new Error("The model answered with no program.");
204
+ return program;
205
+ }
206
+ /**
207
+ * The budget a create or an update is held to, writing the program and
208
+ * validating it together: the config's — or, where a run's program asked
209
+ * for it, that run's and those above it, and not the config's a second time.
210
+ */
211
+ const budgetOf = (config, asked) => (asked.above ? undefined : config.budget);
212
+ /**
213
+ * The backend a create or an update asks: held to its budget, and it is said
214
+ * when that is spent — once, and where a run's program asked, once for that
215
+ * run, in the run's own words: a program may ask for many projects.
216
+ */
217
+ function backendFor(config, asked) {
218
+ const say = (why) => console.warn(tagged(asked.label, `[trama] ${why}`));
219
+ const { above } = asked;
220
+ // (Asked for by a run's program, the project is written by an agent of that run: with the run's variables.)
221
+ return createBackend(config, createMeter(budgetOf(config, asked), above), above ? saysOnce(above, (why) => say(above.spent() ?? why)) : say, asked.env);
222
+ }
223
+ /** Carry what the agent made beside a program into the project the program is now in, and say what that was. */
224
+ function keepPrepared(prepared, label) {
225
+ const console = shownUnder(label);
226
+ let kept;
227
+ try {
228
+ kept = prepared.keep();
229
+ }
230
+ catch (err) {
231
+ // The program is in the project. That what was made beside it cannot be carried over is said, and does not undo that.
232
+ console.warn(`[trama] what was made beside the program, while it was written, could not be carried into the project: ${messageOf(err)}`);
233
+ return;
234
+ }
235
+ const { changed, unmerged } = kept;
236
+ if (changed.length > 0) {
237
+ console.log(`[trama] ${changed.length} path(s) made or changed beside the program, while it was written: ${shownPaths(changed)}`);
238
+ }
239
+ if (unmerged.length > 0) {
240
+ console.warn(`[trama] ${unmerged.length} thing(s) done while the program was written did not reach the project:`);
241
+ for (const { path, why } of unmerged)
242
+ console.warn(`[trama] ${path} — ${why}`);
243
+ }
244
+ }
245
+ /**
246
+ * Validate a candidate for a project: in the project as the agent prepared
247
+ * it, where what the agent made is to be kept — or in the project as it is.
248
+ * `kept` says which: what was validated is what is then to be in the
249
+ * project. The agent's copy is no place to validate in where it is no longer
250
+ * the copy the agent was given (a link put in its place is not followed), or
251
+ * cannot be copied; the candidate is then validated by itself, which is said
252
+ * (see validateProgram).
253
+ */
254
+ async function validateCandidate(projectDir, backend, candidate, config, prepared, wrote, signal, asked) {
255
+ let as, alone;
256
+ if (config.agentChanges === "keep") {
257
+ try {
258
+ prepared.ready();
259
+ as = prepared.copy;
260
+ }
261
+ catch (err) {
262
+ alone = messageOf(err);
263
+ }
264
+ }
265
+ const validated = await validateProgram(projectDir, backend, candidate, {
266
+ timeout: config.defaultTimeout,
267
+ maxRepairAttempts: config.maxRepairAttempts,
268
+ maxIterations: config.defaultMaxIterations,
269
+ journalRuns: config.journalRuns,
270
+ signal,
271
+ as,
272
+ alone,
273
+ budget: budgetOf(config, asked),
274
+ wrote,
275
+ label: asked.label,
276
+ env: asked.env,
277
+ askedFor: asked.parent && asked.started && { parent: asked.parent, started: asked.started },
278
+ });
279
+ return { validated, kept: as !== undefined && validated.alone === undefined };
166
280
  }
167
- const validationOptions = (config) => ({
168
- timeout: config.defaultTimeout,
169
- maxRepairAttempts: config.maxRepairAttempts,
170
- maxIterations: config.defaultMaxIterations,
171
- journalRuns: config.journalRuns,
281
+ /** What is shown of a project being made, under the name of the run that asked for it — if one did, and has one. */
282
+ const shownUnder = (label) => ({
283
+ log: (line) => console.log(tagged(label, line)),
284
+ warn: (line) => console.warn(tagged(label, line)),
172
285
  });
173
286
  // --- Public API ---
287
+ /** Generate a program for a new project from a prompt, validate it, and make it the project's. */
174
288
  export async function createProject(name, prompt, options) {
289
+ const bridge = parentBridge();
290
+ if (!bridge)
291
+ return createHere(name, prompt, options);
292
+ const { signal, ...asked } = options ?? {};
293
+ await overBridge(bridge, "/project/create", withOptions({ name, prompt }, asked), signal);
294
+ }
295
+ /** Generate a new program for a project from a prompt and its current one, validate it, and put it in the other's place. */
296
+ export async function updateProject(name, prompt, options) {
297
+ const bridge = parentBridge();
298
+ if (!bridge)
299
+ return updateHere(name, prompt, options);
300
+ const { signal, ...asked } = options ?? {};
301
+ await overBridge(bridge, "/project/update", withOptions({ name, prompt }, asked), signal);
302
+ }
303
+ async function createHere(name, prompt, options, asked = {}) {
304
+ const console = shownUnder(asked.label);
175
305
  validateProjectName(name);
306
+ throwIfAborted(options?.signal);
176
307
  const projectDir = join(projectsDir(), name);
177
308
  let keepProjectOnFailure = false;
178
- if (existsSync(projectDir)) {
179
- throw new Error(`Project "${name}" already exists.`);
309
+ mkdirSync(projectsDir(), { recursive: true });
310
+ try {
311
+ // Made here, and only here: whatever bears the name already — a project, a file, a link to nothing — is in the way.
312
+ mkdirSync(projectDir);
180
313
  }
181
- mkdirSync(projectDir, { recursive: true });
314
+ catch (err) {
315
+ if (err.code === "EEXIST")
316
+ throw new Error(`Project "${name}" already exists.`);
317
+ throw err;
318
+ }
319
+ // 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.
320
+ const made = identityOf(projectDir);
321
+ const stillTheProject = sameProjectAs(projectDir);
182
322
  try {
183
323
  ensureProjectScaffold(projectDir);
184
324
  const config = loadConfig();
@@ -192,58 +332,77 @@ export async function createProject(name, prompt, options) {
192
332
  provider: config.provider,
193
333
  };
194
334
  writeFileSync(join(projectDir, "meta.json"), JSON.stringify(meta, null, 2));
195
- const backend = createBackend(config);
335
+ const backend = backendFor(config, asked);
336
+ const wrote = [];
196
337
  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()));
198
- // From here on the project is kept even if validation fails, so the
199
- // generated program can be inspected and fixed by hand.
200
- writeFileSync(join(projectDir, "program.ts"), candidate);
201
- keepProjectOnFailure = true;
202
- console.log("Validating program...");
203
- const validated = await validateProgram(projectDir, backend, candidate, validationOptions(config));
204
- installValidatedProgram(projectDir, validated, "create", prompt);
338
+ // (What the agent is given to look at is the project made here, and no other directory that is at its path by now.)
339
+ stillTheProject();
340
+ await withTempDir("trama-gen-", async (privateDir) => {
341
+ const prepared = prepareProject(projectDir, privateDir);
342
+ const candidate = await generateProgram(backend, prepared, `${prompt}\n\nOutput ONLY the TypeScript program. No markdown fences. No explanation.`, getSystemPrompt(config.agentChanges === "keep"), wrote, options?.signal, asked.label);
343
+ stillTheProject();
344
+ // From here on the project is kept even if validation fails, so the
345
+ // generated program can be inspected and fixed by hand.
346
+ writeFileSync(guardPath(projectDir, "program.ts"), candidate);
347
+ keepProjectOnFailure = true;
348
+ console.log("Validating program...");
349
+ const { validated, kept } = await validateCandidate(projectDir, backend, candidate, config, prepared, wrote, options?.signal, asked);
350
+ stillTheProject();
351
+ installValidatedProgram(projectDir, validated, "create", prompt);
352
+ if (kept)
353
+ keepPrepared(prepared, asked.label);
354
+ });
205
355
  console.log(`Created ${name}. Run with: trama run ${name}`);
206
356
  }
207
357
  catch (err) {
208
- if (!keepProjectOnFailure) {
358
+ if (!keepProjectOnFailure && identityOf(projectDir) === made) {
209
359
  rmSync(projectDir, { recursive: true, force: true });
210
360
  }
211
361
  throw err;
212
362
  }
213
363
  }
214
- export async function updateProject(name, prompt) {
364
+ async function updateHere(name, prompt, options, asked = {}) {
365
+ const console = shownUnder(asked.label);
215
366
  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)}` : "");
367
+ const unchanged = (why) => new Error(`Update failed — the program is unchanged.\n${messageOf(why)}`);
368
+ const stillTheProject = sameProjectAs(projectDir);
369
+ // Asked before anything else is done, the project's own preparation included: an update's only
370
+ // use is to replace the program, and where that cannot be done there is nothing to prepare for.
371
+ const refusal = whyNotReplaceable(projectDir);
372
+ if (refusal)
373
+ throw unchanged(refusal);
228
374
  // The new program is generated and validated off to the side. The project is
229
375
  // only written to once there is a program that works, so a failed update has
230
376
  // nothing to undo.
231
377
  try {
378
+ throwIfAborted(options?.signal);
379
+ // A hand-written project may never have been run: give it history/ and the rest first.
380
+ ensureProjectScaffold(projectDir);
381
+ const originalSource = readFileSync(guardPath(projectDir, "program.ts"), "utf-8");
382
+ const state = loadState(projectDir);
383
+ const meta = readProjectMeta(projectDir);
384
+ const config = loadProjectConfig(projectDir, meta);
385
+ const backend = backendFor(config, asked);
386
+ const wrote = [];
387
+ const systemPrompt = getSystemPrompt(config.agentChanges === "keep") +
388
+ `\n\nOriginal prompt: ${meta.input.prompt}` +
389
+ `\n\nCurrent program.ts:\n${originalSource}` +
390
+ (Object.keys(state).length > 0 ? `\n\nCurrent state:\n${JSON.stringify(state, null, 2)}` : "");
232
391
  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));
234
- console.log("Validating updated program...");
235
- const validated = await validateProgram(projectDir, backend, candidate, validationOptions(config));
236
- try {
392
+ await withTempDir("trama-gen-", async (privateDir) => {
393
+ const prepared = prepareProject(projectDir, privateDir);
394
+ const candidate = await generateProgram(backend, prepared, `${prompt}\n\nOutput the complete updated program.ts. No partial patches. No markdown fences. No explanation.`, systemPrompt, wrote, options?.signal, asked.label);
395
+ stillTheProject();
396
+ console.log("Validating updated program...");
397
+ const { validated, kept } = await validateCandidate(projectDir, backend, candidate, config, prepared, wrote, options?.signal, asked);
398
+ stillTheProject();
237
399
  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
- }
400
+ if (kept)
401
+ keepPrepared(prepared, asked.label);
402
+ });
243
403
  }
244
404
  catch (err) {
245
- throw new Error(`Update failed — the project is unchanged.\n` +
246
- `${err instanceof Error ? err.message : err}`);
405
+ throw unchanged(err);
247
406
  }
248
407
  console.log(`Updated ${name}. Run with: trama run ${name}`);
249
408
  }
@@ -264,7 +423,7 @@ export async function listProjects() {
264
423
  let prompt = "";
265
424
  let modified = "";
266
425
  try {
267
- const meta = JSON.parse(readFileSync(guardPath(projectDir, "meta.json"), "utf-8"));
426
+ const meta = readProjectMeta(projectDir);
268
427
  prompt = meta.input?.prompt ?? "";
269
428
  if (prompt.length > 60)
270
429
  prompt = prompt.slice(0, 57) + "...";
@@ -280,12 +439,19 @@ export async function listProjects() {
280
439
  }
281
440
  export async function showLogs(name) {
282
441
  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;
442
+ const logsPath = guardPath(projectDir, LATEST_LOG_PATH);
443
+ let raw;
444
+ try {
445
+ raw = readFileSync(logsPath, "utf-8");
446
+ }
447
+ catch (err) {
448
+ if (err.code === "ENOENT") {
449
+ console.log("No logs found.");
450
+ return;
451
+ }
452
+ throw err;
287
453
  }
288
- const content = readFileSync(logsPath, "utf-8").trim();
454
+ const content = raw.trim();
289
455
  if (!content) {
290
456
  console.log("No log entries.");
291
457
  return;
@@ -1,6 +1,9 @@
1
1
  import { type Server } from "http";
2
- import type { Ctx, Agent, Tools, Workspace } from "./types.js";
2
+ import type { Tools, Workspace } from "./types.js";
3
+ import type { RunnerAgent } from "./agent.js";
4
+ import type { RunContext } from "./context.js";
3
5
  import type { ProgramResult, RunRequest } from "./runner-types.js";
6
+ import type { MakeRequest } from "./runner.js";
4
7
  import type { Journal } from "./journal.js";
5
8
  export interface IpcBackends {
6
9
  /**
@@ -9,8 +12,8 @@ export interface IpcBackends {
9
12
  * page the user happens to have open — could otherwise send commands to.
10
13
  */
11
14
  token: string;
12
- ctx: Ctx;
13
- agent: Agent;
15
+ ctx: RunContext;
16
+ agent: RunnerAgent;
14
17
  tools: Tools;
15
18
  /** The workspace of the session the program is running in — null when it is in none. */
16
19
  workspace: Workspace | null;
@@ -21,12 +24,18 @@ export interface IpcBackends {
21
24
  * to stop it. `seq` is the position of the call that asked for it.
22
25
  */
23
26
  run(request: RunRequest, stop: AbortSignal, seq: number): Promise<ProgramResult>;
27
+ /** Make a project, or change one, on the program's behalf — until it is done or `stop` says to stop. */
28
+ make(request: MakeRequest, stop: AbortSignal, seq: number): Promise<void>;
24
29
  /** Where every call, and how it ended, is written down. */
25
30
  journal: Journal;
26
- /** Called once ctx.done() or ctx.yield() has been persisted for this run. */
27
- onTerminalSignal(result: ProgramResult): void;
31
+ /**
32
+ * Whether the program has ended. What comes back for a call after that is
33
+ * no answer — though its connection may not have been seen to close yet.
34
+ */
35
+ programOver(): boolean;
28
36
  }
29
37
  export declare function createIPCServer(backends: IpcBackends): Server;
30
38
  /** Start listening on an ephemeral loopback port and return it. */
31
39
  export declare function listen(server: Server): Promise<number>;
40
+ /** Stop listening, and wait until it has. (The one thing a server can say against it is that it was not listening.) */
32
41
  export declare function closeServer(server: Server): Promise<void>;