@trama-dev/runtime 0.1.3 → 0.1.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -12,7 +12,7 @@ The runtime behind [trama](https://github.com/NaNhkNaN/trama) — execution, sta
12
12
  import { ctx, agent, tools } from "@trama-dev/runtime";
13
13
 
14
14
  const data = await tools.read("input.csv");
15
- const report = await agent.ask(`Analyze this:\n${data}`);
15
+ const report = await agent.instruct(`Analyze this:\n${data}`);
16
16
  await tools.write("report.md", report);
17
17
  await ctx.done();
18
18
  ```
package/dist/agent.js CHANGED
@@ -21,10 +21,10 @@ function validateShape(result, schema) {
21
21
  return null;
22
22
  }
23
23
  export function createAgent(adapter, signal) {
24
+ const instructImpl = async (prompt, options) => adapter.ask(prompt, signal ? { ...options, signal } : options);
24
25
  return {
25
- async ask(prompt, options) {
26
- return adapter.ask(prompt, signal ? { ...options, signal } : options);
27
- },
26
+ instruct: instructImpl,
27
+ ask: instructImpl,
28
28
  async generate(input) {
29
29
  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
30
  const fullPrompt = `${input.prompt}\n\n${schemaInstruction}`;
package/dist/client.d.ts CHANGED
@@ -1,4 +1,5 @@
1
- import type { Ctx, Agent, Tools } from "./types.js";
1
+ 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
+ export declare const workspace: Workspace;
package/dist/client.js CHANGED
@@ -26,11 +26,14 @@ async function call(endpoint, body) {
26
26
  }
27
27
  let donePromise = null;
28
28
  let readyCalled = false;
29
+ let terminalSignal = null;
29
30
  export const ctx = {
30
31
  input: initData.input,
31
32
  state: initData.state,
32
33
  iteration: initData.iteration,
33
34
  maxIterations: initData.maxIterations,
35
+ resumed: initData.resumed ?? false,
36
+ yieldReason: initData.yieldReason ?? null,
34
37
  async log(msg, data) {
35
38
  let safeData = data;
36
39
  try {
@@ -60,10 +63,15 @@ export const ctx = {
60
63
  ctx.iteration += 1;
61
64
  },
62
65
  async done(result) {
66
+ // Mutual exclusivity: yield() was already called
67
+ if (terminalSignal === "yielded") {
68
+ throw new Error("Cannot call ctx.done() after ctx.yield() — yield already signaled.");
69
+ }
63
70
  // If a previous done() completed or is in flight, coalesce onto it.
64
71
  // If a previous done() failed, allow retry (promise was cleared).
65
72
  if (donePromise)
66
73
  return donePromise;
74
+ terminalSignal = "done";
67
75
  const run = async () => {
68
76
  assertSerializable(ctx.state, "ctx.state");
69
77
  if (result !== undefined)
@@ -80,9 +88,28 @@ export const ctx = {
80
88
  throw err;
81
89
  }
82
90
  },
91
+ async yield(reason) {
92
+ // Mutual exclusivity: done() was already called
93
+ if (terminalSignal === "done") {
94
+ throw new Error("Cannot call ctx.yield() after ctx.done() — done already signaled.");
95
+ }
96
+ // Idempotent: second yield after successful persistence is a no-op
97
+ if (terminalSignal === "yielded") {
98
+ process.exit(0);
99
+ }
100
+ assertSerializable(ctx.state, "ctx.state");
101
+ // Set terminalSignal only after validation and HTTP call succeed,
102
+ // so a failed yield can be retried (mirrors done()'s retry pattern).
103
+ await call("/ctx/yield", { state: ctx.state, reason });
104
+ terminalSignal = "yielded";
105
+ // Structured exit — the runner detects the yield marker in state.json
106
+ process.exit(0);
107
+ },
83
108
  };
109
+ const instructImpl = (prompt, opts) => call("/agent/ask", { prompt, ...opts }).then(r => r.result);
84
110
  export const agent = {
85
- ask: (prompt, opts) => call("/agent/ask", { prompt, ...opts }).then(r => r.result),
111
+ instruct: instructImpl,
112
+ ask: instructImpl,
86
113
  generate: (input) => call("/agent/generate", input).then(r => r.result),
87
114
  };
88
115
  export const tools = {
@@ -91,3 +118,30 @@ export const tools = {
91
118
  shell: (cmd, opts) => call("/tools/shell", { command: cmd, ...opts }).then(r => r.result),
92
119
  fetch: (url, opts) => call("/tools/fetch", { url, ...opts }).then(r => r.result),
93
120
  };
121
+ // Workspace — available only when running in a session (workspace path is in init data)
122
+ function createWorkspaceClient() {
123
+ const throwIfNoWorkspace = () => {
124
+ if (!initData.workspace) {
125
+ throw new Error("workspace is only available when running in a session");
126
+ }
127
+ };
128
+ return {
129
+ async read(path) {
130
+ throwIfNoWorkspace();
131
+ return call("/workspace/read", { path }).then(r => r.result);
132
+ },
133
+ async write(path, content) {
134
+ throwIfNoWorkspace();
135
+ return call("/workspace/write", { path, content }).then(r => r.result);
136
+ },
137
+ async list(pattern) {
138
+ throwIfNoWorkspace();
139
+ return call("/workspace/list", { pattern }).then(r => r.result);
140
+ },
141
+ async observe(pattern, options) {
142
+ throwIfNoWorkspace();
143
+ return call("/workspace/observe", { pattern, ...options }).then(r => r.result);
144
+ },
145
+ };
146
+ }
147
+ export const workspace = createWorkspaceClient();
package/dist/context.js CHANGED
@@ -9,9 +9,15 @@ export function createContext(projectDir, initialState, options) {
9
9
  let donePromise = null;
10
10
  let doneLogged = false;
11
11
  let readyCalled = false;
12
+ // Track terminal signal: null, "done", or "yielded"
13
+ let terminalSignal = null;
12
14
  const input = options?.argsOverride
13
15
  ? { ...meta.input, args: { ...(meta.input.args ?? {}), ...options.argsOverride } }
14
16
  : meta.input;
17
+ // Detect yield marker from previous run
18
+ const yieldMarker = initialState.__trama_yield;
19
+ const resumed = yieldMarker != null;
20
+ const yieldReason = yieldMarker?.reason ?? null;
15
21
  return {
16
22
  input,
17
23
  state: { ...initialState },
@@ -20,6 +26,8 @@ export function createContext(projectDir, initialState, options) {
20
26
  && initialState.__trama_iteration >= 0
21
27
  ? initialState.__trama_iteration : 0,
22
28
  maxIterations: options?.maxIterations ?? 100,
29
+ resumed,
30
+ yieldReason,
23
31
  async log(message, data) {
24
32
  let safeData = data ?? null;
25
33
  try {
@@ -41,23 +49,40 @@ export function createContext(projectDir, initialState, options) {
41
49
  },
42
50
  async checkpoint() {
43
51
  assertSerializable(this.state, "ctx.state");
52
+ // Clear yield marker on checkpoint (explicit state advancement)
53
+ delete this.state.__trama_yield;
44
54
  const nextIteration = this.iteration + 1;
45
55
  this.state.__trama_iteration = nextIteration;
46
56
  writeFileSync(statePath, JSON.stringify(this.state, null, 2));
47
57
  this.iteration = nextIteration;
48
58
  },
49
59
  async done(result) {
60
+ // Mutual exclusivity: yield() was already called
61
+ if (terminalSignal === "yielded") {
62
+ throw new Error("Cannot call ctx.done() after ctx.yield() — yield already signaled.");
63
+ }
50
64
  // If a previous done() completed successfully, no-op.
51
65
  // If a previous done() is still in flight, coalesce onto it.
52
66
  // If a previous done() failed (checkpoint threw), allow retry.
53
67
  if (donePromise)
54
68
  return donePromise;
69
+ terminalSignal = "done";
55
70
  const run = async () => {
71
+ // Persist first — this is the critical action
72
+ this.state.__trama_done = { result: result ?? null };
73
+ // Clear any stale yield marker
74
+ delete this.state.__trama_yield;
75
+ await this.checkpoint();
76
+ // Log is best-effort: persistence already succeeded.
77
+ // Matches yield()'s pattern — log failure must not
78
+ // prevent the IPC handler from acknowledging the signal.
56
79
  if (!doneLogged) {
57
- await this.log("done", result);
80
+ try {
81
+ await this.log("done", result);
82
+ }
83
+ catch { /* best-effort */ }
84
+ doneLogged = true;
58
85
  }
59
- await this.checkpoint();
60
- doneLogged = true;
61
86
  };
62
87
  donePromise = run();
63
88
  try {
@@ -68,6 +93,40 @@ export function createContext(projectDir, initialState, options) {
68
93
  donePromise = null;
69
94
  throw err;
70
95
  }
71
- }
96
+ },
97
+ async yield(reason) {
98
+ // Mutual exclusivity: done() was already called
99
+ if (terminalSignal === "done") {
100
+ throw new Error("Cannot call ctx.yield() after ctx.done() — done already signaled.");
101
+ }
102
+ // Idempotent: second yield after successful persistence is a no-op
103
+ if (terminalSignal === "yielded") {
104
+ // In server-side context, just return (won't actually reach here
105
+ // in IPC mode since the client exits after the first yield)
106
+ return undefined;
107
+ }
108
+ assertSerializable(this.state, "ctx.state");
109
+ // Persist yield marker
110
+ this.state.__trama_yield = { reason };
111
+ // Clear done marker if somehow present
112
+ delete this.state.__trama_done;
113
+ const nextIteration = this.iteration + 1;
114
+ this.state.__trama_iteration = nextIteration;
115
+ writeFileSync(statePath, JSON.stringify(this.state, null, 2));
116
+ // Set terminalSignal only after persistence succeeds,
117
+ // so a failed yield can be retried (mirrors done()'s pattern).
118
+ terminalSignal = "yielded";
119
+ // Log is best-effort: the critical action (state persistence) already
120
+ // succeeded. A log failure must not prevent the IPC handler from
121
+ // acknowledging the yield to the signal tracker.
122
+ try {
123
+ await this.log("yield", { reason });
124
+ }
125
+ catch { /* best-effort */ }
126
+ // In IPC mode, the client handles process.exit(0).
127
+ // Return never — the caller (IPC handler) responds to the client,
128
+ // and the client exits the child process.
129
+ return undefined;
130
+ },
72
131
  };
73
132
  }
package/dist/index.d.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  export { runProgram } from "./runner.js";
2
+ export type { ProgramResult, RunOptions } from "./types.js";
2
3
  export declare function validateProjectName(name: string): void;
3
4
  export declare function resolveProject(name: string): string;
4
5
  export declare function createProject(name: string, prompt: string, options?: {
package/dist/index.js CHANGED
@@ -19,7 +19,7 @@ await ctx.done();
19
19
  import { ctx, agent, tools } from "@trama-dev/runtime";
20
20
 
21
21
  const data = await tools.read(ctx.input.args.file as string);
22
- const summary = await agent.ask("Summarize this data concisely:\\n" + data);
22
+ const summary = await agent.instruct("Summarize this data concisely:\\n" + data);
23
23
  await tools.write("summary.md", summary);
24
24
  await ctx.done({ summaryLength: summary.length });
25
25
 
@@ -89,6 +89,9 @@ await new Promise<void>(() => {});`;
89
89
  function getSystemPrompt() {
90
90
  return (`You are generating a TypeScript program for the trama runtime.\n\n` +
91
91
  `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` +
92
+ `The workspace object is available when running in a session (shared artifact I/O between agents). ` +
93
+ `ctx.yield(reason) suspends the program cooperatively — persists state and exits. ` +
94
+ `ctx.resumed is true if this run follows a yield; ctx.yieldReason has the reason.\n\n` +
92
95
  `Runtime API:\n${RUNTIME_TYPES}\n\n` +
93
96
  `Examples:\n${EXAMPLE_PROGRAMS}`);
94
97
  }
@@ -109,7 +112,7 @@ export function resolveProject(name) {
109
112
  return dir;
110
113
  }
111
114
  // --- Helpers ---
112
- /** Run an LLM ask() in an isolated temp cwd so pi-coding-agent tools can't write into the real project. */
115
+ /** Run an LLM instruction in an isolated temp cwd so pi-coding-agent tools can't write into the real project. */
113
116
  async function isolatedAsk(adapter, prompt, options) {
114
117
  return withTempDir("trama-gen-", (dir) => adapter.withCwd(dir).ask(prompt, options));
115
118
  }
package/dist/runner.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import type { RunOptions, TramaConfig } from "./types.js";
1
+ import type { RunOptions, TramaConfig, ProgramResult } from "./types.js";
2
2
  import { PiAdapter } from "./pi-adapter.js";
3
3
  export declare const PI_VERSION: string;
4
4
  /**
@@ -13,7 +13,7 @@ export declare function ensureProjectScaffold(projectDir: string): void;
13
13
  * needs a concise reference, not the full implementation types.
14
14
  * If types.ts changes, review whether this summary needs updating.
15
15
  */
16
- export declare const RUNTIME_TYPES = "// @trama-dev/runtime - Complete API\n\nexport interface Ctx {\n input: { prompt: string; args: Record<string, unknown> };\n state: Record<string, unknown>;\n iteration: number;\n maxIterations: number;\n log(message: string, data?: Record<string, unknown>): Promise<void>;\n ready(data?: Record<string, unknown>): Promise<void>;\n checkpoint(): Promise<void>;\n done(result?: Record<string, unknown>): Promise<void>;\n}\n\nexport interface Agent {\n ask(prompt: string, options?: { system?: string }): Promise<string>;\n generate<T>(input: {\n prompt: string;\n schema: Record<string, string>;\n system?: string;\n }): Promise<T>;\n}\n\nexport interface ShellResult {\n exitCode: number;\n stdout: string;\n stderr: string;\n}\n\nexport interface Tools {\n read(path: string): Promise<string>;\n write(path: string, content: string): Promise<void>;\n shell(command: string, options?: { cwd?: string; timeout?: number }): Promise<ShellResult>;\n fetch(url: string, options?: {\n method?: string;\n headers?: Record<string, string>;\n body?: string;\n }): Promise<{ status: number; body: string; headers: Record<string, string> }>;\n}\n\nexport declare const ctx: Ctx;\nexport declare const agent: Agent;\nexport declare const tools: Tools;";
16
+ export declare const RUNTIME_TYPES = "// @trama-dev/runtime - Complete API\n\nexport interface Ctx {\n input: { prompt: string; args: Record<string, unknown> };\n state: Record<string, unknown>;\n iteration: number;\n maxIterations: number;\n readonly resumed: boolean;\n readonly yieldReason: string | null;\n log(message: string, data?: Record<string, unknown>): Promise<void>;\n ready(data?: Record<string, unknown>): Promise<void>;\n checkpoint(): Promise<void>;\n done(result?: Record<string, unknown>): Promise<void>;\n yield(reason: string): Promise<never>;\n}\n\nexport interface Agent {\n instruct(prompt: string, options?: { system?: string }): Promise<string>;\n /** @deprecated Use instruct() instead */\n ask(prompt: string, options?: { system?: string }): Promise<string>;\n generate<T>(input: {\n prompt: string;\n schema: Record<string, string>;\n system?: string;\n }): Promise<T>;\n}\n\nexport interface ShellResult {\n exitCode: number;\n stdout: string;\n stderr: string;\n}\n\nexport interface Tools {\n read(path: string): Promise<string>;\n write(path: string, content: string): Promise<void>;\n shell(command: string, options?: { cwd?: string; timeout?: number }): Promise<ShellResult>;\n fetch(url: string, options?: {\n method?: string;\n headers?: Record<string, string>;\n body?: string;\n }): Promise<{ status: number; body: string; headers: Record<string, string> }>;\n}\n\nexport type ObserveResult = string | Array<{ path: string; content: string }>;\n\nexport interface Workspace {\n read(path: string): Promise<string>;\n write(path: string, content: string): Promise<void>;\n list(pattern: string): Promise<string[]>;\n observe(pattern: string, options?: { expect?: number; timeout?: number }): Promise<ObserveResult>;\n}\n\nexport declare const ctx: Ctx;\nexport declare const agent: Agent;\nexport declare const tools: Tools;\nexport declare const workspace: Workspace;";
17
17
  export declare function loadConfig(): TramaConfig;
18
18
  export declare function loadState(projectDir: string): Record<string, unknown>;
19
19
  /**
@@ -23,6 +23,32 @@ export declare function loadState(projectDir: string): Record<string, unknown>;
23
23
  * Create-time repairs go to index.jsonl only (reason: "create-repair").
24
24
  */
25
25
  export declare function copyToHistory(projectDir: string, reason: string, detail?: string): void;
26
+ /** Record all files in a directory with their size and mtime for change detection. */
27
+ export declare function snapshotDir(dir: string, prefix?: string): Map<string, {
28
+ size: number;
29
+ mtimeMs: number;
30
+ }>;
31
+ /**
32
+ * Commit workspace changes from a temp workspace back to the real workspace,
33
+ * using a three-way check to avoid overwriting concurrent updates by other participants.
34
+ *
35
+ * @param tempDir - temp workspace after the rerun (source of changes)
36
+ * @param realDir - real shared workspace (destination)
37
+ * @param tempBefore - temp workspace snapshot before the rerun (detects what the rerun changed)
38
+ * @param realSeed - real workspace snapshot at seed time (detects concurrent changes)
39
+ *
40
+ * For each file changed in the temp workspace during the rerun:
41
+ * - New file (not in tempBefore): always copy to real workspace.
42
+ * - Modified file: only copy if the real workspace's current state still matches
43
+ * realSeed. If it doesn't, another participant changed it concurrently — skip.
44
+ */
45
+ export declare function commitWorkspaceChanges(tempDir: string, realDir: string, tempBefore: Map<string, {
46
+ size: number;
47
+ mtimeMs: number;
48
+ }>, realSeed: Map<string, {
49
+ size: number;
50
+ mtimeMs: number;
51
+ }>): void;
26
52
  /**
27
53
  * Snapshot a directory, run fn, restore from snapshot if fn returns false
28
54
  * or if fn throws. Always cleans up the snapshot. Returns whatever fn returns.
@@ -39,4 +65,4 @@ export declare function smokeRunAndRepair(projectDir: string, adapter: PiAdapter
39
65
  maxRepairAttempts?: number;
40
66
  maxIterations?: number;
41
67
  }): Promise<void>;
42
- export declare function runProgram(options: RunOptions): Promise<void>;
68
+ export declare function runProgram(options: RunOptions): Promise<ProgramResult>;
package/dist/runner.js CHANGED
@@ -1,6 +1,6 @@
1
1
  import { createServer } from "http";
2
2
  import { spawn } from "child_process";
3
- import { readFileSync, writeFileSync, appendFileSync, readdirSync, copyFileSync, mkdirSync, existsSync, symlinkSync, rmSync, lstatSync, readlinkSync, cpSync, mkdtempSync, openSync, closeSync, } from "fs";
3
+ import { readFileSync, writeFileSync, appendFileSync, readdirSync, copyFileSync, mkdirSync, existsSync, statSync, symlinkSync, rmSync, lstatSync, readlinkSync, cpSync, mkdtempSync, openSync, closeSync, } from "fs";
4
4
  import { join, dirname } from "path";
5
5
  import { homedir, tmpdir } from "os";
6
6
  import { fileURLToPath } from "url";
@@ -11,6 +11,7 @@ import { createAgent } from "./agent.js";
11
11
  import { createTools, cappedBuffer } from "./tools.js";
12
12
  import { guardPath } from "./path-guard.js";
13
13
  import { assertSerializable } from "./serializable.js";
14
+ import { createWorkspace } from "./workspace.js";
14
15
  // --- Module resolution for child processes ---
15
16
  /**
16
17
  * Find the node_modules directory that contains @trama-dev/runtime.
@@ -121,13 +122,18 @@ export interface Ctx {
121
122
  state: Record<string, unknown>;
122
123
  iteration: number;
123
124
  maxIterations: number;
125
+ readonly resumed: boolean;
126
+ readonly yieldReason: string | null;
124
127
  log(message: string, data?: Record<string, unknown>): Promise<void>;
125
128
  ready(data?: Record<string, unknown>): Promise<void>;
126
129
  checkpoint(): Promise<void>;
127
130
  done(result?: Record<string, unknown>): Promise<void>;
131
+ yield(reason: string): Promise<never>;
128
132
  }
129
133
 
130
134
  export interface Agent {
135
+ instruct(prompt: string, options?: { system?: string }): Promise<string>;
136
+ /** @deprecated Use instruct() instead */
131
137
  ask(prompt: string, options?: { system?: string }): Promise<string>;
132
138
  generate<T>(input: {
133
139
  prompt: string;
@@ -153,9 +159,19 @@ export interface Tools {
153
159
  }): Promise<{ status: number; body: string; headers: Record<string, string> }>;
154
160
  }
155
161
 
162
+ export type ObserveResult = string | Array<{ path: string; content: string }>;
163
+
164
+ export interface Workspace {
165
+ read(path: string): Promise<string>;
166
+ write(path: string, content: string): Promise<void>;
167
+ list(pattern: string): Promise<string[]>;
168
+ observe(pattern: string, options?: { expect?: number; timeout?: number }): Promise<ObserveResult>;
169
+ }
170
+
156
171
  export declare const ctx: Ctx;
157
172
  export declare const agent: Agent;
158
- export declare const tools: Tools;`;
173
+ export declare const tools: Tools;
174
+ export declare const workspace: Workspace;`;
159
175
  // --- Config & state loaders ---
160
176
  export function loadConfig() {
161
177
  const configPath = join(homedir(), ".trama", "config.json");
@@ -240,7 +256,7 @@ function validateIPC(data, fields) {
240
256
  }
241
257
  return null;
242
258
  }
243
- function createIPCServer(ctx, agentImpl, toolsImpl) {
259
+ function createIPCServer(ctx, agentImpl, toolsImpl, workspaceImpl, signalTracker) {
244
260
  return createServer((req, res) => {
245
261
  if (req.method !== "POST") {
246
262
  res.writeHead(405);
@@ -279,6 +295,11 @@ function createIPCServer(ctx, agentImpl, toolsImpl) {
279
295
  "/ctx/checkpoint": { state: "object" },
280
296
  "/ctx/log": { message: "string" },
281
297
  "/ctx/done": { state: "object" },
298
+ "/ctx/yield": { state: "object", reason: "string" },
299
+ "/workspace/read": { path: "string" },
300
+ "/workspace/write": { path: "string", content: "string" },
301
+ "/workspace/list": { pattern: "string" },
302
+ "/workspace/observe": { pattern: "string" },
282
303
  };
283
304
  const rules = req.url ? validationRules[req.url] : undefined;
284
305
  if (rules) {
@@ -348,9 +369,64 @@ function createIPCServer(ctx, agentImpl, toolsImpl) {
348
369
  assertSerializable(data.state, "ctx.state");
349
370
  ctx.state = data.state;
350
371
  await ctx.done(data.result);
372
+ if (signalTracker)
373
+ signalTracker.doneCalled = true;
374
+ res.writeHead(200, { "Content-Type": "application/json" });
375
+ res.end(JSON.stringify({ result: null }));
376
+ break;
377
+ case "/ctx/yield":
378
+ assertSerializable(data.state, "ctx.state");
379
+ ctx.state = data.state;
380
+ await ctx.yield(data.reason);
381
+ if (signalTracker)
382
+ signalTracker.yieldCalled = true;
383
+ // yield() calls process.exit(0) on the server-side context,
384
+ // but in IPC mode we just persist and respond — the client exits.
385
+ res.writeHead(200, { "Content-Type": "application/json" });
386
+ res.end(JSON.stringify({ result: null }));
387
+ break;
388
+ case "/workspace/read":
389
+ if (!workspaceImpl) {
390
+ res.writeHead(400);
391
+ res.end("Workspace is only available when running in a session");
392
+ break;
393
+ }
394
+ result = await workspaceImpl.read(data.path);
395
+ res.writeHead(200, { "Content-Type": "application/json" });
396
+ res.end(JSON.stringify({ result }));
397
+ break;
398
+ case "/workspace/write":
399
+ if (!workspaceImpl) {
400
+ res.writeHead(400);
401
+ res.end("Workspace is only available when running in a session");
402
+ break;
403
+ }
404
+ await workspaceImpl.write(data.path, data.content);
351
405
  res.writeHead(200, { "Content-Type": "application/json" });
352
406
  res.end(JSON.stringify({ result: null }));
353
407
  break;
408
+ case "/workspace/list":
409
+ if (!workspaceImpl) {
410
+ res.writeHead(400);
411
+ res.end("Workspace is only available when running in a session");
412
+ break;
413
+ }
414
+ result = await workspaceImpl.list(data.pattern);
415
+ res.writeHead(200, { "Content-Type": "application/json" });
416
+ res.end(JSON.stringify({ result }));
417
+ break;
418
+ case "/workspace/observe":
419
+ if (!workspaceImpl) {
420
+ res.writeHead(400);
421
+ res.end("Workspace is only available when running in a session");
422
+ break;
423
+ }
424
+ result = await workspaceImpl.observe(data.pattern, {
425
+ expect: data.expect, timeout: data.timeout,
426
+ });
427
+ res.writeHead(200, { "Content-Type": "application/json" });
428
+ res.end(JSON.stringify({ result }));
429
+ break;
354
430
  default:
355
431
  res.writeHead(404);
356
432
  res.end("Not found");
@@ -520,6 +596,109 @@ export function copyToHistory(projectDir, reason, detail) {
520
596
  appendFileSync(indexPath, JSON.stringify(entry) + "\n");
521
597
  }
522
598
  // --- Helpers ---
599
+ /** Record all files in a directory with their size and mtime for change detection. */
600
+ export function snapshotDir(dir, prefix = "") {
601
+ const result = new Map();
602
+ let entries;
603
+ try {
604
+ entries = readdirSync(dir, { withFileTypes: true });
605
+ }
606
+ catch {
607
+ return result;
608
+ }
609
+ for (const entry of entries) {
610
+ const relPath = prefix ? `${prefix}/${entry.name}` : entry.name;
611
+ const fullPath = join(dir, entry.name);
612
+ if (entry.isDirectory()) {
613
+ for (const [k, v] of snapshotDir(fullPath, relPath))
614
+ result.set(k, v);
615
+ }
616
+ else if (entry.isFile()) {
617
+ try {
618
+ const st = statSync(fullPath);
619
+ result.set(relPath, { size: st.size, mtimeMs: st.mtimeMs });
620
+ }
621
+ catch { /* skip */ }
622
+ }
623
+ }
624
+ return result;
625
+ }
626
+ /**
627
+ * Commit workspace changes from a temp workspace back to the real workspace,
628
+ * using a three-way check to avoid overwriting concurrent updates by other participants.
629
+ *
630
+ * @param tempDir - temp workspace after the rerun (source of changes)
631
+ * @param realDir - real shared workspace (destination)
632
+ * @param tempBefore - temp workspace snapshot before the rerun (detects what the rerun changed)
633
+ * @param realSeed - real workspace snapshot at seed time (detects concurrent changes)
634
+ *
635
+ * For each file changed in the temp workspace during the rerun:
636
+ * - New file (not in tempBefore): always copy to real workspace.
637
+ * - Modified file: only copy if the real workspace's current state still matches
638
+ * realSeed. If it doesn't, another participant changed it concurrently — skip.
639
+ */
640
+ export function commitWorkspaceChanges(tempDir, realDir, tempBefore, realSeed) {
641
+ const tempAfter = snapshotDir(tempDir);
642
+ for (const [relPath, afterStat] of tempAfter) {
643
+ const beforeStat = tempBefore.get(relPath);
644
+ // Was this file created or modified by the rerun?
645
+ if (beforeStat && beforeStat.size === afterStat.size && beforeStat.mtimeMs === afterStat.mtimeMs) {
646
+ continue; // Unchanged in temp — nothing to commit
647
+ }
648
+ const dstPath = join(realDir, relPath);
649
+ // Verify the path resolves inside the workspace root before any stat/write.
650
+ // A concurrent participant could have placed a symlink at this path or in
651
+ // a parent directory, pointing outside the workspace.
652
+ try {
653
+ guardPath(realDir, relPath);
654
+ }
655
+ catch {
656
+ continue; // Path escapes workspace via symlink — skip
657
+ }
658
+ if (beforeStat) {
659
+ // File existed before the rerun — three-way check against the real workspace.
660
+ // If the real workspace's version no longer matches the seed, another
661
+ // participant modified it concurrently — skip to preserve their update.
662
+ const seedStat = realSeed.get(relPath);
663
+ if (seedStat) {
664
+ try {
665
+ const realNow = statSync(dstPath);
666
+ if (realNow.size !== seedStat.size || realNow.mtimeMs !== seedStat.mtimeMs) {
667
+ continue; // Concurrent modification — preserve other participant's version
668
+ }
669
+ }
670
+ catch {
671
+ continue; // File removed concurrently — don't resurrect
672
+ }
673
+ }
674
+ }
675
+ else {
676
+ // New file created by the rerun — check if another participant also
677
+ // created the same path concurrently in the real workspace.
678
+ try {
679
+ statSync(dstPath);
680
+ continue; // Path already exists in real workspace — preserve other participant's version
681
+ }
682
+ catch {
683
+ // ENOENT — path doesn't exist in real workspace, safe to create
684
+ }
685
+ }
686
+ // Best-effort commit with path-guard enforcement.
687
+ // Verify the destination resolves inside the workspace root before writing.
688
+ // A concurrent participant could have placed a symlink pointing outside
689
+ // the workspace — guardPath catches that. Any other filesystem conflict
690
+ // (path-shape, permissions) is also caught and skipped.
691
+ try {
692
+ guardPath(realDir, relPath);
693
+ const srcPath = join(tempDir, relPath);
694
+ mkdirSync(dirname(dstPath), { recursive: true });
695
+ copyFileSync(srcPath, dstPath);
696
+ }
697
+ catch {
698
+ // Path escapes workspace via symlink, path-shape conflict, or other error — skip
699
+ }
700
+ }
701
+ }
523
702
  /**
524
703
  * Snapshot a directory, run fn, restore from snapshot if fn returns false
525
704
  * or if fn throws. Always cleans up the snapshot. Returns whatever fn returns.
@@ -582,7 +761,8 @@ async function repairWithTimeout(adapter, input, timeout, repairErrors) {
582
761
  * Returns the child process result — does NOT throw on non-zero exit.
583
762
  */
584
763
  async function runProgramOnce(options) {
585
- const { projectDir, adapter, timeout, maxIterations, argsOverride, streamOutput, stopOnReady } = options;
764
+ const { projectDir, adapter, timeout, maxIterations, argsOverride, streamOutput, stopOnReady, workspaceDir } = options;
765
+ const signalTracker = { doneCalled: false, yieldCalled: false };
586
766
  ensureProjectScaffold(projectDir);
587
767
  ensureRuntimeLink(projectDir);
588
768
  const abortController = new AbortController();
@@ -613,7 +793,8 @@ async function runProgramOnce(options) {
613
793
  writeFileSync(guardPath(projectDir, join("logs", "latest.jsonl")), "");
614
794
  const agentImpl = createAgent(adapter, signal);
615
795
  const toolsImpl = createTools(projectDir, signal);
616
- const server = createIPCServer(ctx, agentImpl, toolsImpl);
796
+ const workspaceImpl = workspaceDir ? createWorkspace(workspaceDir, signal) : null;
797
+ const server = createIPCServer(ctx, agentImpl, toolsImpl, workspaceImpl, signalTracker);
617
798
  // Infrastructure setup — errors here are NOT program bugs.
618
799
  let port;
619
800
  try {
@@ -634,6 +815,9 @@ async function runProgramOnce(options) {
634
815
  state: ctx.state,
635
816
  iteration: ctx.iteration,
636
817
  maxIterations: ctx.maxIterations,
818
+ workspace: workspaceDir ?? null,
819
+ resumed: ctx.resumed,
820
+ yieldReason: ctx.yieldReason,
637
821
  }));
638
822
  }
639
823
  finally {
@@ -719,28 +903,75 @@ async function runProgramOnce(options) {
719
903
  }
720
904
  catch { /* best-effort */ }
721
905
  }
722
- return result;
906
+ return { child: result, signals: signalTracker };
723
907
  }
724
908
  const formatError = (r) => `program.ts exited with code ${r.exitCode}\nstdout: ${r.stdout}\nstderr: ${r.stderr}`;
909
+ /**
910
+ * Read persisted terminal signals from state.json after a program exits.
911
+ * Uses the IPC signal tracker to distinguish "called during this run" from
912
+ * "stale marker from a previous run".
913
+ * Returns a ProgramResult based on markers and exit code, or null if no
914
+ * terminal signal was found and exit code is non-zero (needs repair).
915
+ */
916
+ function readTerminalSignal(projectDir, childResult, signals) {
917
+ const state = loadState(projectDir);
918
+ // Check done marker first — only if done was actually called this run
919
+ if (signals.doneCalled) {
920
+ const doneMarker = state.__trama_done;
921
+ if (doneMarker != null) {
922
+ return { status: "done", result: doneMarker.result ?? undefined };
923
+ }
924
+ }
925
+ // Check yield marker — only if yield was actually called this run
926
+ if (signals.yieldCalled) {
927
+ const yieldMarker = state.__trama_yield;
928
+ if (yieldMarker != null) {
929
+ return { status: "yielded", reason: yieldMarker.reason };
930
+ }
931
+ }
932
+ // No terminal signal called during this run
933
+ if (childResult.exitCode === 0) {
934
+ // Natural success — clear any stale yield marker
935
+ clearStaleYieldMarker(projectDir, state);
936
+ return { status: "done" };
937
+ }
938
+ // Non-zero exit, no terminal signal → needs repair
939
+ return null;
940
+ }
941
+ /**
942
+ * Clear stale yield marker from state.json when program exits normally without
943
+ * calling any terminal signal. Prevents stale yield state from polluting future runs.
944
+ */
945
+ function clearStaleYieldMarker(projectDir, state) {
946
+ if (state.__trama_yield != null) {
947
+ delete state.__trama_yield;
948
+ const statePath = guardPath(projectDir, "state.json");
949
+ writeFileSync(statePath, JSON.stringify(state, null, 2));
950
+ }
951
+ }
725
952
  async function executeProgram(options) {
726
953
  const { projectDir, adapter, maxRepairAttempts, timeout, maxIterations } = options;
727
954
  mkdirSync(guardPath(projectDir, "history"), { recursive: true });
728
955
  mkdirSync(guardPath(projectDir, "logs"), { recursive: true });
729
956
  // Phase 1: Run in the real project directory.
730
- const result = await runProgramOnce({
957
+ const runResult = await runProgramOnce({
731
958
  projectDir, adapter, timeout, maxIterations,
732
959
  argsOverride: options.argsOverride,
733
960
  streamOutput: true,
734
961
  stopOnReady: options.stopOnReady,
962
+ workspaceDir: options.workspaceDir,
735
963
  });
736
- if (result.exitCode === 0)
737
- return;
964
+ // Check for persisted terminal signals before checking exit code
965
+ const termSignal = readTerminalSignal(projectDir, runResult.child, runResult.signals);
966
+ if (termSignal)
967
+ return termSignal;
968
+ // Non-zero exit with no terminal signal → attempt repair
738
969
  if (maxRepairAttempts === 0) {
739
- throw new Error(`Program failed (repair disabled): ${formatError(result)}`);
970
+ return { status: "failed", reason: `Program failed (repair disabled): ${formatError(runResult.child)}` };
740
971
  }
741
972
  // Phase 2: Repair loop — both LLM repair call and verification run
742
973
  // are fully isolated in temp dirs to prevent side effects on the real project.
743
- let lastError = formatError(result);
974
+ let lastError = formatError(runResult.child);
744
975
  const originalSource = readFileSync(guardPath(projectDir, "program.ts"), "utf-8");
745
976
  let currentSource = originalSource;
746
977
  const repairErrors = [];
@@ -754,51 +985,98 @@ async function executeProgram(options) {
754
985
  if (!fixed)
755
986
  return null;
756
987
  writeFileSync(guardPath(tempDir, "program.ts"), fixed);
757
- const verifyResult = await runProgramOnce({
758
- projectDir: tempDir, adapter: tempAdapter, timeout, maxIterations,
759
- argsOverride: options.argsOverride,
760
- stopOnReady: options.stopOnReady,
761
- });
762
- return { fixed, verifyResult };
988
+ // Verification runs use a temp workspace seeded from the real one,
989
+ // so the repair can read existing artifacts but writes don't leak.
990
+ let tempWorkspaceDir;
991
+ if (options.workspaceDir) {
992
+ tempWorkspaceDir = mkdtempSync(join(tmpdir(), "trama-repair-ws-"));
993
+ cpSync(options.workspaceDir, tempWorkspaceDir, { recursive: true });
994
+ }
995
+ try {
996
+ const verifyResult = await runProgramOnce({
997
+ projectDir: tempDir, adapter: tempAdapter, timeout, maxIterations,
998
+ argsOverride: options.argsOverride,
999
+ stopOnReady: options.stopOnReady,
1000
+ workspaceDir: tempWorkspaceDir,
1001
+ });
1002
+ // Read terminal signal while tempDir still exists
1003
+ const verifySignal = readTerminalSignal(tempDir, verifyResult.child, verifyResult.signals);
1004
+ return { fixed, verifyResult, verifySignal, tempDir };
1005
+ }
1006
+ finally {
1007
+ if (tempWorkspaceDir) {
1008
+ try {
1009
+ rmSync(tempWorkspaceDir, { recursive: true, force: true });
1010
+ }
1011
+ catch { /* best-effort */ }
1012
+ }
1013
+ }
763
1014
  });
764
1015
  if (!repairResult) {
765
- // Repair LLM call itself failed — don't re-run the same broken program.
766
- throw new Error(`Failed after ${attempt + 1} repair attempt(s): ${lastError}${repairDetails()}`);
1016
+ return { status: "failed", reason: `Failed after ${attempt + 1} repair attempt(s): ${lastError}${repairDetails()}` };
767
1017
  }
768
- if (repairResult.verifyResult.exitCode === 0) {
1018
+ // Terminal signal was read inside withTempDir while state.json still existed
1019
+ const verifySignal = repairResult.verifySignal;
1020
+ if (verifySignal && verifySignal.status !== "failed") {
769
1021
  // Repair verified in isolation — now run in the real project for actual output.
770
- // Snapshot first so we can restore cleanly if the real run fails.
771
- const realResult = await withSnapshot(projectDir, async () => {
1022
+ // For workspace: run against a temp workspace seeded from the real one.
1023
+ // On success, commit new/changed artifacts back. On failure, discard the
1024
+ // temp workspace — the real workspace is never touched, so concurrent
1025
+ // writes from other participants are preserved.
1026
+ let realRerunWsDir;
1027
+ // Two snapshots for workspace three-way merge:
1028
+ // - realSeedSnapshot: real workspace at seed time (for detecting concurrent changes)
1029
+ // - tempBeforeSnapshot: temp workspace before rerun (for detecting rerun's changes)
1030
+ let realSeedSnapshot;
1031
+ let tempBeforeSnapshot;
1032
+ if (options.workspaceDir) {
1033
+ realSeedSnapshot = snapshotDir(options.workspaceDir);
1034
+ realRerunWsDir = mkdtempSync(join(tmpdir(), "trama-repair-realws-"));
1035
+ cpSync(options.workspaceDir, realRerunWsDir, { recursive: true });
1036
+ tempBeforeSnapshot = snapshotDir(realRerunWsDir);
1037
+ }
1038
+ const { run: realRun, signal: realSignal } = await withSnapshot(projectDir, async () => {
772
1039
  writeFileSync(guardPath(projectDir, "program.ts"), repairResult.fixed);
773
1040
  const r = await runProgramOnce({
774
1041
  projectDir, adapter, timeout, maxIterations,
775
1042
  argsOverride: options.argsOverride,
776
1043
  streamOutput: true,
777
1044
  stopOnReady: options.stopOnReady,
1045
+ workspaceDir: realRerunWsDir ?? options.workspaceDir,
778
1046
  });
779
- return { keep: r.exitCode === 0, value: r };
1047
+ const sig = readTerminalSignal(projectDir, r.child, r.signals);
1048
+ return { keep: sig != null && sig.status !== "failed", value: { run: r, signal: sig } };
780
1049
  });
781
- if (realResult.exitCode === 0) {
782
- // Bookkeeping is best-effort — program already succeeded and side effects
783
- // are committed. Don't mask success with a history/log write failure.
1050
+ if (realSignal && realSignal.status !== "failed") {
1051
+ // Success — commit only files that were created or modified during the
1052
+ // rerun, with a three-way check to avoid overwriting concurrent updates.
1053
+ if (realRerunWsDir && options.workspaceDir && tempBeforeSnapshot && realSeedSnapshot) {
1054
+ commitWorkspaceChanges(realRerunWsDir, options.workspaceDir, tempBeforeSnapshot, realSeedSnapshot);
1055
+ }
1056
+ }
1057
+ if (realRerunWsDir) {
1058
+ try {
1059
+ rmSync(realRerunWsDir, { recursive: true, force: true });
1060
+ }
1061
+ catch { /* best-effort */ }
1062
+ }
1063
+ if (realSignal && realSignal.status !== "failed") {
784
1064
  try {
785
1065
  options.onRepair?.(attempt, maxRepairAttempts, lastError);
786
1066
  }
787
1067
  catch (bookkeepingErr) {
788
1068
  console.warn(`[trama] repair bookkeeping failed: ${bookkeepingErr instanceof Error ? bookkeepingErr.message : bookkeepingErr}`);
789
1069
  }
790
- return;
1070
+ return realSignal;
791
1071
  }
792
- // Passed in isolation but failed in real dir — project already restored by withSnapshot.
793
1072
  currentSource = repairResult.fixed;
794
- lastError = formatError(realResult);
1073
+ lastError = realSignal?.reason ?? formatError(realRun.child);
795
1074
  continue;
796
1075
  }
797
- // Repair produced broken code — update context for next attempt.
798
1076
  currentSource = repairResult.fixed;
799
- lastError = formatError(repairResult.verifyResult);
1077
+ lastError = formatError(repairResult.verifyResult.child);
800
1078
  }
801
- throw new Error(`Failed after ${maxRepairAttempts} repair attempts: ${lastError}${repairDetails()}`);
1079
+ return { status: "failed", reason: `Failed after ${maxRepairAttempts} repair attempts: ${lastError}${repairDetails()}` };
802
1080
  }
803
1081
  // --- Smoke run (used by create and update) ---
804
1082
  /** Copy new history entries from src to dst (appends only entries added after the shared prefix). */
@@ -829,7 +1107,7 @@ export async function smokeRunAndRepair(projectDir, adapter, reason, options) {
829
1107
  cpSync(projectDir, smokeDir, { recursive: true });
830
1108
  const smokeAdapter = adapter.withCwd(smokeDir);
831
1109
  try {
832
- await executeProgram({
1110
+ const smokeResult = await executeProgram({
833
1111
  projectDir: smokeDir,
834
1112
  adapter: smokeAdapter,
835
1113
  maxRepairAttempts: options?.maxRepairAttempts ?? 3,
@@ -842,6 +1120,9 @@ export async function smokeRunAndRepair(projectDir, adapter, reason, options) {
842
1120
  appendFileSync(guardPath(smokeDir, join("history", "index.jsonl")), JSON.stringify({ reason: `${reason}-repair`, timestamp: new Date().toISOString(), error }) + "\n");
843
1121
  },
844
1122
  });
1123
+ if (smokeResult.status === "failed") {
1124
+ throw new Error(`Program failed: ${smokeResult.reason}`);
1125
+ }
845
1126
  // Smoke passed — copy back program.ts (may have been repaired)
846
1127
  copyFileSync(guardPath(smokeDir, "program.ts"), guardPath(projectDir, "program.ts"));
847
1128
  }
@@ -876,13 +1157,14 @@ export async function runProgram(options) {
876
1157
  throw new Error(`Invalid maxRepairAttempts: ${maxRepairAttempts}. Must be a non-negative integer.`);
877
1158
  }
878
1159
  const adapter = new PiAdapter(config, projectDir);
879
- await executeProgram({
1160
+ return executeProgram({
880
1161
  projectDir,
881
1162
  adapter,
882
1163
  maxRepairAttempts,
883
1164
  timeout,
884
1165
  maxIterations,
885
1166
  argsOverride: options.args,
1167
+ workspaceDir: options.workspaceDir,
886
1168
  onRepair(attempt, max, error) {
887
1169
  // Log repair attempts (appends to already-open logs file)
888
1170
  const logsPath = guardPath(projectDir, join("logs", "latest.jsonl"));
package/dist/types.d.ts CHANGED
@@ -17,6 +17,10 @@ export interface Ctx {
17
17
  iteration: number;
18
18
  /** Max iterations hint. Not enforced by runtime. */
19
19
  maxIterations: number;
20
+ /** True if this run follows a yield (read-only, set by runtime on startup). */
21
+ readonly resumed: boolean;
22
+ /** The reason string from the previous yield, or null (read-only, set by runtime on startup). */
23
+ readonly yieldReason: string | null;
20
24
  /** Write a structured log entry */
21
25
  log(message: string, data?: Record<string, unknown>): Promise<void>;
22
26
  /**
@@ -29,17 +33,35 @@ export interface Ctx {
29
33
  /** Persist current ctx.state to disk */
30
34
  checkpoint(): Promise<void>;
31
35
  /**
32
- * Signal program completion. Persists state and logs result.
36
+ * Signal program completion. Persists state (logging is best-effort).
33
37
  * Does NOT terminate execution — program should return naturally.
34
38
  * Idempotent: second call is a no-op.
39
+ * Mutually exclusive with yield() — throws if yield() was already called.
40
+ * Terminal choice is irreversible: once done() is attempted (even if it fails),
41
+ * yield() is permanently blocked. Fix the issue and retry done() instead.
35
42
  */
36
43
  done(result?: Record<string, unknown>): Promise<void>;
44
+ /**
45
+ * Cooperative suspension. Persists ctx.state with a yield marker and exits (logging is best-effort).
46
+ * The session layer (or manual `trama run`) re-runs the program when ready.
47
+ * The program resumes by reading its own ctx.state.
48
+ * Idempotent: second call is a no-op.
49
+ * Mutually exclusive with done() — throws if done() was already called.
50
+ * Unlike done(), yield's terminal choice is only locked after successful persistence —
51
+ * a failed yield() leaves both done() and yield() available for retry.
52
+ */
53
+ yield(reason: string): Promise<never>;
37
54
  }
38
55
  export interface Agent {
39
56
  /**
40
- * LLM call via pi-coding-agent. Returns plain text.
41
- * The underlying pi agent may use its built-in tools autonomously.
57
+ * Instruct the pi-coding-agent to perform a task. Returns plain text.
58
+ * The underlying agent may autonomously use its built-in tools
59
+ * (bash, file read/write/edit) to fulfill the instruction.
42
60
  */
61
+ instruct(prompt: string, options?: {
62
+ system?: string;
63
+ }): Promise<string>;
64
+ /** @deprecated Use instruct() instead. Alias kept for backwards compatibility. */
43
65
  ask(prompt: string, options?: {
44
66
  system?: string;
45
67
  }): Promise<string>;
@@ -80,6 +102,34 @@ export interface Tools {
80
102
  headers: Record<string, string>;
81
103
  }>;
82
104
  }
105
+ /** Result of workspace.observe(). Single-file returns content string; multi-file returns array. */
106
+ export type ObserveResult = string | Array<{
107
+ path: string;
108
+ content: string;
109
+ }>;
110
+ export interface Workspace {
111
+ /** Read an artifact. Path is relative to workspace root. */
112
+ read(path: string): Promise<string>;
113
+ /** Write an artifact atomically. Path is relative to workspace root. */
114
+ write(path: string, content: string): Promise<void>;
115
+ /** List artifacts matching a glob pattern. Returns paths relative to workspace root. */
116
+ list(pattern: string): Promise<string[]>;
117
+ /**
118
+ * Observe artifact changes. Level-triggered: existing matches are included immediately.
119
+ * Single-file pattern returns content string. Glob/expect>1 returns sorted array of {path, content}.
120
+ */
121
+ observe(pattern: string, options?: {
122
+ expect?: number;
123
+ timeout?: number;
124
+ }): Promise<ObserveResult>;
125
+ }
126
+ export interface ProgramResult {
127
+ status: "done" | "yielded" | "failed";
128
+ /** Yield reason, or error summary for failed. */
129
+ reason?: string;
130
+ /** From ctx.done(result), if provided. */
131
+ result?: unknown;
132
+ }
83
133
  export interface PiAdapterConfig {
84
134
  provider: string;
85
135
  model: string;
@@ -89,6 +139,8 @@ export interface RunOptions {
89
139
  maxRepairAttempts?: number;
90
140
  timeout?: number;
91
141
  args?: Record<string, unknown>;
142
+ /** Shared workspace directory. When set, workspace.* API is enabled for the program. */
143
+ workspaceDir?: string;
92
144
  }
93
145
  export interface RepairInput {
94
146
  programSource: string;
@@ -0,0 +1,2 @@
1
+ import type { Workspace } from "./types.js";
2
+ export declare function createWorkspace(workspaceDir: string, signal?: AbortSignal): Workspace;
@@ -0,0 +1,257 @@
1
+ import { readFileSync, writeFileSync, mkdirSync, readdirSync, readlinkSync, realpathSync, lstatSync, statSync, existsSync, renameSync, fdatasyncSync, openSync, closeSync, } from "fs";
2
+ import { resolve, dirname, relative, sep } from "path";
3
+ import { resolveBounded, verifyRealPath, verifyNearestAncestor, verifySymlink } from "./path-guard.js";
4
+ const OBSERVE_POLL_MS = 250;
5
+ /**
6
+ * Match a simple glob pattern against a relative path.
7
+ * Supports `*` (any segment chars), `?` (single char), and `**` (any path segments).
8
+ * `** /` matches zero or more directory segments (including root).
9
+ */
10
+ function matchGlob(pattern, filePath) {
11
+ // Replace ** with placeholders before escaping
12
+ let regex = pattern
13
+ .replace(/\*\*\//g, "\x00GLOBSTARSLASH\x00")
14
+ .replace(/\*\*/g, "\x00GLOBSTAR\x00");
15
+ // Escape regex special chars except * and ?
16
+ regex = regex
17
+ .replace(/[.+^${}()|[\]\\]/g, "\\$&")
18
+ .replace(/\*/g, "[^/]*")
19
+ .replace(/\?/g, "[^/]");
20
+ // Restore placeholders
21
+ regex = regex
22
+ .replace(/\x00GLOBSTARSLASH\x00/g, "(?:.+/)?")
23
+ .replace(/\x00GLOBSTAR\x00/g, ".*");
24
+ return new RegExp(`^${regex}$`).test(filePath);
25
+ }
26
+ /**
27
+ * Recursively list all files under a directory, returning paths relative to root.
28
+ * Includes symlinks to files and follows symlinked directories, but only if
29
+ * they resolve inside the bounded root (prevents symlink escapes).
30
+ *
31
+ * Cycle detection: only symlinked directories are tracked in the `visited` set
32
+ * (by their resolved realpath). Regular directories cannot create cycles on their
33
+ * own, so they are traversed unconditionally. This allows legitimate directory
34
+ * aliases (symlink pointing to another dir in the workspace) to produce their
35
+ * own workspace-relative paths alongside the original directory's paths.
36
+ */
37
+ function listFilesRecursive(dir, root, realRoot, visited) {
38
+ const seen = visited ?? new Set();
39
+ const results = [];
40
+ let entries;
41
+ try {
42
+ entries = readdirSync(dir, { withFileTypes: true });
43
+ }
44
+ catch {
45
+ return results;
46
+ }
47
+ for (const entry of entries) {
48
+ const full = resolve(dir, entry.name);
49
+ if (entry.isSymbolicLink()) {
50
+ // Verify symlink target is inside workspace root
51
+ let real;
52
+ try {
53
+ real = realpathSync(full);
54
+ }
55
+ catch {
56
+ continue; /* dangling symlink */
57
+ }
58
+ if (!real.startsWith(realRoot + sep) && real !== realRoot)
59
+ continue; // escapes workspace
60
+ try {
61
+ const stat = statSync(full);
62
+ if (stat.isDirectory()) {
63
+ // Cycle detection: only for symlinked directories
64
+ if (seen.has(real))
65
+ continue;
66
+ seen.add(real);
67
+ results.push(...listFilesRecursive(full, root, realRoot, seen));
68
+ }
69
+ else if (stat.isFile()) {
70
+ results.push(relative(root, full));
71
+ }
72
+ }
73
+ catch { /* stat failed */ }
74
+ }
75
+ else if (entry.isDirectory()) {
76
+ // Regular directories can't cause cycles — traverse unconditionally
77
+ results.push(...listFilesRecursive(full, root, realRoot, seen));
78
+ }
79
+ else if (entry.isFile()) {
80
+ results.push(relative(root, full));
81
+ }
82
+ }
83
+ return results;
84
+ }
85
+ /**
86
+ * Check if a pattern is a simple exact path (no glob characters).
87
+ */
88
+ function isExactPath(pattern) {
89
+ // Only check for glob chars that matchGlob actually supports: * and ?
90
+ // Characters like [ ] { } are not glob operators in our implementation
91
+ // and should be treated as literal filename characters.
92
+ return !/[*?]/.test(pattern);
93
+ }
94
+ export function createWorkspace(workspaceDir, signal) {
95
+ const normalizedDir = resolve(workspaceDir);
96
+ // Ensure workspace directory exists before resolving realpath
97
+ mkdirSync(normalizedDir, { recursive: true });
98
+ let realDir;
99
+ try {
100
+ realDir = realpathSync(normalizedDir);
101
+ }
102
+ catch {
103
+ realDir = normalizedDir;
104
+ }
105
+ const resolvePath = (p) => resolveBounded(normalizedDir, p);
106
+ const checkRealPath = (real, original) => verifyRealPath(real, realDir, original);
107
+ const checkNearestAncestor = (resolved, original) => verifyNearestAncestor(resolved, realDir, original);
108
+ return {
109
+ async read(path) {
110
+ const target = resolvePath(path);
111
+ let real;
112
+ try {
113
+ real = realpathSync(target);
114
+ }
115
+ catch (e) {
116
+ if (e.code === "ENOENT") {
117
+ throw new Error(`Workspace artifact not found: ${path}`);
118
+ }
119
+ throw e;
120
+ }
121
+ checkRealPath(real, path);
122
+ return readFileSync(target, "utf-8");
123
+ },
124
+ async write(path, content) {
125
+ const target = resolvePath(path);
126
+ checkNearestAncestor(target, path);
127
+ mkdirSync(dirname(target), { recursive: true });
128
+ // If target is a symlink, resolve to real path and write through it
129
+ // (matches tools.write behavior — write to the target, don't replace the link)
130
+ let writePath = target;
131
+ try {
132
+ if (lstatSync(target).isSymbolicLink()) {
133
+ verifySymlink(target, realDir, path);
134
+ try {
135
+ writePath = realpathSync(target);
136
+ }
137
+ catch (realErr) {
138
+ if (realErr.code !== "ENOENT")
139
+ throw realErr;
140
+ // Dangling symlink — resolve the link destination manually
141
+ writePath = resolve(dirname(target), readlinkSync(target));
142
+ mkdirSync(dirname(writePath), { recursive: true });
143
+ }
144
+ }
145
+ }
146
+ catch (e) {
147
+ if (e.code !== "ENOENT")
148
+ throw e;
149
+ }
150
+ // Atomic write: write to temp file in same directory, fsync, rename
151
+ const tmpFile = writePath + `.trama-tmp-${process.pid}-${Date.now()}`;
152
+ const fd = openSync(tmpFile, "w");
153
+ try {
154
+ writeFileSync(fd, content);
155
+ fdatasyncSync(fd);
156
+ }
157
+ finally {
158
+ closeSync(fd);
159
+ }
160
+ renameSync(tmpFile, writePath);
161
+ },
162
+ async list(pattern) {
163
+ const allFiles = listFilesRecursive(normalizedDir, normalizedDir, realDir);
164
+ // Normalize to forward slashes for matching
165
+ return allFiles
166
+ .map(f => f.split(sep).join("/"))
167
+ .filter(f => matchGlob(pattern, f))
168
+ .sort();
169
+ },
170
+ async observe(pattern, options = {}) {
171
+ const { expect, timeout } = options;
172
+ if (expect !== undefined && (!Number.isInteger(expect) || expect < 1)) {
173
+ throw new Error(`workspace.observe(): expect must be a positive integer (got ${expect})`);
174
+ }
175
+ if (timeout !== undefined && (!Number.isFinite(timeout) || timeout < 0)) {
176
+ throw new Error(`workspace.observe(): timeout must be a non-negative number (got ${timeout})`);
177
+ }
178
+ const isExact = isExactPath(pattern) && (expect === undefined || expect <= 1);
179
+ const startTime = Date.now();
180
+ const collectMatches = () => {
181
+ if (isExact) {
182
+ const target = resolvePath(pattern);
183
+ if (existsSync(target)) {
184
+ try {
185
+ const real = realpathSync(target);
186
+ checkRealPath(real, pattern);
187
+ return [{ path: pattern, content: readFileSync(target, "utf-8") }];
188
+ }
189
+ catch {
190
+ return [];
191
+ }
192
+ }
193
+ return [];
194
+ }
195
+ const allFiles = listFilesRecursive(normalizedDir, normalizedDir, realDir);
196
+ const matches = [];
197
+ for (const f of allFiles) {
198
+ const normalized = f.split(sep).join("/");
199
+ if (matchGlob(pattern, normalized)) {
200
+ const target = resolve(normalizedDir, f);
201
+ try {
202
+ const real = realpathSync(target);
203
+ checkRealPath(real, normalized);
204
+ matches.push({ path: normalized, content: readFileSync(target, "utf-8") });
205
+ }
206
+ catch {
207
+ // Skip files we can't read
208
+ }
209
+ }
210
+ }
211
+ return matches.sort((a, b) => a.path.localeCompare(b.path));
212
+ };
213
+ const neededCount = expect ?? 1;
214
+ // Poll until condition is met
215
+ while (true) {
216
+ if (signal?.aborted) {
217
+ throw new Error("workspace.observe() aborted");
218
+ }
219
+ const matches = collectMatches();
220
+ if (matches.length >= neededCount) {
221
+ // Return single string for exact single-file, array otherwise
222
+ if (isExact && neededCount <= 1) {
223
+ return matches[0].content;
224
+ }
225
+ return matches;
226
+ }
227
+ if (timeout !== undefined && (Date.now() - startTime) >= timeout) {
228
+ throw new Error(`workspace.observe("${pattern}") timed out after ${timeout}ms. ` +
229
+ `Found ${matches.length}/${neededCount} matching artifacts.`);
230
+ }
231
+ // Wait before polling again
232
+ await new Promise((resolve, reject) => {
233
+ let settled = false;
234
+ const onTimer = () => {
235
+ if (settled)
236
+ return;
237
+ settled = true;
238
+ if (signal)
239
+ signal.removeEventListener("abort", onAbort);
240
+ resolve();
241
+ };
242
+ const onAbort = () => {
243
+ if (settled)
244
+ return;
245
+ settled = true;
246
+ clearTimeout(timer);
247
+ reject(new Error("workspace.observe() aborted"));
248
+ };
249
+ const timer = setTimeout(onTimer, OBSERVE_POLL_MS);
250
+ if (signal) {
251
+ signal.addEventListener("abort", onAbort, { once: true });
252
+ }
253
+ });
254
+ }
255
+ },
256
+ };
257
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@trama-dev/runtime",
3
- "version": "0.1.3",
3
+ "version": "0.1.5",
4
4
  "type": "module",
5
5
  "exports": {
6
6
  ".": {