@trama-dev/runtime 0.3.0 → 0.3.1

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.
@@ -16,3 +16,9 @@ export interface AgentBackend {
16
16
  */
17
17
  ask(prompt: string, call: AgentCall): Promise<string>;
18
18
  }
19
+ /**
20
+ * Hold a piece of work to the promise above: reject as soon as `signal` is
21
+ * aborted, whether or not the work itself notices. What the work goes on to do
22
+ * after that is no longer waited for.
23
+ */
24
+ export declare function rejectOnAbort<T>(work: Promise<T>, signal?: AbortSignal): Promise<T>;
@@ -6,4 +6,24 @@
6
6
  // request; what to ask for, and what to make of the reply, is decided by the
7
7
  // caller. Nothing outside the backend's own file knows which agent, harness or
8
8
  // model is behind it.
9
- export {};
9
+ /**
10
+ * Hold a piece of work to the promise above: reject as soon as `signal` is
11
+ * aborted, whether or not the work itself notices. What the work goes on to do
12
+ * after that is no longer waited for.
13
+ */
14
+ export function rejectOnAbort(work, signal) {
15
+ if (!signal)
16
+ return work;
17
+ return new Promise((resolve, reject) => {
18
+ const onAbort = () => reject(new Error("Aborted"));
19
+ if (signal.aborted)
20
+ onAbort();
21
+ else
22
+ signal.addEventListener("abort", onAbort, { once: true });
23
+ const settle = (pass) => (value) => {
24
+ signal.removeEventListener("abort", onAbort);
25
+ pass(value);
26
+ };
27
+ work.then(settle(resolve), settle(reject));
28
+ });
29
+ }
@@ -1,17 +1,22 @@
1
+ import type { Workspace } from "./types.js";
1
2
  export interface Bridge {
2
3
  /** What the runner handed the program when it started it — the bridge secret among it. */
3
4
  init: Record<string, any>;
4
5
  /** POST one call to the runner and return its result. */
5
6
  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
7
  }
13
8
  /**
14
9
  * @param port - the runner's loopback port (TRAMA_PORT)
15
10
  * @param initPath - the file the runner wrote for this program (TRAMA_INIT)
16
11
  */
17
12
  export declare function openBridge(port: string, initPath: string): Bridge;
13
+ /**
14
+ * The bridge to the runner that started this process as a program — or null
15
+ * when this process is not a program, and so is itself where runs happen.
16
+ */
17
+ export declare function parentBridge(): Bridge | null;
18
+ /**
19
+ * A workspace reached over a bridge: the directory `dir`, or — without one —
20
+ * the workspace of the session the calling program is running in.
21
+ */
22
+ export declare function remoteWorkspace(call: Bridge["call"], dir?: string): Workspace;
@@ -8,24 +8,22 @@ import { request } from "http";
8
8
  */
9
9
  export function openBridge(port, initPath) {
10
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.)
11
+ // A call lasts as long as the work behind it — an agent run, or the whole
12
+ // run of another program — so this uses node:http, which sets no deadline
13
+ // for the response. (fetch gives up after five minutes without response headers.)
25
14
  const call = (endpoint, body) => new Promise((resolve, reject) => {
26
15
  const payload = JSON.stringify(body);
27
- const req = post(endpoint, payload);
28
- req.on("response", (res) => {
16
+ const req = request({
17
+ host: "127.0.0.1",
18
+ port,
19
+ path: endpoint,
20
+ method: "POST",
21
+ headers: {
22
+ "Content-Type": "application/json",
23
+ "Content-Length": Buffer.byteLength(payload),
24
+ "Authorization": `Bearer ${init.token}`,
25
+ },
26
+ }, (res) => {
29
27
  const chunks = [];
30
28
  res.on("data", (chunk) => chunks.push(chunk));
31
29
  res.on("error", reject);
@@ -40,13 +38,34 @@ export function openBridge(port, initPath) {
40
38
  req.on("error", reject);
41
39
  req.end(payload);
42
40
  });
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();
41
+ return { init, call };
42
+ }
43
+ let parent;
44
+ /**
45
+ * The bridge to the runner that started this process as a program — or null
46
+ * when this process is not a program, and so is itself where runs happen.
47
+ */
48
+ export function parentBridge() {
49
+ if (parent === undefined) {
50
+ const { TRAMA_PORT: port, TRAMA_INIT: initPath } = process.env;
51
+ try {
52
+ parent = port && initPath ? openBridge(port, initPath) : null;
53
+ }
54
+ catch {
55
+ parent = null; // a stale environment: there is no runner to ask
56
+ }
57
+ }
58
+ return parent;
59
+ }
60
+ /**
61
+ * A workspace reached over a bridge: the directory `dir`, or — without one —
62
+ * the workspace of the session the calling program is running in.
63
+ */
64
+ export function remoteWorkspace(call, dir) {
65
+ return {
66
+ read: (path) => call("/workspace/read", { dir, path }),
67
+ write: (path, content) => call("/workspace/write", { dir, path, content }),
68
+ list: (pattern) => call("/workspace/list", { dir, pattern }),
69
+ observe: (pattern, options) => call("/workspace/observe", { dir, pattern, ...options }),
50
70
  };
51
- return { init, call, hold };
52
71
  }
@@ -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,19 +10,19 @@ 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
+ /** The timing of a stop, shared with the watchdog. */
14
+ export declare const STOP_TIMINGS: {
15
+ grace: number;
16
+ settle: number;
17
+ poll: number;
18
+ };
19
+ export declare function onGroupAskedToStop(listener: (pgid: number) => void): void;
13
20
  /**
14
21
  * Stop process groups for good: SIGTERM now, SIGKILL after the grace period to
15
22
  * whichever are still there. Resolves when none is left — so that what follows
16
23
  * (merging a directory they were writing to, deleting it) finds them gone.
17
24
  */
18
25
  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
26
  /**
27
27
  * A time limit that only runs down while nothing is holding it.
28
28
  *
@@ -1,4 +1,3 @@
1
- import { spawn } from "child_process";
2
1
  import { StringDecoder } from "string_decoder";
3
2
  const MAX_OUTPUT = 10 * 1024 * 1024; // 10 MB
4
3
  /** How long a process group gets to exit after SIGTERM before it is sent SIGKILL. */
@@ -43,17 +42,22 @@ export function signalGroup(pgid, signal) {
43
42
  }
44
43
  // --- Stopping ---
45
44
  //
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.
45
+ // Never SIGKILL first. A group gets the chance to end properly — a program to
46
+ // close what it opened, a `trama` command to stop its own run and report it.
47
+ // Killed outright, nothing in it gets to finish anything. So a group is asked
48
+ // to stop, and killed only if it is still there when the grace period is over.
51
49
  //
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).
50
+ // stopGroups does that for a runner that is there to see it through. When the
51
+ // runner itself is gone, its watchdog does the same (see watchdog.ts).
52
+ /** The timing of a stop, shared with the watchdog. */
53
+ export const STOP_TIMINGS = { grace: KILL_GRACE_MS, settle: KILL_SETTLE_MS, poll: STOP_POLL_MS };
55
54
  /** Groups this process has asked to stop and is still watching. */
56
55
  const stopping = new Map();
56
+ /** Called with each group as it is asked to stop — for the watchdog, which must not ask it again. */
57
+ let onAsked = () => { };
58
+ export function onGroupAskedToStop(listener) {
59
+ onAsked = listener;
60
+ }
57
61
  function stopGroup(pgid) {
58
62
  // Asked once is enough: to some programs a second SIGTERM means "now".
59
63
  const watched = stopping.get(pgid);
@@ -61,6 +65,7 @@ function stopGroup(pgid) {
61
65
  return watched;
62
66
  if (!signalGroup(pgid, "SIGTERM"))
63
67
  return Promise.resolve();
68
+ onAsked(pgid);
64
69
  const gone = new Promise((resolve) => {
65
70
  let deadline = performance.now() + KILL_GRACE_MS;
66
71
  let killed = false;
@@ -92,59 +97,6 @@ function stopGroup(pgid) {
92
97
  export async function stopGroups(pgids) {
93
98
  await Promise.all(pgids.map(stopGroup));
94
99
  }
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
100
  export function createAllowance(ms) {
149
101
  let remaining = ms;
150
102
  let holds = 0;
package/dist/client.d.ts CHANGED
@@ -2,4 +2,5 @@ import type { Ctx, Agent, Tools, Workspace } from "./types.js";
2
2
  export declare const ctx: Ctx;
3
3
  export declare const agent: Agent;
4
4
  export declare const tools: Tools;
5
+ /** workspace.* exists only inside a session — everywhere else it fails clearly, without a round trip. */
5
6
  export declare const workspace: Workspace;
package/dist/client.js CHANGED
@@ -1,7 +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 { openBridge } from "./bridge-client.js";
4
+ import { openBridge, remoteWorkspace } from "./bridge-client.js";
5
5
  import { assertSerializable } from "./serializable.js";
6
6
  const PORT = process.env.TRAMA_PORT;
7
7
  if (!PORT) {
@@ -68,15 +68,9 @@ export const tools = {
68
68
  fetch: (url, opts) => call("/tools/fetch", { url, ...opts }),
69
69
  };
70
70
  /** workspace.* exists only inside a session — everywhere else it fails clearly, without a round trip. */
71
- async function workspaceCall(endpoint, body) {
71
+ export const workspace = remoteWorkspace((endpoint, body) => {
72
72
  if (!initData.inSession) {
73
- throw new Error("workspace is only available when running in a session");
73
+ return Promise.reject(new Error("workspace is only available when running in a session"));
74
74
  }
75
75
  return call(endpoint, body);
76
- }
77
- export const workspace = {
78
- read: (path) => workspaceCall("/workspace/read", { path }),
79
- write: (path, content) => workspaceCall("/workspace/write", { path, content }),
80
- list: (pattern) => workspaceCall("/workspace/list", { pattern }),
81
- observe: (pattern, options) => workspaceCall("/workspace/observe", { pattern, ...options }),
82
- };
76
+ });
package/dist/context.d.ts CHANGED
@@ -14,4 +14,6 @@ export declare function createContext(projectDir: string, initialState: Record<s
14
14
  maxIterations?: number;
15
15
  argsOverride?: Record<string, unknown>;
16
16
  onReady?: (data?: Record<string, unknown>) => void;
17
+ /** Where the run's log lines are shown as they are written. Defaults to the console. */
18
+ print?: (line: string) => void;
17
19
  }): Ctx;
package/dist/context.js CHANGED
@@ -51,7 +51,7 @@ export function createContext(projectDir, initialState, options) {
51
51
  }
52
52
  const entry = { ts: Date.now(), message, data: safeData };
53
53
  appendFileSync(logsPath, JSON.stringify(entry) + "\n");
54
- console.log(`[trama] ${message}`);
54
+ (options?.print ?? console.log)(`[trama] ${message}`);
55
55
  },
56
56
  async ready(data) {
57
57
  if (readyCalled)
package/dist/index.d.ts CHANGED
@@ -1,7 +1,11 @@
1
- export { runProgram } from "./runner.js";
2
- export { createWorkspace } from "./workspace.js";
3
1
  export type { ProgramResult, RunOptions } from "./runner-types.js";
2
+ import type { ProgramResult, RunOptions } from "./runner-types.js";
4
3
  export type { Workspace, ObserveResult } from "./types.js";
4
+ import type { Workspace } from "./types.js";
5
+ /** Run a project to an outcome: done, yielded, or failed. */
6
+ export declare function runProgram(options: RunOptions): Promise<ProgramResult>;
7
+ /** The shared workspace in a directory, created if it does not exist: read, write, list, observe. */
8
+ export declare function createWorkspace(dir: string): Workspace;
5
9
  export declare function validateProjectName(name: string): void;
6
10
  export declare function resolveProject(name: string): string;
7
11
  export declare function createProject(name: string, prompt: string, options?: {
package/dist/index.js CHANGED
@@ -1,13 +1,58 @@
1
1
  // @trama-dev/runtime runner surface — exported via "@trama-dev/runtime/runner"
2
+ import { randomUUID } from "crypto";
2
3
  import { readFileSync, writeFileSync, mkdirSync, readdirSync, existsSync, statSync, rmSync } from "fs";
3
- import { join } from "path";
4
+ import { join, resolve } from "path";
4
5
  import { homedir } from "os";
5
- import { PI_VERSION } from "./pi-adapter.js";
6
+ import { piVersion } from "./pi-adapter.js";
6
7
  import { stripCodeFences } from "./agent.js";
7
- import { loadConfig, loadProjectConfig, loadState, createBackend, validateProgram, installValidatedProgram, withTempDir, ensureProjectScaffold, RUNTIME_TYPES, } from "./runner.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";
8
11
  import { guardPath } from "./path-guard.js";
9
- export { runProgram } from "./runner.js";
10
- export { createWorkspace } from "./workspace.js";
12
+ // --- Running a project, and reaching a workspace ---
13
+ //
14
+ // A program never runs another program: it asks its runner to. So these two do
15
+ // their work in this process only when this process is not itself a program.
16
+ // Inside one they are calls on the bridge, carried out by the one runner that
17
+ // owns every run in the tree — which is how it can time them, stop them, and
18
+ // see them.
19
+ /** Run a project to an outcome: done, yielded, or failed. */
20
+ export async function runProgram(options) {
21
+ const bridge = parentBridge();
22
+ if (!bridge)
23
+ return runHere(options);
24
+ // A signal cannot cross the bridge, but what it says can: the runner is told
25
+ // to stop the run, and this call still waits for the run to be over — the
26
+ // same as outside a program.
27
+ const { signal, ...request } = options;
28
+ const id = randomUUID();
29
+ const stop = () => { bridge.call("/run/stop", { id }).catch(() => { }); };
30
+ if (signal?.aborted)
31
+ stop();
32
+ else
33
+ signal?.addEventListener("abort", stop, { once: true });
34
+ try {
35
+ return await bridge.call("/run/program", {
36
+ ...request,
37
+ id,
38
+ // The runner does not share this program's working directory.
39
+ projectDir: resolve(request.projectDir),
40
+ workspaceDir: request.workspaceDir && resolve(request.workspaceDir),
41
+ });
42
+ }
43
+ finally {
44
+ signal?.removeEventListener("abort", stop);
45
+ }
46
+ }
47
+ /** The shared workspace in a directory, created if it does not exist: read, write, list, observe. */
48
+ export function createWorkspace(dir) {
49
+ const bridge = parentBridge();
50
+ if (!bridge)
51
+ return workspaceHere(dir);
52
+ const absolute = resolve(dir);
53
+ mkdirSync(absolute, { recursive: true }); // it exists from here on, as it does outside a program
54
+ return remoteWorkspace(bridge.call, absolute);
55
+ }
11
56
  // --- Example programs (included in system prompt during create/update) ---
12
57
  const EXAMPLE_PROGRAMS = `// Example A: Simple — one-shot action, no LLM needed.
13
58
  import { ctx, tools } from "@trama-dev/runtime";
@@ -140,7 +185,7 @@ export async function createProject(name, prompt, options) {
140
185
  const meta = {
141
186
  input: { prompt, args: options?.args ?? {} },
142
187
  createdAt: new Date().toISOString(),
143
- piVersion: PI_VERSION,
188
+ piVersion: await piVersion(),
144
189
  model: config.model,
145
190
  provider: config.provider,
146
191
  };
@@ -1,6 +1,6 @@
1
1
  import { type Server } from "http";
2
2
  import type { Ctx, Agent, Tools, Workspace } from "./types.js";
3
- import type { ProgramResult } from "./runner-types.js";
3
+ import type { ProgramResult, RunRequest } from "./runner-types.js";
4
4
  export interface IpcBackends {
5
5
  /**
6
6
  * The secret only this run's program knows. Every request must present it:
@@ -11,12 +11,14 @@ export interface IpcBackends {
11
11
  ctx: Ctx;
12
12
  agent: Agent;
13
13
  tools: Tools;
14
- /** Null when the program is not running in a session. */
14
+ /** The workspace of the session the program is running in — null when it is in none. */
15
15
  workspace: Workspace | null;
16
+ /** A workspace by directory, for a program that created a session rather than joined one. */
17
+ workspaceAt(dir: string): Workspace;
18
+ /** Run another project on the program's behalf, until it ends or `stop` says to stop it. */
19
+ run(request: RunRequest, stop: AbortSignal): Promise<ProgramResult>;
16
20
  /** Called once ctx.done() or ctx.yield() has been persisted for this run. */
17
21
  onTerminalSignal(result: ProgramResult): void;
18
- /** Stop the program's clock until the returned function is called (see Allowance). */
19
- holdClock(): () => void;
20
22
  }
21
23
  export declare function createIPCServer(backends: IpcBackends): Server;
22
24
  /** Start listening on an ephemeral loopback port and return it. */
@@ -28,13 +28,23 @@ function isAuthorized(header, token) {
28
28
  const actual = Buffer.from(header ?? "");
29
29
  return actual.length === expected.length && timingSafeEqual(actual, expected);
30
30
  }
31
- function buildRoutes({ ctx, agent, tools, workspace, onTerminalSignal, holdClock }) {
31
+ function buildRoutes({ ctx, agent, tools, workspace, workspaceAt, run, onTerminalSignal }) {
32
32
  /** The program owns ctx.state; each persisting call hands over its current copy. */
33
33
  const adoptState = (state) => {
34
34
  assertSerializable(state, "ctx.state");
35
35
  ctx.state = state;
36
36
  };
37
- const inSession = () => {
37
+ /** Runs the program has asked for and that have not ended, by the id it gave each. */
38
+ const runsAskedFor = new Map();
39
+ /** Ids the program asked to stop before their run was seen here: such a run starts stopped. */
40
+ const stoppedAhead = new Set();
41
+ /** The workspace a call is about: the directory it names, or else the one this run was started with. */
42
+ const workspaceOf = (body) => {
43
+ if (body.dir !== undefined) {
44
+ if (typeof body.dir !== "string" || body.dir === "")
45
+ throw new BadRequest("Invalid field: dir (expected a directory path)");
46
+ return workspaceAt(body.dir);
47
+ }
38
48
  if (!workspace)
39
49
  throw new BadRequest("Workspace is only available when running in a session");
40
50
  return workspace;
@@ -86,27 +96,56 @@ function buildRoutes({ ctx, agent, tools, workspace, onTerminalSignal, holdClock
86
96
  onTerminalSignal({ status: "yielded", reason: b.reason });
87
97
  },
88
98
  },
89
- // A run the program starts — a session participant — is under a timeout
90
- // of its own, and the program's clock stops while it lasts (see
91
- // holdParentClock). The hold is the connection: it ends when the caller
92
- // closes it, and cannot outlast a caller that dies without doing so.
93
- "/clock/hold": {
94
- fields: {},
95
- handle: async (_body, connectionClosed) => {
96
- const release = holdClock();
97
- await connectionClosed;
98
- release();
99
+ // A program never runs another program: it asks its runner to. The call
100
+ // lasts as long as the run does, repairs included.
101
+ "/run/program": {
102
+ fields: { projectDir: "string", args: "optional object" },
103
+ handle: async (b, connectionClosed) => {
104
+ const stop = new AbortController();
105
+ // A caller that is gone — its process died, or it gave up — no longer wants the run.
106
+ void connectionClosed.then(() => stop.abort());
107
+ const id = typeof b.id === "string" ? b.id : undefined;
108
+ if (id && stoppedAhead.delete(id))
109
+ stop.abort();
110
+ if (id)
111
+ runsAskedFor.set(id, stop);
112
+ try {
113
+ return await run({
114
+ projectDir: b.projectDir,
115
+ args: b.args,
116
+ timeout: b.timeout,
117
+ maxRepairAttempts: b.maxRepairAttempts,
118
+ workspaceDir: b.workspaceDir,
119
+ label: b.label,
120
+ }, stop.signal);
121
+ }
122
+ finally {
123
+ if (id)
124
+ runsAskedFor.delete(id);
125
+ }
126
+ },
127
+ },
128
+ // Stop a run asked for above. The call that asked for it still gets its
129
+ // answer — a failed run — once the run is over.
130
+ "/run/stop": {
131
+ fields: { id: "string" },
132
+ handle: b => {
133
+ const asked = runsAskedFor.get(b.id);
134
+ if (asked)
135
+ asked.abort();
136
+ else
137
+ stoppedAhead.add(b.id);
99
138
  },
100
139
  },
101
- "/workspace/read": { fields: { path: "string" }, handle: b => inSession().read(b.path) },
140
+ "/workspace/read": { fields: { path: "string" }, handle: b => workspaceOf(b).read(b.path) },
102
141
  "/workspace/write": {
103
142
  fields: { path: "string", content: "string" },
104
- handle: b => inSession().write(b.path, b.content),
143
+ handle: b => workspaceOf(b).write(b.path, b.content),
105
144
  },
106
- "/workspace/list": { fields: { pattern: "string" }, handle: b => inSession().list(b.pattern) },
145
+ "/workspace/list": { fields: { pattern: "string" }, handle: b => workspaceOf(b).list(b.pattern) },
107
146
  "/workspace/observe": {
108
147
  fields: { pattern: "string" },
109
- handle: b => inSession().observe(b.pattern, { expect: b.expect, timeout: b.timeout }),
148
+ handle: b => workspaceOf(b).observe(b.pattern, { expect: b.expect, timeout: b.timeout }),
110
149
  },
111
150
  };
112
151
  }
@@ -1,7 +1,7 @@
1
- import type { AgentBackend, AgentCall } from "./agent-backend.js";
1
+ import { type AgentBackend, type AgentCall } from "./agent-backend.js";
2
2
  import type { ModelConfig } from "./runner-types.js";
3
3
  /** The pi version this runtime is built against (recorded in each project's meta.json). */
4
- export { VERSION as PI_VERSION } from "@earendil-works/pi-coding-agent";
4
+ export declare const piVersion: () => Promise<string>;
5
5
  /** The pi coding agent, run in-process: a fresh in-memory session for every call. */
6
6
  export declare class PiAdapter implements AgentBackend {
7
7
  private config;
@@ -1,6 +1,12 @@
1
- import { createAgentSession, SessionManager, DefaultResourceLoader, ModelRuntime, getAgentDir, } from "@earendil-works/pi-coding-agent";
1
+ import { rejectOnAbort } from "./agent-backend.js";
2
+ /**
3
+ * pi is loaded when it is first needed, not when this file is: it is most of
4
+ * what the runtime weighs, and listing projects, reading logs, or running a
5
+ * program that never calls the agent does not need it.
6
+ */
7
+ const loadPi = () => import("@earendil-works/pi-coding-agent");
2
8
  /** The pi version this runtime is built against (recorded in each project's meta.json). */
3
- export { VERSION as PI_VERSION } from "@earendil-works/pi-coding-agent";
9
+ export const piVersion = async () => (await loadPi()).VERSION;
4
10
  /** provider/model pairs already warned about, so a loop of agent calls warns once per process. */
5
11
  const warnedUnknownModels = new Set();
6
12
  /** The pi coding agent, run in-process: a fresh in-memory session for every call. */
@@ -12,6 +18,9 @@ export class PiAdapter {
12
18
  async createSession(cwd, systemPrompt, signal) {
13
19
  if (signal?.aborted)
14
20
  throw new Error("Aborted");
21
+ // Each step below is given up on the moment the call is cancelled.
22
+ const raceAbort = (step) => rejectOnAbort(step, signal);
23
+ const { createAgentSession, SessionManager, DefaultResourceLoader, ModelRuntime, getAgentDir } = await raceAbort(loadPi());
15
24
  const agentDir = getAgentDir();
16
25
  const resourceLoader = new DefaultResourceLoader({
17
26
  cwd,
@@ -20,26 +29,6 @@ export class PiAdapter {
20
29
  noSkills: true,
21
30
  ...(systemPrompt && { appendSystemPrompt: [systemPrompt] }),
22
31
  });
23
- // Race an async step against the abort signal.
24
- // Returns the result on success, or rejects with "Aborted" on abort.
25
- const raceAbort = (promise) => {
26
- if (!signal)
27
- return promise;
28
- let onAbort = null;
29
- const cleanup = () => {
30
- if (onAbort) {
31
- signal.removeEventListener("abort", onAbort);
32
- onAbort = null;
33
- }
34
- };
35
- return Promise.race([
36
- promise.finally(cleanup),
37
- new Promise((_resolve, reject) => {
38
- onAbort = () => reject(new Error("Aborted"));
39
- signal.addEventListener("abort", onAbort, { once: true });
40
- }),
41
- ]);
42
- };
43
32
  await raceAbort(resourceLoader.reload());
44
33
  if (signal?.aborted)
45
34
  throw new Error("Aborted");
@@ -23,7 +23,16 @@ export interface RunOptions {
23
23
  args?: Record<string, unknown>;
24
24
  /** Shared workspace directory. When set, workspace.* API is enabled for the program. */
25
25
  workspaceDir?: string;
26
+ /** A name for this run — a participant's, say. Its output is shown under it. */
27
+ label?: string;
28
+ /**
29
+ * Stops the run: its program is stopped, no repair is attempted, and the
30
+ * run ends as failed. A fix that was being tried leaves no trace.
31
+ */
32
+ signal?: AbortSignal;
26
33
  }
34
+ /** A run as one program asks its runner for it: everything in RunOptions that can cross the bridge. */
35
+ export type RunRequest = Omit<RunOptions, "signal">;
27
36
  export interface TramaConfig extends ModelConfig {
28
37
  maxRepairAttempts: number;
29
38
  defaultTimeout: number;