@trama-dev/runtime 0.2.2 → 0.3.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.
@@ -0,0 +1,18 @@
1
+ export interface AgentCall {
2
+ /** The directory the agent works in: what its tools read is here, and what they write lands here. */
3
+ cwd: string;
4
+ /** Instructions for this call, on top of the agent's own. */
5
+ system?: string;
6
+ /** Cancels the call. A cancelled call rejects; it never resolves with a partial answer. */
7
+ signal?: AbortSignal;
8
+ }
9
+ export interface AgentBackend {
10
+ /**
11
+ * Run one prompt to completion and return the agent's final text.
12
+ *
13
+ * Each call stands alone — nothing carries over from one to the next, and
14
+ * everything a call depends on is in its arguments. A backend that cannot
15
+ * honour something in `call` must reject, never silently ignore it.
16
+ */
17
+ ask(prompt: string, call: AgentCall): Promise<string>;
18
+ }
@@ -0,0 +1,9 @@
1
+ // The one thing the runtime needs from whatever does the LLM work: hand it a
2
+ // prompt, get its final text back.
3
+ //
4
+ // Everything trama asks of an LLM goes through this — a program's agent calls,
5
+ // generating a program, repairing one. To a backend they are all the same
6
+ // request; what to ask for, and what to make of the reply, is decided by the
7
+ // caller. Nothing outside the backend's own file knows which agent, harness or
8
+ // model is behind it.
9
+ export {};
package/dist/agent.d.ts CHANGED
@@ -1,3 +1,13 @@
1
1
  import type { Agent } from "./types.js";
2
- import type { PiAdapter } from "./pi-adapter.js";
3
- export declare function createAgent(adapter: PiAdapter, signal?: AbortSignal): Agent;
2
+ import type { AgentBackend } from "./agent-backend.js";
3
+ /**
4
+ * The program in an LLM reply that was asked to contain nothing else: the last
5
+ * fenced block if there is one (models add explanations, or show a "before"
6
+ * first), otherwise the whole reply.
7
+ */
8
+ export declare function stripCodeFences(text: string): string;
9
+ /**
10
+ * The `agent` a program talks to: its calls, served by `backend` working in
11
+ * `cwd`, and cancelled together through `signal`.
12
+ */
13
+ export declare function createAgent(backend: AgentBackend, cwd: string, signal?: AbortSignal): Agent;
package/dist/agent.js CHANGED
@@ -1,3 +1,16 @@
1
+ /**
2
+ * The program in an LLM reply that was asked to contain nothing else: the last
3
+ * fenced block if there is one (models add explanations, or show a "before"
4
+ * first), otherwise the whole reply.
5
+ */
6
+ export function stripCodeFences(text) {
7
+ const trimmed = text.trim();
8
+ const matches = [...trimmed.matchAll(/```(?:\w*)\s*\n([\s\S]*?)\n\s*```/g)];
9
+ if (matches.length > 0) {
10
+ return matches[matches.length - 1][1].trim();
11
+ }
12
+ return trimmed;
13
+ }
1
14
  /**
2
15
  * Minimal shape validation.
3
16
  * Checks all schema keys exist and values match declared primitive types.
@@ -20,15 +33,19 @@ function validateShape(result, schema) {
20
33
  }
21
34
  return null;
22
35
  }
23
- export function createAgent(adapter, signal) {
36
+ /**
37
+ * The `agent` a program talks to: its calls, served by `backend` working in
38
+ * `cwd`, and cancelled together through `signal`.
39
+ */
40
+ export function createAgent(backend, cwd, signal) {
24
41
  return {
25
42
  async instruct(prompt, options) {
26
- return adapter.ask(prompt, signal ? { ...options, signal } : options);
43
+ return backend.ask(prompt, { cwd, system: options?.system, signal });
27
44
  },
28
45
  async generate(input) {
29
46
  const schemaInstruction = `Respond with ONLY a JSON object matching this shape:\n${JSON.stringify(input.schema, null, 2)}\nNo markdown. No explanation. Just the JSON.`;
30
47
  const fullPrompt = `${input.prompt}\n\n${schemaInstruction}`;
31
- const askOptions = signal ? { system: input.system, signal } : { system: input.system };
48
+ const call = { cwd, system: input.system, signal };
32
49
  const parseAndValidate = (response) => {
33
50
  const trimmed = response.trim();
34
51
  // Try raw parse first — avoids mangling valid JSON that contains
@@ -46,15 +63,15 @@ export function createAgent(adapter, signal) {
46
63
  throw new Error(`Schema validation failed: ${error}`);
47
64
  return stripToSchema(parsed, input.schema);
48
65
  };
49
- // First attempt — adapter errors (network/auth) propagate immediately.
66
+ // First attempt — backend errors (network/auth) propagate immediately.
50
67
  // Only parse/validation failures trigger a retry.
51
- const response = await adapter.ask(fullPrompt, askOptions);
68
+ const response = await backend.ask(fullPrompt, call);
52
69
  try {
53
70
  return parseAndValidate(response);
54
71
  }
55
72
  catch (firstError) {
56
73
  const retryPrompt = `Your previous response failed validation: ${firstError}.\nTry again.\n\n${fullPrompt}`;
57
- const retryResponse = await adapter.ask(retryPrompt, askOptions);
74
+ const retryResponse = await backend.ask(retryPrompt, call);
58
75
  return parseAndValidate(retryResponse);
59
76
  }
60
77
  }
@@ -0,0 +1,17 @@
1
+ export interface Bridge {
2
+ /** What the runner handed the program when it started it — the bridge secret among it. */
3
+ init: Record<string, any>;
4
+ /** POST one call to the runner and return its result. */
5
+ call(endpoint: string, body: unknown): Promise<any>;
6
+ /**
7
+ * Open a call that lasts until the returned function is called — or until
8
+ * this process ends, however it ends. It has no result; it is the connection
9
+ * itself the runner goes by.
10
+ */
11
+ hold(endpoint: string): () => void;
12
+ }
13
+ /**
14
+ * @param port - the runner's loopback port (TRAMA_PORT)
15
+ * @param initPath - the file the runner wrote for this program (TRAMA_INIT)
16
+ */
17
+ export declare function openBridge(port: string, initPath: string): Bridge;
@@ -0,0 +1,52 @@
1
+ // The program's end of the IPC bridge: how code running inside a program
2
+ // reaches the runner that started it (ipc-server.ts is the other end).
3
+ import { readFileSync } from "fs";
4
+ import { request } from "http";
5
+ /**
6
+ * @param port - the runner's loopback port (TRAMA_PORT)
7
+ * @param initPath - the file the runner wrote for this program (TRAMA_INIT)
8
+ */
9
+ export function openBridge(port, initPath) {
10
+ const init = JSON.parse(readFileSync(initPath, "utf-8"));
11
+ const post = (endpoint, payload) => request({
12
+ host: "127.0.0.1",
13
+ port,
14
+ path: endpoint,
15
+ method: "POST",
16
+ headers: {
17
+ "Content-Type": "application/json",
18
+ "Content-Length": Buffer.byteLength(payload),
19
+ "Authorization": `Bearer ${init.token}`,
20
+ },
21
+ });
22
+ // A call lasts as long as the work behind it — an agent run, or a wait for
23
+ // another program — so this uses node:http, which sets no deadline for the
24
+ // response. (fetch gives up after five minutes without response headers.)
25
+ const call = (endpoint, body) => new Promise((resolve, reject) => {
26
+ const payload = JSON.stringify(body);
27
+ const req = post(endpoint, payload);
28
+ req.on("response", (res) => {
29
+ const chunks = [];
30
+ res.on("data", (chunk) => chunks.push(chunk));
31
+ res.on("error", reject);
32
+ res.on("end", () => {
33
+ const text = Buffer.concat(chunks).toString("utf-8");
34
+ if (res.statusCode !== 200)
35
+ reject(new Error(`trama runtime error: ${text}`));
36
+ else
37
+ resolve(JSON.parse(text).result);
38
+ });
39
+ });
40
+ req.on("error", reject);
41
+ req.end(payload);
42
+ });
43
+ const hold = (endpoint) => {
44
+ const req = post(endpoint, "{}");
45
+ // Nothing to do if the runner is gone or will not have it: there is no clock to hold.
46
+ req.on("error", () => { });
47
+ req.on("response", res => res.resume());
48
+ req.end("{}");
49
+ return () => req.destroy();
50
+ };
51
+ return { init, call, hold };
52
+ }
@@ -1,4 +1,4 @@
1
- import type { ChildProcess } from "child_process";
1
+ import { type ChildProcess } from "child_process";
2
2
  /** A string accumulator that stops growing (and says so) once it passes 10MB. */
3
3
  export declare function cappedBuffer(): {
4
4
  append(text: string): void;
@@ -10,15 +10,48 @@ export declare function cappedBuffer(): {
10
10
  * Signal 0 only probes. Returns false if the group no longer exists.
11
11
  */
12
12
  export declare function signalGroup(pgid: number, signal: NodeJS.Signals | 0): boolean;
13
+ /**
14
+ * Stop process groups for good: SIGTERM now, SIGKILL after the grace period to
15
+ * whichever are still there. Resolves when none is left — so that what follows
16
+ * (merging a directory they were writing to, deleting it) finds them gone.
17
+ */
18
+ export declare function stopGroups(pgids: number[]): Promise<void>;
19
+ /**
20
+ * The same as stopGroups, for a process that is itself on its way out and can
21
+ * neither wait nor keep a timer: synchronous, with the grace period seen
22
+ * through by a small detached process. Once the groups are gone it also
23
+ * removes `dirs` — temp directories they may have been writing to until then.
24
+ */
25
+ export declare function stopGroupsOnExit(pgids: number[], dirs: string[]): void;
26
+ /**
27
+ * A time limit that only runs down while nothing is holding it.
28
+ *
29
+ * A program's timeout is an allowance for its own work. While it waits for a
30
+ * run it started — one that is under a timeout of its own — the clock stops,
31
+ * so that every moment is charged to exactly one of them and a program is
32
+ * never killed for the time something else was entitled to take.
33
+ */
34
+ export interface Allowance {
35
+ /** Start the clock. `onSpent` is called once, if the allowance runs out. */
36
+ start(onSpent: () => void): void;
37
+ /** Stop the clock until the returned function is called. Holds add up: the clock runs only when all are released. */
38
+ hold(): () => void;
39
+ /** Stop for good; `onSpent` will not be called. */
40
+ cancel(): void;
41
+ }
42
+ export declare function createAllowance(ms: number): Allowance;
13
43
  export interface SuperviseOptions {
14
- /** Wall-clock limit in ms. On expiry the child's process group is terminated. */
15
- timeout: number;
44
+ /**
45
+ * Time limit: a number of ms of wall-clock time, or an allowance that its
46
+ * owner may put on hold. On expiry the child's process group is terminated.
47
+ */
48
+ timeout: number | Allowance;
16
49
  /** Receive output as it arrives, in addition to it being collected. */
17
50
  sinks?: {
18
51
  stdout?: (chunk: string) => void;
19
52
  stderr?: (chunk: string) => void;
20
53
  };
21
- /** Aborting this asks the child to stop (same SIGTERM → SIGKILL sequence as a timeout). */
54
+ /** Aborting this asks the child to stop, the same way a timeout does. */
22
55
  stopSignal?: AbortSignal;
23
56
  }
24
57
  export interface ChildExit {
@@ -32,9 +65,9 @@ export interface ChildExit {
32
65
  stopped: boolean;
33
66
  }
34
67
  /**
35
- * Collect a child's output and wait for it to exit, enforcing a wall-clock
36
- * timeout and an optional stop request. Termination is SIGTERM to the child's
37
- * process group, then SIGKILL if it is still alive after a grace period.
68
+ * Collect a child's output and wait for it to exit, enforcing a time limit
69
+ * and an optional stop request. Either one stops the child's whole process
70
+ * group (see stopGroups).
38
71
  * Resolves on exit however it happened; rejects only if the child failed to spawn.
39
72
  */
40
73
  export declare function superviseChild(child: ChildProcess, options: SuperviseOptions): Promise<ChildExit>;
@@ -1,7 +1,15 @@
1
+ import { spawn } from "child_process";
1
2
  import { StringDecoder } from "string_decoder";
2
3
  const MAX_OUTPUT = 10 * 1024 * 1024; // 10 MB
3
- /** How long a child gets to exit after SIGTERM before it is sent SIGKILL. */
4
+ /** How long a process group gets to exit after SIGTERM before it is sent SIGKILL. */
4
5
  const KILL_GRACE_MS = 5000;
6
+ const STOP_POLL_MS = 25;
7
+ /** How long a group is waited for after SIGKILL before it is given up on. */
8
+ const KILL_SETTLE_MS = 1000;
9
+ /** How long a child's output is waited for once the child itself has exited. */
10
+ const DRAIN_MS = 1000;
11
+ /** The longest delay a timer can be given; a longer one fires at once. */
12
+ const MAX_TIMER_MS = 2 ** 31 - 1;
5
13
  /** A string accumulator that stops growing (and says so) once it passes 10MB. */
6
14
  export function cappedBuffer() {
7
15
  let buf = "";
@@ -33,14 +41,165 @@ export function signalGroup(pgid, signal) {
33
41
  return false;
34
42
  }
35
43
  }
44
+ // --- Stopping ---
45
+ //
46
+ // Never SIGKILL first. A process group may hold a runner of its own — a program
47
+ // that coordinates others, a shell command that runs trama — and that runner
48
+ // has started process groups this one cannot see. SIGTERM is its chance to stop
49
+ // them; killed outright, it leaves them running. So a group is asked to stop,
50
+ // and killed only if it is still there when the grace period is over.
51
+ //
52
+ // There are two ways to see that through, depending on whether the process
53
+ // asking will be around to do it: stopGroups (it will) and stopGroupsOnExit
54
+ // (it will not).
55
+ /** Groups this process has asked to stop and is still watching. */
56
+ const stopping = new Map();
57
+ function stopGroup(pgid) {
58
+ // Asked once is enough: to some programs a second SIGTERM means "now".
59
+ const watched = stopping.get(pgid);
60
+ if (watched)
61
+ return watched;
62
+ if (!signalGroup(pgid, "SIGTERM"))
63
+ return Promise.resolve();
64
+ const gone = new Promise((resolve) => {
65
+ let deadline = performance.now() + KILL_GRACE_MS;
66
+ let killed = false;
67
+ const poll = setInterval(() => {
68
+ const alive = signalGroup(pgid, 0);
69
+ if (alive && performance.now() < deadline)
70
+ return;
71
+ if (alive && !killed) {
72
+ // Out of patience. A killed group is gone in a moment; allow it that
73
+ // moment, but do not wait on one that for some reason never goes.
74
+ signalGroup(pgid, "SIGKILL");
75
+ killed = true;
76
+ deadline = performance.now() + KILL_SETTLE_MS;
77
+ return;
78
+ }
79
+ clearInterval(poll);
80
+ stopping.delete(pgid);
81
+ resolve();
82
+ }, STOP_POLL_MS);
83
+ });
84
+ stopping.set(pgid, gone);
85
+ return gone;
86
+ }
87
+ /**
88
+ * Stop process groups for good: SIGTERM now, SIGKILL after the grace period to
89
+ * whichever are still there. Resolves when none is left — so that what follows
90
+ * (merging a directory they were writing to, deleting it) finds them gone.
91
+ */
92
+ export async function stopGroups(pgids) {
93
+ await Promise.all(pgids.map(stopGroup));
94
+ }
95
+ // What stopGroupsOnExit leaves behind to finish the job: a process of its own
96
+ // that waits for the groups to go, kills whichever are still there when the
97
+ // grace period is over, and then deletes the directories they were using.
98
+ const REAPER = `
99
+ const { rmSync } = require("fs");
100
+ const { grace, settle, poll, groups, dirs } = JSON.parse(process.argv[1]);
101
+ let left = groups;
102
+ const alive = (pgid) => { try { process.kill(-pgid, 0); return true; } catch { return false; } };
103
+ const finish = () => {
104
+ for (const dir of dirs) { try { rmSync(dir, { recursive: true, force: true }); } catch {} }
105
+ process.exit(0);
106
+ };
107
+ let deadline = performance.now() + grace;
108
+ let killed = false;
109
+ setInterval(() => {
110
+ // A group seen gone is never signalled again: its id may belong to another by now.
111
+ left = left.filter(alive);
112
+ if (left.length === 0) return finish();
113
+ if (performance.now() < deadline) return;
114
+ if (killed) return finish();
115
+ for (const pgid of left) { try { process.kill(-pgid, "SIGKILL"); } catch {} }
116
+ killed = true;
117
+ deadline = performance.now() + settle;
118
+ }, poll);
119
+ `;
120
+ /**
121
+ * The same as stopGroups, for a process that is itself on its way out and can
122
+ * neither wait nor keep a timer: synchronous, with the grace period seen
123
+ * through by a small detached process. Once the groups are gone it also
124
+ * removes `dirs` — temp directories they may have been writing to until then.
125
+ */
126
+ export function stopGroupsOnExit(pgids, dirs) {
127
+ // Groups already asked to stop are not asked again, but still need seeing through.
128
+ const groups = pgids.filter(pgid => stopping.has(pgid) ? signalGroup(pgid, 0) : signalGroup(pgid, "SIGTERM"));
129
+ if (groups.length === 0)
130
+ return;
131
+ // Without a reaper, do not leave them to chance.
132
+ const killNow = () => { for (const pgid of groups)
133
+ signalGroup(pgid, "SIGKILL"); };
134
+ try {
135
+ const job = JSON.stringify({ grace: KILL_GRACE_MS, settle: KILL_SETTLE_MS, poll: STOP_POLL_MS, groups, dirs });
136
+ const reaper = spawn(process.execPath, ["-e", REAPER, job], { detached: true, stdio: "ignore" });
137
+ // A spawn that fails says so later, in an event this process will not be
138
+ // around for — but it has no pid from the start.
139
+ if (reaper.pid === undefined)
140
+ killNow();
141
+ reaper.on("error", killNow);
142
+ reaper.unref();
143
+ }
144
+ catch {
145
+ killNow();
146
+ }
147
+ }
148
+ export function createAllowance(ms) {
149
+ let remaining = ms;
150
+ let holds = 0;
151
+ let onSpent = null;
152
+ // Set while the clock is running: the timer, and when it was started. Time
153
+ // is read from a clock that only moves forward — the wall clock can be set.
154
+ let running = null;
155
+ const pause = () => {
156
+ if (!running)
157
+ return;
158
+ clearTimeout(running.timer);
159
+ remaining = Math.max(0, remaining - (performance.now() - running.since));
160
+ running = null;
161
+ };
162
+ const run = () => {
163
+ if (!onSpent || holds > 0 || running)
164
+ return;
165
+ running = {
166
+ since: performance.now(),
167
+ timer: setTimeout(() => {
168
+ pause();
169
+ if (remaining > 0)
170
+ return run(); // an allowance longer than one timer can measure
171
+ const spent = onSpent;
172
+ onSpent = null;
173
+ spent?.();
174
+ }, Math.min(remaining, MAX_TIMER_MS)),
175
+ };
176
+ };
177
+ return {
178
+ start(fn) { onSpent = fn; run(); },
179
+ hold() {
180
+ holds += 1;
181
+ pause();
182
+ let released = false;
183
+ return () => {
184
+ if (released)
185
+ return;
186
+ released = true;
187
+ holds -= 1;
188
+ run();
189
+ };
190
+ },
191
+ cancel() { pause(); onSpent = null; },
192
+ };
193
+ }
36
194
  /**
37
- * Collect a child's output and wait for it to exit, enforcing a wall-clock
38
- * timeout and an optional stop request. Termination is SIGTERM to the child's
39
- * process group, then SIGKILL if it is still alive after a grace period.
195
+ * Collect a child's output and wait for it to exit, enforcing a time limit
196
+ * and an optional stop request. Either one stops the child's whole process
197
+ * group (see stopGroups).
40
198
  * Resolves on exit however it happened; rejects only if the child failed to spawn.
41
199
  */
42
200
  export function superviseChild(child, options) {
43
- const { timeout, sinks, stopSignal } = options;
201
+ const { sinks, stopSignal } = options;
202
+ const allowance = typeof options.timeout === "number" ? createAllowance(options.timeout) : options.timeout;
44
203
  return new Promise((resolve, reject) => {
45
204
  const out = cappedBuffer();
46
205
  const err = cappedBuffer();
@@ -49,7 +208,6 @@ export function superviseChild(child, options) {
49
208
  let timedOut = false;
50
209
  let stopped = false;
51
210
  let exited = false;
52
- let killFallbackTimer = null;
53
211
  const emitOut = (text) => { if (text) {
54
212
  out.append(text);
55
213
  sinks?.stdout?.(text);
@@ -58,20 +216,10 @@ export function superviseChild(child, options) {
58
216
  err.append(text);
59
217
  sinks?.stderr?.(text);
60
218
  } };
61
- const kill = (sig) => {
62
- if (child.pid)
63
- signalGroup(child.pid, sig);
64
- else
65
- child.kill(sig);
66
- };
67
- const terminate = () => {
68
- kill("SIGTERM");
69
- if (killFallbackTimer)
70
- clearTimeout(killFallbackTimer);
71
- killFallbackTimer = setTimeout(() => { if (!exited)
72
- kill("SIGKILL"); }, KILL_GRACE_MS);
73
- killFallbackTimer.unref();
74
- };
219
+ let drainTimer = null;
220
+ // A child that failed to spawn has no pid, and nothing to stop.
221
+ const terminate = () => { if (child.pid)
222
+ void stopGroups([child.pid]); };
75
223
  const onStopRequest = () => {
76
224
  if (exited || stopped || timedOut)
77
225
  return;
@@ -79,16 +227,16 @@ export function superviseChild(child, options) {
79
227
  terminate();
80
228
  };
81
229
  stopSignal?.addEventListener("abort", onStopRequest, { once: true });
82
- const timer = setTimeout(() => {
230
+ allowance.start(() => {
83
231
  if (exited)
84
232
  return;
85
233
  timedOut = true;
86
234
  terminate();
87
- }, timeout);
235
+ });
88
236
  const cleanup = () => {
89
- clearTimeout(timer);
90
- if (killFallbackTimer)
91
- clearTimeout(killFallbackTimer);
237
+ allowance.cancel();
238
+ if (drainTimer)
239
+ clearTimeout(drainTimer);
92
240
  stopSignal?.removeEventListener("abort", onStopRequest);
93
241
  };
94
242
  child.stdout?.on("data", (chunk) => emitOut(outDecoder.write(chunk)));
@@ -97,6 +245,13 @@ export function superviseChild(child, options) {
97
245
  cleanup();
98
246
  reject(spawnError);
99
247
  });
248
+ // The output pipes normally close right behind the exit. They stay open
249
+ // only if something else inherited them — a process the child detached —
250
+ // and what that writes is not the child's output. Stop waiting for it:
251
+ // otherwise such a process keeps the run from ever ending, timeout or not.
252
+ child.on("exit", () => {
253
+ drainTimer = setTimeout(() => { child.stdout?.destroy(); child.stderr?.destroy(); }, DRAIN_MS);
254
+ });
100
255
  child.on("close", (code, signal) => {
101
256
  exited = true;
102
257
  cleanup();
package/dist/client.js CHANGED
@@ -1,8 +1,7 @@
1
1
  // @trama-dev/runtime client — this is what program.ts imports.
2
2
  // A thin wrapper that forwards every call to the runner's IPC server
3
3
  // (ipc-server.ts), which does the real work.
4
- import { readFileSync } from "fs";
5
- import { request } from "http";
4
+ import { openBridge } from "./bridge-client.js";
6
5
  import { assertSerializable } from "./serializable.js";
7
6
  const PORT = process.env.TRAMA_PORT;
8
7
  if (!PORT) {
@@ -14,43 +13,7 @@ if (!INIT_PATH) {
14
13
  throw new Error("@trama-dev/runtime: TRAMA_INIT env var missing. " +
15
14
  "This program must be launched by the trama runner.");
16
15
  }
17
- const initData = JSON.parse(readFileSync(INIT_PATH, "utf-8"));
18
- /**
19
- * POST one call to the runner and return its result.
20
- *
21
- * A call lasts as long as the work behind it — an agent run, or a wait for
22
- * another program — so this uses node:http, which sets no deadline for the
23
- * response. (fetch gives up after five minutes without response headers.)
24
- */
25
- function call(endpoint, body) {
26
- return new Promise((resolve, reject) => {
27
- const payload = JSON.stringify(body);
28
- const req = request({
29
- host: "127.0.0.1",
30
- port: PORT,
31
- path: endpoint,
32
- method: "POST",
33
- headers: {
34
- "Content-Type": "application/json",
35
- "Content-Length": Buffer.byteLength(payload),
36
- "Authorization": `Bearer ${initData.token}`,
37
- },
38
- }, (res) => {
39
- const chunks = [];
40
- res.on("data", (chunk) => chunks.push(chunk));
41
- res.on("error", reject);
42
- res.on("end", () => {
43
- const text = Buffer.concat(chunks).toString("utf-8");
44
- if (res.statusCode !== 200)
45
- reject(new Error(`trama runtime error: ${text}`));
46
- else
47
- resolve(JSON.parse(text).result);
48
- });
49
- });
50
- req.on("error", reject);
51
- req.end(payload);
52
- });
53
- }
16
+ const { init: initData, call } = openBridge(PORT, INIT_PATH);
54
17
  /** Log payloads are best-effort: anything that can't be sent as JSON is replaced by its string form. */
55
18
  function sendable(data) {
56
19
  try {
package/dist/index.js CHANGED
@@ -2,8 +2,9 @@
2
2
  import { readFileSync, writeFileSync, mkdirSync, readdirSync, existsSync, statSync, rmSync } from "fs";
3
3
  import { join } from "path";
4
4
  import { homedir } from "os";
5
- import { PiAdapter, PI_VERSION, stripCodeFences } from "./pi-adapter.js";
6
- import { loadConfig, loadProjectConfig, loadState, validateProgram, installValidatedProgram, withTempDir, ensureProjectScaffold, RUNTIME_TYPES, } from "./runner.js";
5
+ import { PI_VERSION } from "./pi-adapter.js";
6
+ import { stripCodeFences } from "./agent.js";
7
+ import { loadConfig, loadProjectConfig, loadState, createBackend, validateProgram, installValidatedProgram, withTempDir, ensureProjectScaffold, RUNTIME_TYPES, } from "./runner.js";
7
8
  import { guardPath } from "./path-guard.js";
8
9
  export { runProgram } from "./runner.js";
9
10
  export { createWorkspace } from "./workspace.js";
@@ -113,9 +114,9 @@ export function resolveProject(name) {
113
114
  return dir;
114
115
  }
115
116
  // --- Helpers ---
116
- /** Run an LLM instruction in an isolated temp cwd so pi-coding-agent tools can't write into the real project. */
117
- async function isolatedAsk(adapter, prompt, options) {
118
- return withTempDir("trama-gen-", (dir) => adapter.withCwd(dir).ask(prompt, options));
117
+ /** Ask in an empty throwaway directory, so the agent's tools cannot write into the real project. */
118
+ async function isolatedAsk(backend, prompt, system) {
119
+ return withTempDir("trama-gen-", (cwd) => backend.ask(prompt, { cwd, system }));
119
120
  }
120
121
  const validationOptions = (config) => ({
121
122
  timeout: config.defaultTimeout,
@@ -144,15 +145,15 @@ export async function createProject(name, prompt, options) {
144
145
  provider: config.provider,
145
146
  };
146
147
  writeFileSync(join(projectDir, "meta.json"), JSON.stringify(meta, null, 2));
147
- const adapter = new PiAdapter(config, projectDir);
148
+ const backend = createBackend(config);
148
149
  console.log(`Generating program for "${name}"...`);
149
- const candidate = stripCodeFences(await isolatedAsk(adapter, `${prompt}\n\nOutput ONLY the TypeScript program. No markdown fences. No explanation.`, { system: getSystemPrompt() }));
150
+ const candidate = stripCodeFences(await isolatedAsk(backend, `${prompt}\n\nOutput ONLY the TypeScript program. No markdown fences. No explanation.`, getSystemPrompt()));
150
151
  // From here on the project is kept even if validation fails, so the
151
152
  // generated program can be inspected and fixed by hand.
152
153
  writeFileSync(join(projectDir, "program.ts"), candidate);
153
154
  keepProjectOnFailure = true;
154
155
  console.log("Validating program...");
155
- const validated = await validateProgram(projectDir, adapter, candidate, validationOptions(config));
156
+ const validated = await validateProgram(projectDir, backend, candidate, validationOptions(config));
156
157
  installValidatedProgram(projectDir, validated, "create", prompt);
157
158
  console.log(`Created ${name}. Run with: trama run ${name}`);
158
159
  }
@@ -172,7 +173,7 @@ export async function updateProject(name, prompt) {
172
173
  const state = loadState(projectDir);
173
174
  const meta = JSON.parse(readFileSync(guardPath(projectDir, "meta.json"), "utf-8"));
174
175
  const config = loadProjectConfig(projectDir);
175
- const adapter = new PiAdapter(config, projectDir);
176
+ const backend = createBackend(config);
176
177
  const systemPrompt = getSystemPrompt() +
177
178
  `\n\nOriginal prompt: ${meta.input.prompt}` +
178
179
  `\n\nCurrent program.ts:\n${originalSource}` +
@@ -182,9 +183,9 @@ export async function updateProject(name, prompt) {
182
183
  // nothing to undo.
183
184
  try {
184
185
  console.log(`Updating "${name}"...`);
185
- const candidate = stripCodeFences(await isolatedAsk(adapter, `${prompt}\n\nOutput the complete updated program.ts. No partial patches. No markdown fences. No explanation.`, { system: systemPrompt }));
186
+ const candidate = stripCodeFences(await isolatedAsk(backend, `${prompt}\n\nOutput the complete updated program.ts. No partial patches. No markdown fences. No explanation.`, systemPrompt));
186
187
  console.log("Validating updated program...");
187
- const validated = await validateProgram(projectDir, adapter, candidate, validationOptions(config));
188
+ const validated = await validateProgram(projectDir, backend, candidate, validationOptions(config));
188
189
  try {
189
190
  installValidatedProgram(projectDir, validated, "update", prompt);
190
191
  }
@@ -15,6 +15,8 @@ export interface IpcBackends {
15
15
  workspace: Workspace | null;
16
16
  /** Called once ctx.done() or ctx.yield() has been persisted for this run. */
17
17
  onTerminalSignal(result: ProgramResult): void;
18
+ /** Stop the program's clock until the returned function is called (see Allowance). */
19
+ holdClock(): () => void;
18
20
  }
19
21
  export declare function createIPCServer(backends: IpcBackends): Server;
20
22
  /** Start listening on an ephemeral loopback port and return it. */