@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/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
@@ -1,4 +1,4 @@
1
- export type { ProgramResult, RunOptions } from "./runner-types.js";
1
+ export type { Budget, ProgramResult, RunOptions } from "./runner-types.js";
2
2
  import type { ProgramResult, RunOptions } from "./runner-types.js";
3
3
  export type { Workspace, ObserveResult } from "./types.js";
4
4
  import type { Workspace } from "./types.js";
@@ -8,11 +8,16 @@ export declare function runProgram(options: RunOptions): Promise<ProgramResult>;
8
8
  export declare function createWorkspace(dir: string): Workspace;
9
9
  export declare function validateProjectName(name: string): void;
10
10
  export declare function resolveProject(name: string): string;
11
+ /** Generate a program for a new project from a prompt, validate it, and make it the project's. */
11
12
  export declare function createProject(name: string, prompt: string, options?: {
12
13
  model?: string;
13
14
  args?: Record<string, unknown>;
15
+ signal?: AbortSignal;
16
+ }): Promise<void>;
17
+ /** Generate a new program for a project from a prompt and its current one, validate it, and put it in the other's place. */
18
+ export declare function updateProject(name: string, prompt: string, options?: {
19
+ signal?: AbortSignal;
14
20
  }): Promise<void>;
15
- export declare function updateProject(name: string, prompt: string): Promise<void>;
16
21
  export declare function listProjects(): Promise<void>;
17
22
  export declare function showLogs(name: string): Promise<void>;
18
23
  /**