@trama-dev/runtime 0.1.4 → 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/README.md +4 -4
- package/dist/agent.js +3 -3
- package/dist/child-process.d.ts +40 -0
- package/dist/child-process.js +108 -0
- package/dist/client.d.ts +2 -1
- package/dist/client.js +52 -53
- package/dist/context.d.ts +11 -0
- package/dist/context.js +62 -17
- package/dist/index.d.ts +3 -0
- package/dist/index.js +39 -59
- package/dist/ipc-server.d.ts +22 -0
- package/dist/ipc-server.js +168 -0
- package/dist/path-guard.d.ts +16 -26
- package/dist/path-guard.js +42 -37
- package/dist/pi-adapter.d.ts +11 -2
- package/dist/pi-adapter.js +49 -6
- package/dist/runner-types.d.ts +29 -0
- package/dist/runner-types.js +3 -0
- package/dist/runner.d.ts +58 -21
- package/dist/runner.js +426 -674
- package/dist/tools.d.ts +3 -5
- package/dist/tools.js +70 -166
- package/dist/types.d.ts +35 -29
- package/dist/types.js +4 -1
- package/dist/workspace.d.ts +2 -0
- package/dist/workspace.js +209 -0
- package/package.json +6 -4
package/dist/tools.d.ts
CHANGED
|
@@ -1,10 +1,8 @@
|
|
|
1
1
|
import type { Tools } from "./types.js";
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
readonly value: string;
|
|
5
|
-
};
|
|
2
|
+
import { cappedBuffer } from "./child-process.js";
|
|
3
|
+
export { cappedBuffer };
|
|
6
4
|
export interface ToolsWithCleanup extends Tools {
|
|
7
|
-
/** Kill
|
|
5
|
+
/** Kill every shell command still running, and anything they left in the background. */
|
|
8
6
|
killActiveShells(): void;
|
|
9
7
|
}
|
|
10
8
|
export declare function createTools(projectDir: string, signal?: AbortSignal): ToolsWithCleanup;
|
package/dist/tools.js
CHANGED
|
@@ -1,194 +1,98 @@
|
|
|
1
1
|
import { spawn } from "child_process";
|
|
2
|
-
import { readFileSync, writeFileSync, mkdirSync
|
|
2
|
+
import { readFileSync, writeFileSync, mkdirSync } from "fs";
|
|
3
3
|
import { resolve, dirname } from "path";
|
|
4
|
-
import {
|
|
5
|
-
import {
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
return {
|
|
11
|
-
append(text) {
|
|
12
|
-
if (capped)
|
|
13
|
-
return;
|
|
14
|
-
buf += text;
|
|
15
|
-
if (buf.length > MAX_OUTPUT) {
|
|
16
|
-
buf = buf.slice(0, MAX_OUTPUT) + "\n[trama] output truncated at 10MB";
|
|
17
|
-
capped = true;
|
|
18
|
-
}
|
|
19
|
-
},
|
|
20
|
-
get value() { return buf; },
|
|
21
|
-
};
|
|
22
|
-
}
|
|
4
|
+
import { guardPath } from "./path-guard.js";
|
|
5
|
+
import { cappedBuffer, signalGroup, superviseChild } from "./child-process.js";
|
|
6
|
+
export { cappedBuffer };
|
|
7
|
+
const MAX_FETCH_BODY = 10 * 1024 * 1024; // 10 MB
|
|
8
|
+
const DEFAULT_SHELL_TIMEOUT = 30_000;
|
|
9
|
+
const GROUP_SWEEP_MS = 250;
|
|
23
10
|
export function createTools(projectDir, signal) {
|
|
24
11
|
const normalizedProjectDir = resolve(projectDir);
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
const
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
const timer = sessionReapers.get(sessionId);
|
|
37
|
-
if (timer) {
|
|
38
|
-
clearTimeout(timer);
|
|
39
|
-
sessionReapers.delete(sessionId);
|
|
40
|
-
}
|
|
12
|
+
// Each shell command leads its own process group, so background processes it
|
|
13
|
+
// starts stay killable after the shell itself exits. A group is tracked from
|
|
14
|
+
// spawn until it has no members left; `true` marks groups whose shell has
|
|
15
|
+
// exited — only those are probed, since a group that is still starting up
|
|
16
|
+
// may not be visible yet.
|
|
17
|
+
const groups = new Map();
|
|
18
|
+
let sweeper = null;
|
|
19
|
+
const stopSweeping = () => {
|
|
20
|
+
if (sweeper)
|
|
21
|
+
clearInterval(sweeper);
|
|
22
|
+
sweeper = null;
|
|
41
23
|
};
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
24
|
+
/** Forget groups that have fully exited, so a recycled pid is never signalled. */
|
|
25
|
+
const sweep = () => {
|
|
26
|
+
let pending = false;
|
|
27
|
+
for (const [pgid, shellExited] of groups) {
|
|
28
|
+
if (!shellExited)
|
|
29
|
+
continue;
|
|
30
|
+
if (signalGroup(pgid, 0))
|
|
31
|
+
pending = true;
|
|
32
|
+
else
|
|
33
|
+
groups.delete(pgid);
|
|
45
34
|
}
|
|
46
|
-
|
|
35
|
+
if (!pending)
|
|
36
|
+
stopSweeping();
|
|
47
37
|
};
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
}
|
|
57
|
-
catch {
|
|
58
|
-
// ESRCH — process group gone
|
|
59
|
-
activeSessions.delete(sessionId);
|
|
60
|
-
sessionReapers.delete(sessionId);
|
|
61
|
-
return;
|
|
62
|
-
}
|
|
63
|
-
reapSessionWhenGone(sessionId);
|
|
64
|
-
}, 250);
|
|
65
|
-
timer.unref?.();
|
|
66
|
-
sessionReapers.set(sessionId, timer);
|
|
38
|
+
const markShellExited = (pgid) => {
|
|
39
|
+
if (!groups.has(pgid))
|
|
40
|
+
return; // already killed by killActiveShells
|
|
41
|
+
groups.set(pgid, true);
|
|
42
|
+
if (!sweeper) {
|
|
43
|
+
sweeper = setInterval(sweep, GROUP_SWEEP_MS);
|
|
44
|
+
sweeper.unref();
|
|
45
|
+
}
|
|
67
46
|
};
|
|
68
|
-
const resolvePath = (p) => resolveBounded(normalizedProjectDir, p);
|
|
69
|
-
const checkRealPath = (real, original) => verifyRealPath(real, realProjectDir, original);
|
|
70
|
-
const checkNearestAncestor = (resolved, original) => verifyNearestAncestor(resolved, realProjectDir, original);
|
|
71
47
|
return {
|
|
72
48
|
killActiveShells() {
|
|
73
|
-
for (const
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
}
|
|
78
|
-
catch { /* already exited */ }
|
|
79
|
-
}
|
|
80
|
-
}
|
|
81
|
-
for (const sessionId of activeSessions) {
|
|
82
|
-
killSession(sessionId, "SIGKILL");
|
|
83
|
-
stopReapingSession(sessionId);
|
|
84
|
-
}
|
|
85
|
-
activeShells.clear();
|
|
86
|
-
activeSessions.clear();
|
|
49
|
+
for (const pgid of groups.keys())
|
|
50
|
+
signalGroup(pgid, "SIGKILL");
|
|
51
|
+
groups.clear();
|
|
52
|
+
stopSweeping();
|
|
87
53
|
},
|
|
88
54
|
async read(path) {
|
|
89
|
-
const target =
|
|
90
|
-
let real;
|
|
55
|
+
const target = guardPath(normalizedProjectDir, path);
|
|
91
56
|
try {
|
|
92
|
-
|
|
57
|
+
return readFileSync(target, "utf-8");
|
|
93
58
|
}
|
|
94
59
|
catch (e) {
|
|
95
|
-
if (e.code === "ENOENT")
|
|
60
|
+
if (e.code === "ENOENT")
|
|
96
61
|
throw new Error(`File not found: ${path}`);
|
|
97
|
-
}
|
|
98
62
|
throw e;
|
|
99
63
|
}
|
|
100
|
-
checkRealPath(real, path);
|
|
101
|
-
return readFileSync(target, "utf-8");
|
|
102
64
|
},
|
|
103
65
|
async write(path, content) {
|
|
104
|
-
const target =
|
|
105
|
-
checkNearestAncestor(target, path); // before mkdir — prevents side effects outside project
|
|
66
|
+
const target = guardPath(normalizedProjectDir, path); // before mkdir — no side effects outside the project
|
|
106
67
|
mkdirSync(dirname(target), { recursive: true });
|
|
107
|
-
try {
|
|
108
|
-
if (lstatSync(target).isSymbolicLink()) {
|
|
109
|
-
verifySymlink(target, realProjectDir, path);
|
|
110
|
-
}
|
|
111
|
-
}
|
|
112
|
-
catch (e) {
|
|
113
|
-
if (e.code !== "ENOENT")
|
|
114
|
-
throw e;
|
|
115
|
-
}
|
|
116
68
|
writeFileSync(target, content);
|
|
117
69
|
},
|
|
118
70
|
async shell(command, options = {}) {
|
|
119
|
-
const
|
|
120
|
-
const
|
|
71
|
+
const cwd = options.cwd ? guardPath(normalizedProjectDir, options.cwd) : normalizedProjectDir;
|
|
72
|
+
const child = spawn("sh", ["-c", command], {
|
|
73
|
+
cwd,
|
|
74
|
+
stdio: ["pipe", "pipe", "pipe"],
|
|
75
|
+
detached: true,
|
|
76
|
+
});
|
|
77
|
+
const pgid = child.pid;
|
|
78
|
+
if (pgid)
|
|
79
|
+
groups.set(pgid, false);
|
|
121
80
|
try {
|
|
122
|
-
|
|
123
|
-
|
|
81
|
+
const exit = await superviseChild(child, { timeout: options.timeout ?? DEFAULT_SHELL_TIMEOUT });
|
|
82
|
+
if (pgid)
|
|
83
|
+
markShellExited(pgid);
|
|
84
|
+
return {
|
|
85
|
+
exitCode: exit.timedOut ? 1 : (exit.code ?? 1),
|
|
86
|
+
stdout: exit.stdout,
|
|
87
|
+
stderr: exit.timedOut ? exit.stderr + "\ntimeout" : exit.stderr,
|
|
88
|
+
};
|
|
124
89
|
}
|
|
125
|
-
catch (
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
90
|
+
catch (spawnError) {
|
|
91
|
+
// Failed to start (e.g. cwd does not exist) — a result, not an exception.
|
|
92
|
+
if (pgid)
|
|
93
|
+
groups.delete(pgid);
|
|
94
|
+
return { exitCode: 1, stdout: "", stderr: spawnError.message };
|
|
129
95
|
}
|
|
130
|
-
return new Promise((resolve) => {
|
|
131
|
-
const child = spawn("sh", ["-c", command], {
|
|
132
|
-
cwd,
|
|
133
|
-
stdio: ["pipe", "pipe", "pipe"],
|
|
134
|
-
detached: true,
|
|
135
|
-
});
|
|
136
|
-
activeShells.add(child);
|
|
137
|
-
if (child.pid)
|
|
138
|
-
activeSessions.add(child.pid);
|
|
139
|
-
const out = cappedBuffer();
|
|
140
|
-
const err = cappedBuffer();
|
|
141
|
-
const outDecoder = new StringDecoder("utf-8");
|
|
142
|
-
const errDecoder = new StringDecoder("utf-8");
|
|
143
|
-
let timedOut = false;
|
|
144
|
-
let exited = false;
|
|
145
|
-
let killFallbackTimer = null;
|
|
146
|
-
child.stdout.on("data", (chunk) => { out.append(outDecoder.write(chunk)); });
|
|
147
|
-
child.stderr.on("data", (chunk) => { err.append(errDecoder.write(chunk)); });
|
|
148
|
-
const timer = setTimeout(() => {
|
|
149
|
-
timedOut = true;
|
|
150
|
-
if (child.pid) {
|
|
151
|
-
killSession(child.pid, "SIGTERM");
|
|
152
|
-
}
|
|
153
|
-
killFallbackTimer = setTimeout(() => {
|
|
154
|
-
if (!exited && child.pid) {
|
|
155
|
-
killSession(child.pid, "SIGKILL");
|
|
156
|
-
}
|
|
157
|
-
}, 5000);
|
|
158
|
-
killFallbackTimer.unref?.();
|
|
159
|
-
}, timeout);
|
|
160
|
-
child.on("error", (spawnError) => {
|
|
161
|
-
clearTimeout(timer);
|
|
162
|
-
if (killFallbackTimer)
|
|
163
|
-
clearTimeout(killFallbackTimer);
|
|
164
|
-
activeShells.delete(child);
|
|
165
|
-
if (child.pid) {
|
|
166
|
-
activeSessions.delete(child.pid);
|
|
167
|
-
stopReapingSession(child.pid);
|
|
168
|
-
}
|
|
169
|
-
resolve({ exitCode: 1, stdout: out.value, stderr: spawnError.message });
|
|
170
|
-
});
|
|
171
|
-
child.on("close", (code) => {
|
|
172
|
-
exited = true;
|
|
173
|
-
activeShells.delete(child);
|
|
174
|
-
clearTimeout(timer);
|
|
175
|
-
if (killFallbackTimer)
|
|
176
|
-
clearTimeout(killFallbackTimer);
|
|
177
|
-
if (child.pid)
|
|
178
|
-
reapSessionWhenGone(child.pid);
|
|
179
|
-
const outFlush = outDecoder.end();
|
|
180
|
-
const errFlush = errDecoder.end();
|
|
181
|
-
if (outFlush)
|
|
182
|
-
out.append(outFlush);
|
|
183
|
-
if (errFlush)
|
|
184
|
-
err.append(errFlush);
|
|
185
|
-
resolve({
|
|
186
|
-
exitCode: timedOut ? 1 : (code ?? 1),
|
|
187
|
-
stdout: out.value,
|
|
188
|
-
stderr: timedOut ? err.value + "\ntimeout" : err.value,
|
|
189
|
-
});
|
|
190
|
-
});
|
|
191
|
-
});
|
|
192
96
|
},
|
|
193
97
|
async fetch(url, options = {}) {
|
|
194
98
|
const response = await globalThis.fetch(url, {
|
|
@@ -198,8 +102,8 @@ export function createTools(projectDir, signal) {
|
|
|
198
102
|
signal,
|
|
199
103
|
});
|
|
200
104
|
const raw = await response.text();
|
|
201
|
-
const body = raw.length >
|
|
202
|
-
? raw.slice(0,
|
|
105
|
+
const body = raw.length > MAX_FETCH_BODY
|
|
106
|
+
? raw.slice(0, MAX_FETCH_BODY) + "\n[trama] response body truncated at 10MB"
|
|
203
107
|
: raw;
|
|
204
108
|
const headers = {};
|
|
205
109
|
response.headers.forEach((v, k) => { headers[k] = v; });
|
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,21 @@ export interface Ctx {
|
|
|
29
33
|
/** Persist current ctx.state to disk */
|
|
30
34
|
checkpoint(): Promise<void>;
|
|
31
35
|
/**
|
|
32
|
-
* Signal program completion. Persists state
|
|
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.
|
|
35
40
|
*/
|
|
36
41
|
done(result?: Record<string, unknown>): Promise<void>;
|
|
42
|
+
/**
|
|
43
|
+
* Cooperative suspension. Persists ctx.state with a yield marker and exits (logging is best-effort).
|
|
44
|
+
* The session layer (or manual `trama run`) re-runs the program when ready.
|
|
45
|
+
* The program resumes by reading its own ctx.state.
|
|
46
|
+
* Mutually exclusive with done() — throws if done() was already called.
|
|
47
|
+
* A done() or yield() that fails (e.g. on unserializable state) settles nothing:
|
|
48
|
+
* fix the problem and call either one.
|
|
49
|
+
*/
|
|
50
|
+
yield(reason: string): Promise<never>;
|
|
37
51
|
}
|
|
38
52
|
export interface Agent {
|
|
39
53
|
/**
|
|
@@ -44,10 +58,6 @@ export interface Agent {
|
|
|
44
58
|
instruct(prompt: string, options?: {
|
|
45
59
|
system?: string;
|
|
46
60
|
}): Promise<string>;
|
|
47
|
-
/** @deprecated Use instruct() instead. Alias kept for backwards compatibility. */
|
|
48
|
-
ask(prompt: string, options?: {
|
|
49
|
-
system?: string;
|
|
50
|
-
}): Promise<string>;
|
|
51
61
|
/**
|
|
52
62
|
* Structured LLM call. Returns typed object matching the provided schema.
|
|
53
63
|
* Supported schema value prefixes: "string", "number", "boolean".
|
|
@@ -85,28 +95,24 @@ export interface Tools {
|
|
|
85
95
|
headers: Record<string, string>;
|
|
86
96
|
}>;
|
|
87
97
|
}
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
}
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
}
|
|
108
|
-
export interface TramaConfig extends PiAdapterConfig {
|
|
109
|
-
maxRepairAttempts: number;
|
|
110
|
-
defaultTimeout: number;
|
|
111
|
-
defaultMaxIterations: number;
|
|
98
|
+
/** Result of workspace.observe(). Single-file returns content string; multi-file returns array. */
|
|
99
|
+
export type ObserveResult = string | Array<{
|
|
100
|
+
path: string;
|
|
101
|
+
content: string;
|
|
102
|
+
}>;
|
|
103
|
+
export interface Workspace {
|
|
104
|
+
/** Read an artifact. Path is relative to workspace root. */
|
|
105
|
+
read(path: string): Promise<string>;
|
|
106
|
+
/** Write an artifact atomically. Path is relative to workspace root. */
|
|
107
|
+
write(path: string, content: string): Promise<void>;
|
|
108
|
+
/** List artifacts matching a glob pattern. Returns paths relative to workspace root. */
|
|
109
|
+
list(pattern: string): Promise<string[]>;
|
|
110
|
+
/**
|
|
111
|
+
* Observe artifact changes. Level-triggered: existing matches are included immediately.
|
|
112
|
+
* Single-file pattern returns content string. Glob/expect>1 returns sorted array of {path, content}.
|
|
113
|
+
*/
|
|
114
|
+
observe(pattern: string, options?: {
|
|
115
|
+
expect?: number;
|
|
116
|
+
timeout?: number;
|
|
117
|
+
}): Promise<ObserveResult>;
|
|
112
118
|
}
|
package/dist/types.js
CHANGED
|
@@ -1,2 +1,5 @@
|
|
|
1
|
-
// @trama-dev/runtime
|
|
1
|
+
// The program-facing API: everything a program.ts can import from "@trama-dev/runtime".
|
|
2
|
+
// This file is the single source of truth for that API — its generated .d.ts is also
|
|
3
|
+
// what the LLM is shown when it writes or repairs a program, so the doc comments here
|
|
4
|
+
// are part of the prompt. Runner-side types live in runner-types.ts.
|
|
2
5
|
export {};
|
|
@@ -0,0 +1,209 @@
|
|
|
1
|
+
import { readFileSync, writeFileSync, mkdirSync, readdirSync, readlinkSync, realpathSync, lstatSync, statSync, renameSync, fdatasyncSync, openSync, closeSync, } from "fs";
|
|
2
|
+
import { resolve, dirname, relative, sep } from "path";
|
|
3
|
+
import { guardPath, isInside, realRootOf, resolveBounded } 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
|
+
* 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.
|
|
35
|
+
* Includes symlinks to files and follows symlinked directories, but only if
|
|
36
|
+
* they resolve inside the bounded root (prevents symlink escapes).
|
|
37
|
+
*
|
|
38
|
+
* Cycle detection: only symlinked directories are tracked in the `visited` set
|
|
39
|
+
* (by their resolved realpath). Regular directories cannot create cycles on their
|
|
40
|
+
* own, so they are traversed unconditionally. This allows legitimate directory
|
|
41
|
+
* aliases (symlink pointing to another dir in the workspace) to produce their
|
|
42
|
+
* own workspace-relative paths alongside the original directory's paths.
|
|
43
|
+
*/
|
|
44
|
+
function listFilesRecursive(dir, root, realRoot, visited = new Set()) {
|
|
45
|
+
const results = [];
|
|
46
|
+
let entries;
|
|
47
|
+
try {
|
|
48
|
+
entries = readdirSync(dir, { withFileTypes: true });
|
|
49
|
+
}
|
|
50
|
+
catch {
|
|
51
|
+
return results;
|
|
52
|
+
}
|
|
53
|
+
const addFile = (full) => results.push(relative(root, full).split(sep).join("/"));
|
|
54
|
+
for (const entry of entries) {
|
|
55
|
+
const full = resolve(dir, entry.name);
|
|
56
|
+
if (entry.isSymbolicLink()) {
|
|
57
|
+
let real;
|
|
58
|
+
try {
|
|
59
|
+
real = realpathSync(full);
|
|
60
|
+
}
|
|
61
|
+
catch {
|
|
62
|
+
continue; /* dangling symlink */
|
|
63
|
+
}
|
|
64
|
+
if (!isInside(real, realRoot))
|
|
65
|
+
continue; // escapes workspace
|
|
66
|
+
try {
|
|
67
|
+
const stat = statSync(full);
|
|
68
|
+
if (stat.isDirectory()) {
|
|
69
|
+
if (visited.has(real))
|
|
70
|
+
continue;
|
|
71
|
+
visited.add(real);
|
|
72
|
+
results.push(...listFilesRecursive(full, root, realRoot, visited));
|
|
73
|
+
}
|
|
74
|
+
else if (stat.isFile()) {
|
|
75
|
+
addFile(full);
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
catch { /* stat failed */ }
|
|
79
|
+
}
|
|
80
|
+
else if (entry.isDirectory()) {
|
|
81
|
+
results.push(...listFilesRecursive(full, root, realRoot, visited));
|
|
82
|
+
}
|
|
83
|
+
else if (entry.isFile()) {
|
|
84
|
+
addFile(full);
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
return results;
|
|
88
|
+
}
|
|
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
|
+
});
|
|
102
|
+
}
|
|
103
|
+
export function createWorkspace(workspaceDir, signal) {
|
|
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
|
+
};
|
|
118
|
+
return {
|
|
119
|
+
async read(path) {
|
|
120
|
+
const target = guardPath(root, path);
|
|
121
|
+
try {
|
|
122
|
+
return readFileSync(target, "utf-8");
|
|
123
|
+
}
|
|
124
|
+
catch (e) {
|
|
125
|
+
if (e.code === "ENOENT")
|
|
126
|
+
throw new Error(`Workspace artifact not found: ${path}`);
|
|
127
|
+
throw e;
|
|
128
|
+
}
|
|
129
|
+
},
|
|
130
|
+
async write(path, content) {
|
|
131
|
+
const target = guardPath(root, path);
|
|
132
|
+
mkdirSync(dirname(target), { recursive: true });
|
|
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.
|
|
136
|
+
let writePath = target;
|
|
137
|
+
try {
|
|
138
|
+
if (lstatSync(target).isSymbolicLink()) {
|
|
139
|
+
try {
|
|
140
|
+
writePath = realpathSync(target);
|
|
141
|
+
}
|
|
142
|
+
catch (e) {
|
|
143
|
+
if (e.code !== "ENOENT")
|
|
144
|
+
throw e;
|
|
145
|
+
// Dangling symlink — resolve the link destination manually
|
|
146
|
+
writePath = resolve(dirname(target), readlinkSync(target));
|
|
147
|
+
mkdirSync(dirname(writePath), { recursive: true });
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
catch (e) {
|
|
152
|
+
if (e.code !== "ENOENT")
|
|
153
|
+
throw e;
|
|
154
|
+
}
|
|
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.
|
|
157
|
+
const tmpFile = writePath + `.trama-tmp-${process.pid}-${Date.now()}`;
|
|
158
|
+
const fd = openSync(tmpFile, "w");
|
|
159
|
+
try {
|
|
160
|
+
writeFileSync(fd, content);
|
|
161
|
+
fdatasyncSync(fd);
|
|
162
|
+
}
|
|
163
|
+
finally {
|
|
164
|
+
closeSync(fd);
|
|
165
|
+
}
|
|
166
|
+
renameSync(tmpFile, writePath);
|
|
167
|
+
},
|
|
168
|
+
async list(pattern) {
|
|
169
|
+
return listMatching(pattern);
|
|
170
|
+
},
|
|
171
|
+
async observe(pattern, options = {}) {
|
|
172
|
+
const { expect, timeout } = options;
|
|
173
|
+
if (expect !== undefined && (!Number.isInteger(expect) || expect < 1)) {
|
|
174
|
+
throw new Error(`workspace.observe(): expect must be a positive integer (got ${expect})`);
|
|
175
|
+
}
|
|
176
|
+
if (timeout !== undefined && (!Number.isFinite(timeout) || timeout < 0)) {
|
|
177
|
+
throw new Error(`workspace.observe(): timeout must be a non-negative number (got ${timeout})`);
|
|
178
|
+
}
|
|
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
|
|
184
|
+
const collectMatches = () => {
|
|
185
|
+
const matches = [];
|
|
186
|
+
for (const path of single ? [pattern] : listMatching(pattern)) {
|
|
187
|
+
const content = readIfPresent(path);
|
|
188
|
+
if (content !== null)
|
|
189
|
+
matches.push({ path, content });
|
|
190
|
+
}
|
|
191
|
+
return matches;
|
|
192
|
+
};
|
|
193
|
+
// Level-triggered: artifacts that already exist count immediately.
|
|
194
|
+
const startTime = Date.now();
|
|
195
|
+
while (true) {
|
|
196
|
+
if (signal?.aborted)
|
|
197
|
+
throw new Error("workspace.observe() aborted");
|
|
198
|
+
const matches = collectMatches();
|
|
199
|
+
if (matches.length >= needed)
|
|
200
|
+
return single ? matches[0].content : matches;
|
|
201
|
+
if (timeout !== undefined && (Date.now() - startTime) >= timeout) {
|
|
202
|
+
throw new Error(`workspace.observe("${pattern}") timed out after ${timeout}ms. ` +
|
|
203
|
+
`Found ${matches.length}/${needed} matching artifacts.`);
|
|
204
|
+
}
|
|
205
|
+
await sleep(OBSERVE_POLL_MS, signal);
|
|
206
|
+
}
|
|
207
|
+
},
|
|
208
|
+
};
|
|
209
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@trama-dev/runtime",
|
|
3
|
-
"version": "0.
|
|
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
|
-
"@
|
|
38
|
-
"
|
|
39
|
-
"tsx": "^4.21.0"
|
|
40
|
+
"@earendil-works/pi-coding-agent": "1.5.2",
|
|
41
|
+
"tsx": "^4.23.15"
|
|
40
42
|
}
|
|
41
43
|
}
|