@trama-dev/runtime 0.1.5 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/workspace.js CHANGED
@@ -1,6 +1,6 @@
1
- import { readFileSync, writeFileSync, mkdirSync, readdirSync, readlinkSync, realpathSync, lstatSync, statSync, existsSync, renameSync, fdatasyncSync, openSync, closeSync, } from "fs";
1
+ import { readFileSync, writeFileSync, mkdirSync, readdirSync, readlinkSync, realpathSync, lstatSync, statSync, renameSync, fdatasyncSync, openSync, closeSync, } from "fs";
2
2
  import { resolve, dirname, relative, sep } from "path";
3
- import { resolveBounded, verifyRealPath, verifyNearestAncestor, verifySymlink } from "./path-guard.js";
3
+ import { guardPath, isInside, realRootOf, resolveBounded } from "./path-guard.js";
4
4
  const OBSERVE_POLL_MS = 250;
5
5
  /**
6
6
  * Match a simple glob pattern against a relative path.
@@ -24,7 +24,14 @@ function matchGlob(pattern, filePath) {
24
24
  return new RegExp(`^${regex}$`).test(filePath);
25
25
  }
26
26
  /**
27
- * Recursively list all files under a directory, returning paths relative to root.
27
+ * A pattern with no glob operators names exactly one artifact.
28
+ * Only `*` and `?` are operators here — `[ ] { }` are literal filename characters.
29
+ */
30
+ function isExactPath(pattern) {
31
+ return !/[*?]/.test(pattern);
32
+ }
33
+ /**
34
+ * Recursively list all files under a directory, as forward-slash paths relative to root.
28
35
  * Includes symlinks to files and follows symlinked directories, but only if
29
36
  * they resolve inside the bounded root (prevents symlink escapes).
30
37
  *
@@ -34,8 +41,7 @@ function matchGlob(pattern, filePath) {
34
41
  * aliases (symlink pointing to another dir in the workspace) to produce their
35
42
  * own workspace-relative paths alongside the original directory's paths.
36
43
  */
37
- function listFilesRecursive(dir, root, realRoot, visited) {
38
- const seen = visited ?? new Set();
44
+ function listFilesRecursive(dir, root, realRoot, visited = new Set()) {
39
45
  const results = [];
40
46
  let entries;
41
47
  try {
@@ -44,10 +50,10 @@ function listFilesRecursive(dir, root, realRoot, visited) {
44
50
  catch {
45
51
  return results;
46
52
  }
53
+ const addFile = (full) => results.push(relative(root, full).split(sep).join("/"));
47
54
  for (const entry of entries) {
48
55
  const full = resolve(dir, entry.name);
49
56
  if (entry.isSymbolicLink()) {
50
- // Verify symlink target is inside workspace root
51
57
  let real;
52
58
  try {
53
59
  real = realpathSync(full);
@@ -55,88 +61,87 @@ function listFilesRecursive(dir, root, realRoot, visited) {
55
61
  catch {
56
62
  continue; /* dangling symlink */
57
63
  }
58
- if (!real.startsWith(realRoot + sep) && real !== realRoot)
64
+ if (!isInside(real, realRoot))
59
65
  continue; // escapes workspace
60
66
  try {
61
67
  const stat = statSync(full);
62
68
  if (stat.isDirectory()) {
63
- // Cycle detection: only for symlinked directories
64
- if (seen.has(real))
69
+ if (visited.has(real))
65
70
  continue;
66
- seen.add(real);
67
- results.push(...listFilesRecursive(full, root, realRoot, seen));
71
+ visited.add(real);
72
+ results.push(...listFilesRecursive(full, root, realRoot, visited));
68
73
  }
69
74
  else if (stat.isFile()) {
70
- results.push(relative(root, full));
75
+ addFile(full);
71
76
  }
72
77
  }
73
78
  catch { /* stat failed */ }
74
79
  }
75
80
  else if (entry.isDirectory()) {
76
- // Regular directories can't cause cycles — traverse unconditionally
77
- results.push(...listFilesRecursive(full, root, realRoot, seen));
81
+ results.push(...listFilesRecursive(full, root, realRoot, visited));
78
82
  }
79
83
  else if (entry.isFile()) {
80
- results.push(relative(root, full));
84
+ addFile(full);
81
85
  }
82
86
  }
83
87
  return results;
84
88
  }
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);
89
+ /** Resolve after `ms`, or reject as soon as `signal` aborts. */
90
+ function sleep(ms, signal) {
91
+ return new Promise((resolve, reject) => {
92
+ const onAbort = () => {
93
+ clearTimeout(timer);
94
+ reject(new Error("workspace.observe() aborted"));
95
+ };
96
+ const timer = setTimeout(() => {
97
+ signal?.removeEventListener("abort", onAbort);
98
+ resolve();
99
+ }, ms);
100
+ signal?.addEventListener("abort", onAbort, { once: true });
101
+ });
93
102
  }
94
103
  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);
104
+ const root = resolve(workspaceDir);
105
+ mkdirSync(root, { recursive: true });
106
+ const realRoot = realRootOf(root);
107
+ /** All artifact paths matching a glob, sorted. */
108
+ const listMatching = (pattern) => listFilesRecursive(root, root, realRoot).filter(f => matchGlob(pattern, f)).sort();
109
+ /** Read an artifact, or null if it is missing, unreadable, or escapes the workspace. */
110
+ const readIfPresent = (path) => {
111
+ try {
112
+ return readFileSync(guardPath(root, path), "utf-8");
113
+ }
114
+ catch {
115
+ return null;
116
+ }
117
+ };
108
118
  return {
109
119
  async read(path) {
110
- const target = resolvePath(path);
111
- let real;
120
+ const target = guardPath(root, path);
112
121
  try {
113
- real = realpathSync(target);
122
+ return readFileSync(target, "utf-8");
114
123
  }
115
124
  catch (e) {
116
- if (e.code === "ENOENT") {
125
+ if (e.code === "ENOENT")
117
126
  throw new Error(`Workspace artifact not found: ${path}`);
118
- }
119
127
  throw e;
120
128
  }
121
- checkRealPath(real, path);
122
- return readFileSync(target, "utf-8");
123
129
  },
124
130
  async write(path, content) {
125
- const target = resolvePath(path);
126
- checkNearestAncestor(target, path);
131
+ const target = guardPath(root, path);
127
132
  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)
133
+ // If the target is a symlink, write to what it points at rather than
134
+ // replacing the link (matches tools.write). guardPath has already
135
+ // verified the destination stays inside the workspace.
130
136
  let writePath = target;
131
137
  try {
132
138
  if (lstatSync(target).isSymbolicLink()) {
133
- verifySymlink(target, realDir, path);
134
139
  try {
135
140
  writePath = realpathSync(target);
136
141
  }
137
- catch (realErr) {
138
- if (realErr.code !== "ENOENT")
139
- throw realErr;
142
+ catch (e) {
143
+ if (e.code !== "ENOENT")
144
+ throw e;
140
145
  // Dangling symlink — resolve the link destination manually
141
146
  writePath = resolve(dirname(target), readlinkSync(target));
142
147
  mkdirSync(dirname(writePath), { recursive: true });
@@ -147,7 +152,8 @@ export function createWorkspace(workspaceDir, signal) {
147
152
  if (e.code !== "ENOENT")
148
153
  throw e;
149
154
  }
150
- // Atomic write: write to temp file in same directory, fsync, rename
155
+ // Atomic write: temp file in the same directory, fsync, rename.
156
+ // Readers see either the old content or the new — never a partial file.
151
157
  const tmpFile = writePath + `.trama-tmp-${process.pid}-${Date.now()}`;
152
158
  const fd = openSync(tmpFile, "w");
153
159
  try {
@@ -160,12 +166,7 @@ export function createWorkspace(workspaceDir, signal) {
160
166
  renameSync(tmpFile, writePath);
161
167
  },
162
168
  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
+ return listMatching(pattern);
169
170
  },
170
171
  async observe(pattern, options = {}) {
171
172
  const { expect, timeout } = options;
@@ -175,82 +176,33 @@ export function createWorkspace(workspaceDir, signal) {
175
176
  if (timeout !== undefined && (!Number.isFinite(timeout) || timeout < 0)) {
176
177
  throw new Error(`workspace.observe(): timeout must be a non-negative number (got ${timeout})`);
177
178
  }
178
- const isExact = isExactPath(pattern) && (expect === undefined || expect <= 1);
179
- const startTime = Date.now();
179
+ const needed = expect ?? 1;
180
+ // One exact path, one artifact wanted → the caller gets its content as a string.
181
+ const single = isExactPath(pattern) && needed === 1;
182
+ if (single)
183
+ resolveBounded(root, pattern); // reject traversal up front rather than polling forever
180
184
  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
185
  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
- }
186
+ for (const path of single ? [pattern] : listMatching(pattern)) {
187
+ const content = readIfPresent(path);
188
+ if (content !== null)
189
+ matches.push({ path, content });
210
190
  }
211
- return matches.sort((a, b) => a.path.localeCompare(b.path));
191
+ return matches;
212
192
  };
213
- const neededCount = expect ?? 1;
214
- // Poll until condition is met
193
+ // Level-triggered: artifacts that already exist count immediately.
194
+ const startTime = Date.now();
215
195
  while (true) {
216
- if (signal?.aborted) {
196
+ if (signal?.aborted)
217
197
  throw new Error("workspace.observe() aborted");
218
- }
219
198
  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
- }
199
+ if (matches.length >= needed)
200
+ return single ? matches[0].content : matches;
227
201
  if (timeout !== undefined && (Date.now() - startTime) >= timeout) {
228
202
  throw new Error(`workspace.observe("${pattern}") timed out after ${timeout}ms. ` +
229
- `Found ${matches.length}/${neededCount} matching artifacts.`);
203
+ `Found ${matches.length}/${needed} matching artifacts.`);
230
204
  }
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
- });
205
+ await sleep(OBSERVE_POLL_MS, signal);
254
206
  }
255
207
  },
256
208
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@trama-dev/runtime",
3
- "version": "0.1.5",
3
+ "version": "0.2.0",
4
4
  "type": "module",
5
5
  "exports": {
6
6
  ".": {
@@ -33,9 +33,11 @@
33
33
  "LICENSE"
34
34
  ],
35
35
  "os": ["darwin", "linux"],
36
+ "engines": {
37
+ "node": ">=22.19.0"
38
+ },
36
39
  "dependencies": {
37
- "@mariozechner/pi-coding-agent": "0.64.0",
38
- "@mariozechner/pi-ai": "0.64.0",
39
- "tsx": "^4.21.0"
40
+ "@earendil-works/pi-coding-agent": "1.5.2",
41
+ "tsx": "^4.23.15"
40
42
  }
41
43
  }