@trama-dev/runtime 0.1.0 → 0.1.2

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.
@@ -0,0 +1,8 @@
1
+ /**
2
+ * Recursively check that a value is strictly JSON-serializable.
3
+ * Throws TypeError with the path to the offending value.
4
+ *
5
+ * Uses a stack (ancestor chain) instead of a flat set so that shared-but-
6
+ * non-circular structures like { a: shared, b: shared } pass validation.
7
+ */
8
+ export declare function assertSerializable(value: unknown, path: string, ancestors?: Set<unknown>): void;
@@ -0,0 +1,40 @@
1
+ /**
2
+ * Recursively check that a value is strictly JSON-serializable.
3
+ * Throws TypeError with the path to the offending value.
4
+ *
5
+ * Uses a stack (ancestor chain) instead of a flat set so that shared-but-
6
+ * non-circular structures like { a: shared, b: shared } pass validation.
7
+ */
8
+ export function assertSerializable(value, path, ancestors = new Set()) {
9
+ if (value === null || typeof value === "string" || typeof value === "boolean") {
10
+ return;
11
+ }
12
+ if (typeof value === "number") {
13
+ if (!Number.isFinite(value)) {
14
+ throw new TypeError(`${path} is not JSON-serializable (${value})`);
15
+ }
16
+ return;
17
+ }
18
+ if (typeof value === "undefined" || typeof value === "function" || typeof value === "symbol" || typeof value === "bigint") {
19
+ throw new TypeError(`${path} is not JSON-serializable (${typeof value})`);
20
+ }
21
+ if (ancestors.has(value)) {
22
+ throw new TypeError(`${path} contains a circular reference`);
23
+ }
24
+ ancestors.add(value);
25
+ if (Array.isArray(value)) {
26
+ for (let i = 0; i < value.length; i++) {
27
+ assertSerializable(value[i], `${path}[${i}]`, ancestors);
28
+ }
29
+ ancestors.delete(value);
30
+ return;
31
+ }
32
+ if (Object.getPrototypeOf(value) !== Object.prototype) {
33
+ const name = value.constructor?.name ?? "unknown";
34
+ throw new TypeError(`${path} is not a plain object (${name})`);
35
+ }
36
+ for (const [k, v] of Object.entries(value)) {
37
+ assertSerializable(v, `${path}.${k}`, ancestors);
38
+ }
39
+ ancestors.delete(value);
40
+ }
package/dist/tools.d.ts CHANGED
@@ -1,6 +1,10 @@
1
1
  import type { Tools } from "./types.js";
2
+ export declare function cappedBuffer(): {
3
+ append(text: string): void;
4
+ readonly value: string;
5
+ };
2
6
  export interface ToolsWithCleanup extends Tools {
3
7
  /** Kill all in-flight shell processes. Called by runner on timeout/error. */
4
8
  killActiveShells(): void;
5
9
  }
6
- export declare function createTools(projectDir: string): ToolsWithCleanup;
10
+ export declare function createTools(projectDir: string, signal?: AbortSignal): ToolsWithCleanup;
package/dist/tools.js CHANGED
@@ -1,12 +1,73 @@
1
1
  import { spawn } from "child_process";
2
- import { readFileSync, writeFileSync, mkdirSync } from "fs";
2
+ import { readFileSync, writeFileSync, mkdirSync, realpathSync, readlinkSync, lstatSync, existsSync } from "fs";
3
3
  import { resolve, dirname, sep } from "path";
4
- export function createTools(projectDir) {
4
+ import { StringDecoder } from "string_decoder";
5
+ const MAX_OUTPUT = 10 * 1024 * 1024; // 10 MB
6
+ export function cappedBuffer() {
7
+ let buf = "";
8
+ let capped = false;
9
+ return {
10
+ append(text) {
11
+ if (capped)
12
+ return;
13
+ buf += text;
14
+ if (buf.length > MAX_OUTPUT) {
15
+ buf = buf.slice(0, MAX_OUTPUT) + "\n[trama] output truncated at 10MB";
16
+ capped = true;
17
+ }
18
+ },
19
+ get value() { return buf; },
20
+ };
21
+ }
22
+ export function createTools(projectDir, signal) {
5
23
  const normalizedProjectDir = resolve(projectDir);
24
+ let realProjectDir;
25
+ try {
26
+ realProjectDir = realpathSync(normalizedProjectDir);
27
+ }
28
+ catch {
29
+ realProjectDir = normalizedProjectDir;
30
+ }
6
31
  const activeShells = new Set();
32
+ const activeSessions = new Set();
33
+ const sessionReapers = new Map();
34
+ const stopReapingSession = (sessionId) => {
35
+ const timer = sessionReapers.get(sessionId);
36
+ if (timer) {
37
+ clearTimeout(timer);
38
+ sessionReapers.delete(sessionId);
39
+ }
40
+ };
41
+ const killSession = (sessionId, signal) => {
42
+ try {
43
+ process.kill(-sessionId, signal);
44
+ }
45
+ catch { /* already exited */ }
46
+ };
47
+ /** Poll until the process group is gone, then remove from tracking. */
48
+ const reapSessionWhenGone = (sessionId) => {
49
+ stopReapingSession(sessionId);
50
+ const timer = setTimeout(() => {
51
+ if (!activeSessions.has(sessionId))
52
+ return;
53
+ try {
54
+ process.kill(-sessionId, 0); // signal 0: check if process group still exists
55
+ }
56
+ catch {
57
+ // ESRCH — process group gone
58
+ activeSessions.delete(sessionId);
59
+ sessionReapers.delete(sessionId);
60
+ return;
61
+ }
62
+ reapSessionWhenGone(sessionId);
63
+ }, 250);
64
+ timer.unref?.();
65
+ sessionReapers.set(sessionId, timer);
66
+ };
7
67
  /**
8
- * Path traversal guard. Not a security sandbox — just a footgun guard.
9
- * Uses normalizedProjectDir + sep to prevent /tmp/foo-bar matching /tmp/foo.
68
+ * Path traversal guard. Checks both logical path (.. segments) and
69
+ * real path (symlinks) to prevent escaping the project directory.
70
+ * Not a security sandbox — just a footgun guard.
10
71
  */
11
72
  const resolvePath = (p) => {
12
73
  const resolved = resolve(normalizedProjectDir, p);
@@ -15,56 +76,143 @@ export function createTools(projectDir) {
15
76
  }
16
77
  return resolved;
17
78
  };
79
+ /** Verify that an existing path's real location is inside the project dir. */
80
+ const verifyRealPath = (real, original) => {
81
+ if (real !== realProjectDir && !real.startsWith(realProjectDir + sep)) {
82
+ throw new Error(`Path escapes project directory via symlink: ${original}`);
83
+ }
84
+ };
85
+ /**
86
+ * Walk up from `resolved` to find the deepest existing ancestor,
87
+ * then verify its real path is inside the project dir.
88
+ * This catches symlink escapes BEFORE any mkdir side effects.
89
+ */
90
+ const verifyNearestAncestor = (resolved, original) => {
91
+ let cur = resolved;
92
+ while (!existsSync(cur)) {
93
+ const parent = dirname(cur);
94
+ if (parent === cur)
95
+ return; // reached filesystem root — nothing to verify
96
+ cur = parent;
97
+ }
98
+ verifyRealPath(realpathSync(cur), original);
99
+ };
18
100
  return {
19
101
  killActiveShells() {
20
102
  for (const proc of activeShells) {
21
- proc.kill("SIGKILL");
103
+ if (proc.pid) {
104
+ try {
105
+ process.kill(-proc.pid, "SIGKILL");
106
+ }
107
+ catch { /* already exited */ }
108
+ }
109
+ }
110
+ for (const sessionId of activeSessions) {
111
+ killSession(sessionId, "SIGKILL");
112
+ stopReapingSession(sessionId);
22
113
  }
23
114
  activeShells.clear();
115
+ activeSessions.clear();
24
116
  },
25
117
  async read(path) {
26
- return readFileSync(resolvePath(path), "utf-8");
118
+ const target = resolvePath(path);
119
+ verifyRealPath(realpathSync(target), path);
120
+ return readFileSync(target, "utf-8");
27
121
  },
28
122
  async write(path, content) {
29
123
  const target = resolvePath(path);
124
+ verifyNearestAncestor(target, path); // before mkdir — prevents side effects outside project
30
125
  mkdirSync(dirname(target), { recursive: true });
126
+ try {
127
+ if (lstatSync(target).isSymbolicLink()) {
128
+ try {
129
+ verifyRealPath(realpathSync(target), path);
130
+ }
131
+ catch (e) {
132
+ if (e.code !== "ENOENT")
133
+ throw e;
134
+ // Dangling symlink — resolve what we can via nearest existing ancestor
135
+ verifyNearestAncestor(resolve(dirname(target), readlinkSync(target)), path);
136
+ }
137
+ }
138
+ }
139
+ catch (e) {
140
+ if (e.code !== "ENOENT")
141
+ throw e;
142
+ }
31
143
  writeFileSync(target, content);
32
144
  },
33
145
  async shell(command, options = {}) {
34
146
  const timeout = options.timeout ?? 30_000;
35
147
  const cwd = options.cwd ? resolvePath(options.cwd) : normalizedProjectDir;
148
+ try {
149
+ if (options.cwd)
150
+ verifyRealPath(realpathSync(cwd), options.cwd);
151
+ }
152
+ catch (err) {
153
+ if (err.code !== "ENOENT")
154
+ throw err;
155
+ // cwd doesn't exist — spawn will fail with ENOENT on its own
156
+ }
36
157
  return new Promise((resolve) => {
37
158
  const child = spawn("sh", ["-c", command], {
38
159
  cwd,
39
160
  stdio: ["pipe", "pipe", "pipe"],
161
+ detached: true,
40
162
  });
41
163
  activeShells.add(child);
42
- let stdout = "";
43
- let stderr = "";
164
+ if (child.pid)
165
+ activeSessions.add(child.pid);
166
+ const out = cappedBuffer();
167
+ const err = cappedBuffer();
168
+ const outDecoder = new StringDecoder("utf-8");
169
+ const errDecoder = new StringDecoder("utf-8");
44
170
  let timedOut = false;
45
171
  let exited = false;
46
- child.stdout.on("data", (chunk) => { stdout += chunk; });
47
- child.stderr.on("data", (chunk) => { stderr += chunk; });
48
- child.on("error", (err) => {
49
- activeShells.delete(child);
50
- resolve({ exitCode: 1, stdout, stderr: err.message });
51
- });
172
+ let killFallbackTimer = null;
173
+ child.stdout.on("data", (chunk) => { out.append(outDecoder.write(chunk)); });
174
+ child.stderr.on("data", (chunk) => { err.append(errDecoder.write(chunk)); });
52
175
  const timer = setTimeout(() => {
53
176
  timedOut = true;
54
- child.kill("SIGTERM");
55
- setTimeout(() => {
56
- if (!exited)
57
- child.kill("SIGKILL");
177
+ if (child.pid) {
178
+ killSession(child.pid, "SIGTERM");
179
+ }
180
+ killFallbackTimer = setTimeout(() => {
181
+ if (!exited && child.pid) {
182
+ killSession(child.pid, "SIGKILL");
183
+ }
58
184
  }, 5000);
185
+ killFallbackTimer.unref?.();
59
186
  }, timeout);
187
+ child.on("error", (spawnError) => {
188
+ clearTimeout(timer);
189
+ if (killFallbackTimer)
190
+ clearTimeout(killFallbackTimer);
191
+ activeShells.delete(child);
192
+ if (child.pid) {
193
+ activeSessions.delete(child.pid);
194
+ stopReapingSession(child.pid);
195
+ }
196
+ resolve({ exitCode: 1, stdout: out.value, stderr: spawnError.message });
197
+ });
60
198
  child.on("close", (code) => {
61
199
  exited = true;
62
200
  activeShells.delete(child);
63
201
  clearTimeout(timer);
202
+ if (killFallbackTimer)
203
+ clearTimeout(killFallbackTimer);
204
+ if (child.pid)
205
+ reapSessionWhenGone(child.pid);
206
+ const outFlush = outDecoder.end();
207
+ const errFlush = errDecoder.end();
208
+ if (outFlush)
209
+ out.append(outFlush);
210
+ if (errFlush)
211
+ err.append(errFlush);
64
212
  resolve({
65
213
  exitCode: timedOut ? 1 : (code ?? 1),
66
- stdout,
67
- stderr: timedOut ? stderr + "\ntimeout" : stderr,
214
+ stdout: out.value,
215
+ stderr: timedOut ? err.value + "\ntimeout" : err.value,
68
216
  });
69
217
  });
70
218
  });
@@ -74,8 +222,12 @@ export function createTools(projectDir) {
74
222
  method: options.method ?? "GET",
75
223
  headers: options.headers,
76
224
  body: options.body,
225
+ signal,
77
226
  });
78
- const body = await response.text();
227
+ const raw = await response.text();
228
+ const body = raw.length > MAX_OUTPUT
229
+ ? raw.slice(0, MAX_OUTPUT) + "\n[trama] response body truncated at 10MB"
230
+ : raw;
79
231
  const headers = {};
80
232
  response.headers.forEach((v, k) => { headers[k] = v; });
81
233
  return { status: response.status, body, headers };
package/dist/types.d.ts CHANGED
@@ -19,6 +19,12 @@ export interface Ctx {
19
19
  maxIterations: number;
20
20
  /** Write a structured log entry */
21
21
  log(message: string, data?: Record<string, unknown>): Promise<void>;
22
+ /**
23
+ * Signal that a long-running program has finished startup and is now serving.
24
+ * Used by smoke validation to distinguish "started successfully" from "completed".
25
+ * Idempotent: second call is a no-op.
26
+ */
27
+ ready(data?: Record<string, unknown>): Promise<void>;
22
28
  /** Persist current ctx.state to disk */
23
29
  checkpoint(): Promise<void>;
24
30
  /**
@@ -81,6 +87,7 @@ export interface RunOptions {
81
87
  projectDir: string;
82
88
  maxRepairAttempts?: number;
83
89
  timeout?: number;
90
+ args?: Record<string, unknown>;
84
91
  }
85
92
  export interface RepairInput {
86
93
  programSource: string;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@trama-dev/runtime",
3
- "version": "0.1.0",
3
+ "version": "0.1.2",
4
4
  "type": "module",
5
5
  "exports": {
6
6
  ".": {
@@ -33,8 +33,8 @@
33
33
  "LICENSE"
34
34
  ],
35
35
  "dependencies": {
36
- "@mariozechner/pi-coding-agent": "0.63.1",
37
- "@mariozechner/pi-ai": "0.63.1",
38
- "tsx": "^4.0.0"
36
+ "@mariozechner/pi-coding-agent": "0.64.0",
37
+ "@mariozechner/pi-ai": "0.64.0",
38
+ "tsx": "^4.21.0"
39
39
  }
40
40
  }