@trama-dev/runtime 0.1.4 → 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/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,6 +88,23 @@ 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
  };
84
109
  const instructImpl = (prompt, opts) => call("/agent/ask", { prompt, ...opts }).then(r => r.result);
85
110
  export const agent = {
@@ -93,3 +118,30 @@ export const tools = {
93
118
  shell: (cmd, opts) => call("/tools/shell", { command: cmd, ...opts }).then(r => r.result),
94
119
  fetch: (url, opts) => call("/tools/fetch", { url, ...opts }).then(r => r.result),
95
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
@@ -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
  }
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 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 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,10 +122,13 @@ 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 {
@@ -155,9 +159,19 @@ export interface Tools {
155
159
  }): Promise<{ status: number; body: string; headers: Record<string, string> }>;
156
160
  }
157
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
+
158
171
  export declare const ctx: Ctx;
159
172
  export declare const agent: Agent;
160
- export declare const tools: Tools;`;
173
+ export declare const tools: Tools;
174
+ export declare const workspace: Workspace;`;
161
175
  // --- Config & state loaders ---
162
176
  export function loadConfig() {
163
177
  const configPath = join(homedir(), ".trama", "config.json");
@@ -242,7 +256,7 @@ function validateIPC(data, fields) {
242
256
  }
243
257
  return null;
244
258
  }
245
- function createIPCServer(ctx, agentImpl, toolsImpl) {
259
+ function createIPCServer(ctx, agentImpl, toolsImpl, workspaceImpl, signalTracker) {
246
260
  return createServer((req, res) => {
247
261
  if (req.method !== "POST") {
248
262
  res.writeHead(405);
@@ -281,6 +295,11 @@ function createIPCServer(ctx, agentImpl, toolsImpl) {
281
295
  "/ctx/checkpoint": { state: "object" },
282
296
  "/ctx/log": { message: "string" },
283
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" },
284
303
  };
285
304
  const rules = req.url ? validationRules[req.url] : undefined;
286
305
  if (rules) {
@@ -350,9 +369,64 @@ function createIPCServer(ctx, agentImpl, toolsImpl) {
350
369
  assertSerializable(data.state, "ctx.state");
351
370
  ctx.state = data.state;
352
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);
353
405
  res.writeHead(200, { "Content-Type": "application/json" });
354
406
  res.end(JSON.stringify({ result: null }));
355
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;
356
430
  default:
357
431
  res.writeHead(404);
358
432
  res.end("Not found");
@@ -522,6 +596,109 @@ export function copyToHistory(projectDir, reason, detail) {
522
596
  appendFileSync(indexPath, JSON.stringify(entry) + "\n");
523
597
  }
524
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
+ }
525
702
  /**
526
703
  * Snapshot a directory, run fn, restore from snapshot if fn returns false
527
704
  * or if fn throws. Always cleans up the snapshot. Returns whatever fn returns.
@@ -584,7 +761,8 @@ async function repairWithTimeout(adapter, input, timeout, repairErrors) {
584
761
  * Returns the child process result — does NOT throw on non-zero exit.
585
762
  */
586
763
  async function runProgramOnce(options) {
587
- 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 };
588
766
  ensureProjectScaffold(projectDir);
589
767
  ensureRuntimeLink(projectDir);
590
768
  const abortController = new AbortController();
@@ -615,7 +793,8 @@ async function runProgramOnce(options) {
615
793
  writeFileSync(guardPath(projectDir, join("logs", "latest.jsonl")), "");
616
794
  const agentImpl = createAgent(adapter, signal);
617
795
  const toolsImpl = createTools(projectDir, signal);
618
- const server = createIPCServer(ctx, agentImpl, toolsImpl);
796
+ const workspaceImpl = workspaceDir ? createWorkspace(workspaceDir, signal) : null;
797
+ const server = createIPCServer(ctx, agentImpl, toolsImpl, workspaceImpl, signalTracker);
619
798
  // Infrastructure setup — errors here are NOT program bugs.
620
799
  let port;
621
800
  try {
@@ -636,6 +815,9 @@ async function runProgramOnce(options) {
636
815
  state: ctx.state,
637
816
  iteration: ctx.iteration,
638
817
  maxIterations: ctx.maxIterations,
818
+ workspace: workspaceDir ?? null,
819
+ resumed: ctx.resumed,
820
+ yieldReason: ctx.yieldReason,
639
821
  }));
640
822
  }
641
823
  finally {
@@ -721,28 +903,75 @@ async function runProgramOnce(options) {
721
903
  }
722
904
  catch { /* best-effort */ }
723
905
  }
724
- return result;
906
+ return { child: result, signals: signalTracker };
725
907
  }
726
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
+ }
727
952
  async function executeProgram(options) {
728
953
  const { projectDir, adapter, maxRepairAttempts, timeout, maxIterations } = options;
729
954
  mkdirSync(guardPath(projectDir, "history"), { recursive: true });
730
955
  mkdirSync(guardPath(projectDir, "logs"), { recursive: true });
731
956
  // Phase 1: Run in the real project directory.
732
- const result = await runProgramOnce({
957
+ const runResult = await runProgramOnce({
733
958
  projectDir, adapter, timeout, maxIterations,
734
959
  argsOverride: options.argsOverride,
735
960
  streamOutput: true,
736
961
  stopOnReady: options.stopOnReady,
962
+ workspaceDir: options.workspaceDir,
737
963
  });
738
- if (result.exitCode === 0)
739
- 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
740
969
  if (maxRepairAttempts === 0) {
741
- throw new Error(`Program failed (repair disabled): ${formatError(result)}`);
970
+ return { status: "failed", reason: `Program failed (repair disabled): ${formatError(runResult.child)}` };
742
971
  }
743
972
  // Phase 2: Repair loop — both LLM repair call and verification run
744
973
  // are fully isolated in temp dirs to prevent side effects on the real project.
745
- let lastError = formatError(result);
974
+ let lastError = formatError(runResult.child);
746
975
  const originalSource = readFileSync(guardPath(projectDir, "program.ts"), "utf-8");
747
976
  let currentSource = originalSource;
748
977
  const repairErrors = [];
@@ -756,51 +985,98 @@ async function executeProgram(options) {
756
985
  if (!fixed)
757
986
  return null;
758
987
  writeFileSync(guardPath(tempDir, "program.ts"), fixed);
759
- const verifyResult = await runProgramOnce({
760
- projectDir: tempDir, adapter: tempAdapter, timeout, maxIterations,
761
- argsOverride: options.argsOverride,
762
- stopOnReady: options.stopOnReady,
763
- });
764
- 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
+ }
765
1014
  });
766
1015
  if (!repairResult) {
767
- // Repair LLM call itself failed — don't re-run the same broken program.
768
- 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()}` };
769
1017
  }
770
- 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") {
771
1021
  // Repair verified in isolation — now run in the real project for actual output.
772
- // Snapshot first so we can restore cleanly if the real run fails.
773
- 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 () => {
774
1039
  writeFileSync(guardPath(projectDir, "program.ts"), repairResult.fixed);
775
1040
  const r = await runProgramOnce({
776
1041
  projectDir, adapter, timeout, maxIterations,
777
1042
  argsOverride: options.argsOverride,
778
1043
  streamOutput: true,
779
1044
  stopOnReady: options.stopOnReady,
1045
+ workspaceDir: realRerunWsDir ?? options.workspaceDir,
780
1046
  });
781
- 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 } };
782
1049
  });
783
- if (realResult.exitCode === 0) {
784
- // Bookkeeping is best-effort — program already succeeded and side effects
785
- // 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") {
786
1064
  try {
787
1065
  options.onRepair?.(attempt, maxRepairAttempts, lastError);
788
1066
  }
789
1067
  catch (bookkeepingErr) {
790
1068
  console.warn(`[trama] repair bookkeeping failed: ${bookkeepingErr instanceof Error ? bookkeepingErr.message : bookkeepingErr}`);
791
1069
  }
792
- return;
1070
+ return realSignal;
793
1071
  }
794
- // Passed in isolation but failed in real dir — project already restored by withSnapshot.
795
1072
  currentSource = repairResult.fixed;
796
- lastError = formatError(realResult);
1073
+ lastError = realSignal?.reason ?? formatError(realRun.child);
797
1074
  continue;
798
1075
  }
799
- // Repair produced broken code — update context for next attempt.
800
1076
  currentSource = repairResult.fixed;
801
- lastError = formatError(repairResult.verifyResult);
1077
+ lastError = formatError(repairResult.verifyResult.child);
802
1078
  }
803
- throw new Error(`Failed after ${maxRepairAttempts} repair attempts: ${lastError}${repairDetails()}`);
1079
+ return { status: "failed", reason: `Failed after ${maxRepairAttempts} repair attempts: ${lastError}${repairDetails()}` };
804
1080
  }
805
1081
  // --- Smoke run (used by create and update) ---
806
1082
  /** Copy new history entries from src to dst (appends only entries added after the shared prefix). */
@@ -831,7 +1107,7 @@ export async function smokeRunAndRepair(projectDir, adapter, reason, options) {
831
1107
  cpSync(projectDir, smokeDir, { recursive: true });
832
1108
  const smokeAdapter = adapter.withCwd(smokeDir);
833
1109
  try {
834
- await executeProgram({
1110
+ const smokeResult = await executeProgram({
835
1111
  projectDir: smokeDir,
836
1112
  adapter: smokeAdapter,
837
1113
  maxRepairAttempts: options?.maxRepairAttempts ?? 3,
@@ -844,6 +1120,9 @@ export async function smokeRunAndRepair(projectDir, adapter, reason, options) {
844
1120
  appendFileSync(guardPath(smokeDir, join("history", "index.jsonl")), JSON.stringify({ reason: `${reason}-repair`, timestamp: new Date().toISOString(), error }) + "\n");
845
1121
  },
846
1122
  });
1123
+ if (smokeResult.status === "failed") {
1124
+ throw new Error(`Program failed: ${smokeResult.reason}`);
1125
+ }
847
1126
  // Smoke passed — copy back program.ts (may have been repaired)
848
1127
  copyFileSync(guardPath(smokeDir, "program.ts"), guardPath(projectDir, "program.ts"));
849
1128
  }
@@ -878,13 +1157,14 @@ export async function runProgram(options) {
878
1157
  throw new Error(`Invalid maxRepairAttempts: ${maxRepairAttempts}. Must be a non-negative integer.`);
879
1158
  }
880
1159
  const adapter = new PiAdapter(config, projectDir);
881
- await executeProgram({
1160
+ return executeProgram({
882
1161
  projectDir,
883
1162
  adapter,
884
1163
  maxRepairAttempts,
885
1164
  timeout,
886
1165
  maxIterations,
887
1166
  argsOverride: options.args,
1167
+ workspaceDir: options.workspaceDir,
888
1168
  onRepair(attempt, max, error) {
889
1169
  // Log repair attempts (appends to already-open logs file)
890
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,11 +33,24 @@ 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
  /**
@@ -85,6 +102,34 @@ export interface Tools {
85
102
  headers: Record<string, string>;
86
103
  }>;
87
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
+ }
88
133
  export interface PiAdapterConfig {
89
134
  provider: string;
90
135
  model: string;
@@ -94,6 +139,8 @@ export interface RunOptions {
94
139
  maxRepairAttempts?: number;
95
140
  timeout?: number;
96
141
  args?: Record<string, unknown>;
142
+ /** Shared workspace directory. When set, workspace.* API is enabled for the program. */
143
+ workspaceDir?: string;
97
144
  }
98
145
  export interface RepairInput {
99
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.4",
3
+ "version": "0.1.5",
4
4
  "type": "module",
5
5
  "exports": {
6
6
  ".": {