@fabric-harness/sdk 6.8.0 → 6.9.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.
Files changed (91) hide show
  1. package/dist/agent.d.ts +5 -4
  2. package/dist/agent.d.ts.map +1 -1
  3. package/dist/agent.js +37 -18
  4. package/dist/agent.js.map +1 -1
  5. package/dist/dynamic-agent.d.ts +24 -19
  6. package/dist/dynamic-agent.d.ts.map +1 -1
  7. package/dist/dynamic-agent.js +402 -239
  8. package/dist/dynamic-agent.js.map +1 -1
  9. package/dist/error.d.ts +1 -1
  10. package/dist/error.d.ts.map +1 -1
  11. package/dist/error.js.map +1 -1
  12. package/dist/events.d.ts +5 -0
  13. package/dist/events.d.ts.map +1 -1
  14. package/dist/events.js.map +1 -1
  15. package/dist/index.d.ts +1 -1
  16. package/dist/index.d.ts.map +1 -1
  17. package/dist/index.js +1 -1
  18. package/dist/index.js.map +1 -1
  19. package/dist/local-process.d.ts +8 -0
  20. package/dist/local-process.d.ts.map +1 -0
  21. package/dist/local-process.js +61 -0
  22. package/dist/local-process.js.map +1 -0
  23. package/dist/loop.d.ts +5 -0
  24. package/dist/loop.d.ts.map +1 -1
  25. package/dist/loop.js +18 -3
  26. package/dist/loop.js.map +1 -1
  27. package/dist/model-id.d.ts +3 -0
  28. package/dist/model-id.d.ts.map +1 -0
  29. package/dist/model-id.js +5 -0
  30. package/dist/model-id.js.map +1 -0
  31. package/dist/model-pricing.d.ts.map +1 -1
  32. package/dist/model-pricing.js +18 -1
  33. package/dist/model-pricing.js.map +1 -1
  34. package/dist/model.d.ts.map +1 -1
  35. package/dist/model.js +39 -14
  36. package/dist/model.js.map +1 -1
  37. package/dist/observability.d.ts +3 -2
  38. package/dist/observability.d.ts.map +1 -1
  39. package/dist/observability.js +42 -17
  40. package/dist/observability.js.map +1 -1
  41. package/dist/otel-observer.d.ts +2 -2
  42. package/dist/otel-observer.d.ts.map +1 -1
  43. package/dist/otel-observer.js +109 -26
  44. package/dist/otel-observer.js.map +1 -1
  45. package/dist/otel.d.ts +4 -4
  46. package/dist/otel.d.ts.map +1 -1
  47. package/dist/otel.js +28 -24
  48. package/dist/otel.js.map +1 -1
  49. package/dist/persistent-agent.d.ts +6 -6
  50. package/dist/persistent-agent.d.ts.map +1 -1
  51. package/dist/persistent-agent.js +79 -47
  52. package/dist/persistent-agent.js.map +1 -1
  53. package/dist/pi-loop-runtime.d.ts +6 -0
  54. package/dist/pi-loop-runtime.d.ts.map +1 -1
  55. package/dist/pi-loop-runtime.js +44 -22
  56. package/dist/pi-loop-runtime.js.map +1 -1
  57. package/dist/policy.d.ts +3 -1
  58. package/dist/policy.d.ts.map +1 -1
  59. package/dist/policy.js +13 -1
  60. package/dist/policy.js.map +1 -1
  61. package/dist/sandbox.d.ts +12 -12
  62. package/dist/sandbox.d.ts.map +1 -1
  63. package/dist/sandbox.js +408 -246
  64. package/dist/sandbox.js.map +1 -1
  65. package/dist/session-stream-recovery.d.ts +21 -0
  66. package/dist/session-stream-recovery.d.ts.map +1 -0
  67. package/dist/session-stream-recovery.js +115 -0
  68. package/dist/session-stream-recovery.js.map +1 -0
  69. package/dist/session.d.ts.map +1 -1
  70. package/dist/session.js +126 -39
  71. package/dist/session.js.map +1 -1
  72. package/dist/skills.d.ts +3 -1
  73. package/dist/skills.d.ts.map +1 -1
  74. package/dist/skills.js +7 -2
  75. package/dist/skills.js.map +1 -1
  76. package/dist/strict.d.ts +1 -1
  77. package/dist/strict.d.ts.map +1 -1
  78. package/dist/strict.js +1 -1
  79. package/dist/strict.js.map +1 -1
  80. package/dist/telemetry.d.ts +1 -1
  81. package/dist/telemetry.d.ts.map +1 -1
  82. package/dist/telemetry.js +30 -26
  83. package/dist/telemetry.js.map +1 -1
  84. package/dist/tools.d.ts +4 -0
  85. package/dist/tools.d.ts.map +1 -1
  86. package/dist/tools.js +6 -3
  87. package/dist/tools.js.map +1 -1
  88. package/dist/types.d.ts +14 -0
  89. package/dist/types.d.ts.map +1 -1
  90. package/dist/types.js.map +1 -1
  91. package/package.json +7 -23
package/dist/sandbox.js CHANGED
@@ -1,11 +1,12 @@
1
- import { spawn } from 'node:child_process';
2
- import { Bash, InMemoryFs } from 'just-bash';
3
- import { createHash, randomUUID } from 'node:crypto';
4
- import { promises as fs } from 'node:fs';
5
- import { tmpdir } from 'node:os';
6
- import path from 'node:path';
7
- import { FabricError } from './error.js';
8
- import { assertLocalCommandConfined } from './local-confinement.js';
1
+ import { spawn } from "node:child_process";
2
+ import { Bash, InMemoryFs } from "just-bash";
3
+ import { createHash, randomUUID } from "node:crypto";
4
+ import { promises as fs } from "node:fs";
5
+ import { tmpdir } from "node:os";
6
+ import path from "node:path";
7
+ import { FabricError } from "./error.js";
8
+ import { assertLocalCommandConfined } from "./local-confinement.js";
9
+ import { LOCAL_PROCESS_SUPERVISOR } from "./local-process.js";
9
10
  /** Remediation-naming error for optional sandbox operations a backend does not implement. */
10
11
  function unsupportedSandboxOperation(operation, subject) {
11
12
  return new Error(`${subject} sandbox does not support ${operation}. Guard with sandbox.capabilities before calling, or use a sandbox backend that implements ${operation} (e.g. local or docker).`);
@@ -26,28 +27,28 @@ export function execSandboxCommand(sandbox, command, options = {}) {
26
27
  if (settled)
27
28
  return;
28
29
  returnedOnAbort = true;
29
- const error = new Error('Sandbox command aborted; the remote command may still be running. Its eventual settlement remains observable.');
30
- error.name = 'AbortError';
30
+ const error = new Error("Sandbox command aborted; the remote command may still be running. Its eventual settlement remains observable.");
31
+ error.name = "AbortError";
31
32
  reject(error);
32
33
  };
33
- options.signal?.addEventListener('abort', onAbort, { once: true });
34
+ options.signal?.addEventListener("abort", onAbort, { once: true });
34
35
  if (options.signal?.aborted)
35
36
  onAbort();
36
37
  void operation.then(async (result) => {
37
38
  settled = true;
38
- options.signal?.removeEventListener('abort', onAbort);
39
+ options.signal?.removeEventListener("abort", onAbort);
39
40
  if (returnedOnAbort) {
40
- await options.onOrphanSettled?.({ status: 'fulfilled', exitCode: result.exitCode });
41
+ await options.onOrphanSettled?.({ status: "fulfilled", exitCode: result.exitCode });
41
42
  }
42
43
  else
43
44
  resolve(result);
44
45
  }, async (error) => {
45
46
  settled = true;
46
- options.signal?.removeEventListener('abort', onAbort);
47
+ options.signal?.removeEventListener("abort", onAbort);
47
48
  if (returnedOnAbort) {
48
49
  await options.onOrphanSettled?.({
49
- status: 'rejected',
50
- error: error instanceof Error ? error.name : 'Sandbox command rejected',
50
+ status: "rejected",
51
+ error: error instanceof Error ? error.name : "Sandbox command rejected",
51
52
  });
52
53
  }
53
54
  else
@@ -95,42 +96,84 @@ class ScopedSandboxEnv {
95
96
  capabilities;
96
97
  constructor(sandbox, cwd) {
97
98
  this.sandbox = sandbox;
98
- this.cwd = cwd.startsWith('/')
99
+ this.cwd = cwd.startsWith("/")
99
100
  ? sandbox.resolvePath(cwd)
100
101
  : sandbox.resolvePath(path.posix.join(sandbox.cwd, cwd));
101
102
  if (sandbox.capabilities !== undefined)
102
103
  this.capabilities = sandbox.capabilities;
103
104
  }
104
105
  exec(command, options = {}) {
105
- const execOptions = { ...options, cwd: options.cwd ? this.resolveScopedPath(options.cwd) : this.cwd };
106
+ const execOptions = {
107
+ ...options,
108
+ cwd: options.cwd ? this.resolveScopedPath(options.cwd) : this.cwd,
109
+ };
106
110
  return this.sandbox.exec(command, execOptions);
107
111
  }
108
- readFile(filePath) { return this.sandbox.readFile(this.resolveScopedPath(filePath)); }
109
- readFileBuffer(filePath) { return this.sandbox.readFileBuffer(this.resolveScopedPath(filePath)); }
110
- writeFile(filePath, content) { return this.sandbox.writeFile(this.resolveScopedPath(filePath), content); }
111
- stat(filePath) { return this.sandbox.stat(this.resolveScopedPath(filePath)); }
112
- readdir(dirPath) { return this.sandbox.readdir(this.resolveScopedPath(dirPath)); }
113
- exists(filePath) { return this.sandbox.exists(this.resolveScopedPath(filePath)); }
114
- mkdir(dirPath, options = {}) { return this.sandbox.mkdir(this.resolveScopedPath(dirPath), options); }
115
- rm(filePath, options = {}) { return this.sandbox.rm(this.resolveScopedPath(filePath), options); }
116
- resolvePath(filePath) { return this.sandbox.resolvePath(this.resolveScopedPath(filePath)); }
117
- snapshot() { if (!this.sandbox.snapshot)
118
- throw unsupportedSandboxOperation('snapshot', 'The configured'); return this.sandbox.snapshot(); }
119
- restore(snapshot) { if (!this.sandbox.restore)
120
- throw unsupportedSandboxOperation('restore', 'The configured'); return this.sandbox.restore(snapshot); }
121
- fork(snapshot) { if (!this.sandbox.fork)
122
- throw unsupportedSandboxOperation('fork', 'The configured'); return this.sandbox.fork(snapshot); }
123
- suspend() { if (!this.sandbox.suspend)
124
- throw unsupportedSandboxOperation('suspend', 'The configured'); return this.sandbox.suspend(); }
125
- resume() { if (!this.sandbox.resume)
126
- throw unsupportedSandboxOperation('resume', 'The configured'); return this.sandbox.resume(); }
127
- encodeRef() { return this.sandbox.encodeRef?.(); }
112
+ readFile(filePath) {
113
+ return this.sandbox.readFile(this.resolveScopedPath(filePath));
114
+ }
115
+ readFileBuffer(filePath) {
116
+ return this.sandbox.readFileBuffer(this.resolveScopedPath(filePath));
117
+ }
118
+ writeFile(filePath, content) {
119
+ return this.sandbox.writeFile(this.resolveScopedPath(filePath), content);
120
+ }
121
+ stat(filePath) {
122
+ return this.sandbox.stat(this.resolveScopedPath(filePath));
123
+ }
124
+ readdir(dirPath) {
125
+ return this.sandbox.readdir(this.resolveScopedPath(dirPath));
126
+ }
127
+ exists(filePath) {
128
+ return this.sandbox.exists(this.resolveScopedPath(filePath));
129
+ }
130
+ mkdir(dirPath, options = {}) {
131
+ return this.sandbox.mkdir(this.resolveScopedPath(dirPath), options);
132
+ }
133
+ rm(filePath, options = {}) {
134
+ return this.sandbox.rm(this.resolveScopedPath(filePath), options);
135
+ }
136
+ resolvePath(filePath) {
137
+ return this.sandbox.resolvePath(this.resolveScopedPath(filePath));
138
+ }
139
+ snapshot() {
140
+ if (!this.sandbox.snapshot)
141
+ throw unsupportedSandboxOperation("snapshot", "The configured");
142
+ return this.sandbox.snapshot();
143
+ }
144
+ restore(snapshot) {
145
+ if (!this.sandbox.restore)
146
+ throw unsupportedSandboxOperation("restore", "The configured");
147
+ return this.sandbox.restore(snapshot);
148
+ }
149
+ fork(snapshot) {
150
+ if (!this.sandbox.fork)
151
+ throw unsupportedSandboxOperation("fork", "The configured");
152
+ return this.sandbox.fork(snapshot);
153
+ }
154
+ suspend() {
155
+ if (!this.sandbox.suspend)
156
+ throw unsupportedSandboxOperation("suspend", "The configured");
157
+ return this.sandbox.suspend();
158
+ }
159
+ resume() {
160
+ if (!this.sandbox.resume)
161
+ throw unsupportedSandboxOperation("resume", "The configured");
162
+ return this.sandbox.resume();
163
+ }
164
+ encodeRef() {
165
+ return this.sandbox.encodeRef?.();
166
+ }
128
167
  __runWithPolicyApproval(call, operation) {
129
- return this.sandbox.__runWithPolicyApproval ? this.sandbox.__runWithPolicyApproval(call, operation) : operation();
168
+ return this.sandbox.__runWithPolicyApproval
169
+ ? this.sandbox.__runWithPolicyApproval(call, operation)
170
+ : operation();
171
+ }
172
+ cleanup() {
173
+ return this.sandbox.cleanup();
130
174
  }
131
- cleanup() { return this.sandbox.cleanup(); }
132
175
  resolveScopedPath(filePath) {
133
- if (filePath.startsWith('/'))
176
+ if (filePath.startsWith("/"))
134
177
  return this.sandbox.resolvePath(filePath);
135
178
  return this.sandbox.resolvePath(path.posix.join(this.cwd, filePath));
136
179
  }
@@ -143,23 +186,23 @@ class RemoteSandboxEnv {
143
186
  constructor(api, options) {
144
187
  this.api = api;
145
188
  this.options = options;
146
- this.cwd = normalizeRemotePath(options.cwd ?? '/workspace');
189
+ this.cwd = normalizeRemotePath(options.cwd ?? "/workspace");
147
190
  this.capabilities = {
148
191
  ...(options.capabilities ?? {
149
192
  exec: true,
150
193
  filesystem: true,
151
194
  binaryFiles: true,
152
- snapshots: typeof api.snapshot === 'function',
153
- restore: typeof api.restore === 'function',
154
- fork: typeof api.fork === 'function',
155
- suspend: typeof api.suspend === 'function',
156
- resume: typeof api.resume === 'function',
157
- network: 'provider-managed',
158
- networkEnforcement: 'none',
159
- persistence: 'session',
160
- isolation: 'provider',
195
+ snapshots: typeof api.snapshot === "function",
196
+ restore: typeof api.restore === "function",
197
+ fork: typeof api.fork === "function",
198
+ suspend: typeof api.suspend === "function",
199
+ resume: typeof api.resume === "function",
200
+ network: "provider-managed",
201
+ networkEnforcement: "none",
202
+ persistence: "session",
203
+ isolation: "provider",
161
204
  }),
162
- reconnect: typeof options.encodeRef === 'function',
205
+ reconnect: typeof options.encodeRef === "function",
163
206
  };
164
207
  }
165
208
  exec(command, options = {}) {
@@ -167,16 +210,32 @@ class RemoteSandboxEnv {
167
210
  execOptions.cwd = options.cwd ? this.resolvePath(options.cwd) : this.cwd;
168
211
  return this.api.exec(command, execOptions);
169
212
  }
170
- readFile(filePath) { return this.api.readFile(this.resolvePath(filePath)); }
171
- readFileBuffer(filePath) { return this.api.readFileBuffer(this.resolvePath(filePath)); }
172
- writeFile(filePath, content) { return this.api.writeFile(this.resolvePath(filePath), content); }
173
- stat(filePath) { return this.api.stat(this.resolvePath(filePath)); }
174
- readdir(dirPath) { return this.api.readdir(this.resolvePath(dirPath)); }
175
- exists(filePath) { return this.api.exists(this.resolvePath(filePath)); }
176
- mkdir(dirPath, options = {}) { return this.api.mkdir(this.resolvePath(dirPath), options); }
177
- rm(filePath, options = {}) { return this.api.rm(this.resolvePath(filePath), options); }
213
+ readFile(filePath) {
214
+ return this.api.readFile(this.resolvePath(filePath));
215
+ }
216
+ readFileBuffer(filePath) {
217
+ return this.api.readFileBuffer(this.resolvePath(filePath));
218
+ }
219
+ writeFile(filePath, content) {
220
+ return this.api.writeFile(this.resolvePath(filePath), content);
221
+ }
222
+ stat(filePath) {
223
+ return this.api.stat(this.resolvePath(filePath));
224
+ }
225
+ readdir(dirPath) {
226
+ return this.api.readdir(this.resolvePath(dirPath));
227
+ }
228
+ exists(filePath) {
229
+ return this.api.exists(this.resolvePath(filePath));
230
+ }
231
+ mkdir(dirPath, options = {}) {
232
+ return this.api.mkdir(this.resolvePath(dirPath), options);
233
+ }
234
+ rm(filePath, options = {}) {
235
+ return this.api.rm(this.resolvePath(filePath), options);
236
+ }
178
237
  resolvePath(filePath) {
179
- const resolved = filePath.startsWith('/')
238
+ const resolved = filePath.startsWith("/")
180
239
  ? normalizeRemotePath(filePath)
181
240
  : normalizeRemotePath(path.posix.join(this.cwd, filePath));
182
241
  if (resolved !== this.cwd && !resolved.startsWith(`${this.cwd}/`)) {
@@ -186,28 +245,28 @@ class RemoteSandboxEnv {
186
245
  }
187
246
  async snapshot() {
188
247
  if (!this.api.snapshot)
189
- throw unsupportedSandboxOperation('snapshot', 'The remote');
248
+ throw unsupportedSandboxOperation("snapshot", "The remote");
190
249
  return this.api.snapshot();
191
250
  }
192
251
  async restore(snapshot) {
193
252
  if (!this.api.restore)
194
- throw unsupportedSandboxOperation('restore', 'The remote');
253
+ throw unsupportedSandboxOperation("restore", "The remote");
195
254
  await this.api.restore(snapshot);
196
255
  }
197
256
  async fork(snapshot) {
198
257
  if (!this.api.fork)
199
- throw unsupportedSandboxOperation('fork', 'The remote');
258
+ throw unsupportedSandboxOperation("fork", "The remote");
200
259
  const forkedApi = await this.api.fork(snapshot);
201
260
  return new RemoteSandboxEnv(forkedApi, this.options);
202
261
  }
203
262
  async suspend() {
204
263
  if (!this.api.suspend)
205
- throw unsupportedSandboxOperation('suspend', 'The remote');
264
+ throw unsupportedSandboxOperation("suspend", "The remote");
206
265
  await this.api.suspend();
207
266
  }
208
267
  async resume() {
209
268
  if (!this.api.resume)
210
- throw unsupportedSandboxOperation('resume', 'The remote');
269
+ throw unsupportedSandboxOperation("resume", "The remote");
211
270
  await this.api.resume();
212
271
  }
213
272
  encodeRef() {
@@ -217,20 +276,20 @@ class RemoteSandboxEnv {
217
276
  const cleanup = this.options.cleanup;
218
277
  if (!cleanup)
219
278
  return;
220
- if (typeof cleanup === 'function')
279
+ if (typeof cleanup === "function")
221
280
  await cleanup();
222
281
  else
223
282
  await cleanup.cleanup();
224
283
  }
225
284
  }
226
285
  function normalizeRemotePath(value) {
227
- const normalized = path.posix.resolve('/', value);
228
- return normalized === '/' ? '/' : normalized.replace(/\/+$/u, '');
286
+ const normalized = path.posix.resolve("/", value);
287
+ return normalized === "/" ? "/" : normalized.replace(/\/+$/u, "");
229
288
  }
230
289
  function fileStatFromNode(node) {
231
290
  const stat = {
232
291
  type: node.type,
233
- size: node.type === 'file' ? node.content.byteLength : 0,
292
+ size: node.type === "file" ? node.content.byteLength : 0,
234
293
  };
235
294
  if (node.mtime !== undefined) {
236
295
  stat.mtime = node.mtime;
@@ -242,12 +301,12 @@ function fileStatFromNode(node) {
242
301
  }
243
302
  function fileStatFromFs(stats) {
244
303
  const type = stats.isFile()
245
- ? 'file'
304
+ ? "file"
246
305
  : stats.isDirectory()
247
- ? 'directory'
306
+ ? "directory"
248
307
  : stats.isSymbolicLink()
249
- ? 'symlink'
250
- : 'other';
308
+ ? "symlink"
309
+ : "other";
251
310
  return {
252
311
  type,
253
312
  size: Number(stats.size),
@@ -258,9 +317,7 @@ function fileStatFromFs(stats) {
258
317
  function cloneEntries(entries) {
259
318
  const clone = new Map();
260
319
  for (const [entryPath, entry] of entries) {
261
- clone.set(entryPath, entry.type === 'file'
262
- ? { ...entry, content: new Uint8Array(entry.content) }
263
- : { ...entry });
320
+ clone.set(entryPath, entry.type === "file" ? { ...entry, content: new Uint8Array(entry.content) } : { ...entry });
264
321
  }
265
322
  return clone;
266
323
  }
@@ -273,28 +330,43 @@ const emptyEnvSnapshots = new Map();
273
330
  let emptyEnvNextSnapshotId = 0;
274
331
  export class EmptySandboxEnv {
275
332
  cwd;
276
- capabilities = { exec: true, filesystem: true, binaryFiles: true, snapshots: true, restore: true, fork: true, network: 'none', persistence: 'ephemeral', isolation: 'process' };
333
+ capabilities = {
334
+ exec: true,
335
+ filesystem: true,
336
+ binaryFiles: true,
337
+ snapshots: true,
338
+ restore: true,
339
+ fork: true,
340
+ network: "none",
341
+ persistence: "ephemeral",
342
+ isolation: "process",
343
+ };
277
344
  fs = new InMemoryFs();
278
345
  bash;
279
- constructor(cwd = '/workspace') {
280
- this.cwd = path.posix.resolve('/', cwd);
346
+ constructor(cwd = "/workspace") {
347
+ this.cwd = path.posix.resolve("/", cwd);
281
348
  this.fs.mkdirSync(this.cwd, { recursive: true });
282
349
  this.bash = new Bash({ fs: this.fs, cwd: this.cwd, python: true });
283
350
  }
284
351
  async exec(command, options = {}) {
285
- const started = Date.now();
352
+ const started = performance.now();
286
353
  const cwd = options.cwd ? this.resolvePath(options.cwd) : this.cwd;
287
354
  if (!(await this.exists(cwd)))
288
355
  await this.mkdir(cwd, { recursive: true });
289
- const bash = new Bash({ fs: this.fs, cwd, ...(options.env ? { env: options.env } : {}), python: true });
356
+ const bash = new Bash({
357
+ fs: this.fs,
358
+ cwd,
359
+ ...(options.env ? { env: options.env } : {}),
360
+ python: true,
361
+ });
290
362
  try {
291
363
  const result = await bash.exec(command);
292
364
  const shellResult = {
293
365
  command,
294
366
  exitCode: Number(result.exitCode ?? 0),
295
- stdout: String(result.stdout ?? ''),
296
- stderr: String(result.stderr ?? ''),
297
- durationMs: Date.now() - started,
367
+ stdout: String(result.stdout ?? ""),
368
+ stderr: String(result.stderr ?? ""),
369
+ durationMs: Math.max(0, Math.round(performance.now() - started)),
298
370
  };
299
371
  emitCollectedOutput(options, shellResult);
300
372
  return shellResult;
@@ -303,9 +375,9 @@ export class EmptySandboxEnv {
303
375
  const shellResult = {
304
376
  command,
305
377
  exitCode: 1,
306
- stdout: '',
378
+ stdout: "",
307
379
  stderr: error instanceof Error ? error.message : String(error),
308
- durationMs: Date.now() - started,
380
+ durationMs: Math.max(0, Math.round(performance.now() - started)),
309
381
  };
310
382
  emitCollectedOutput(options, shellResult);
311
383
  return shellResult;
@@ -325,7 +397,13 @@ export class EmptySandboxEnv {
325
397
  async stat(filePath) {
326
398
  const stats = await this.fs.stat(this.resolvePath(filePath));
327
399
  return {
328
- type: stats.isFile ? 'file' : stats.isDirectory ? 'directory' : stats.isSymbolicLink ? 'symlink' : 'other',
400
+ type: stats.isFile
401
+ ? "file"
402
+ : stats.isDirectory
403
+ ? "directory"
404
+ : stats.isSymbolicLink
405
+ ? "symlink"
406
+ : "other",
329
407
  size: Number(stats.size ?? 0),
330
408
  ...(stats.mtime ? { mtime: stats.mtime } : {}),
331
409
  ...(stats.mode !== undefined ? { mode: Number(stats.mode) } : {}),
@@ -347,7 +425,7 @@ export class EmptySandboxEnv {
347
425
  await this.fs.rm(resolved, options);
348
426
  }
349
427
  resolvePath(filePath) {
350
- const resolved = filePath.startsWith('/')
428
+ const resolved = filePath.startsWith("/")
351
429
  ? path.posix.resolve(filePath)
352
430
  : path.posix.resolve(this.cwd, filePath);
353
431
  if (resolved !== this.cwd && !resolved.startsWith(`${this.cwd}/`)) {
@@ -367,7 +445,7 @@ export class EmptySandboxEnv {
367
445
  this.fs = new InMemoryFs();
368
446
  this.fs.mkdirSync(this.cwd, { recursive: true });
369
447
  for (const [entryPath, entry] of entries) {
370
- if (entry.type === 'directory')
448
+ if (entry.type === "directory")
371
449
  await this.fs.mkdir(entryPath, { recursive: true });
372
450
  else
373
451
  await this.writeFile(entryPath, entry.content);
@@ -393,9 +471,18 @@ export class EmptySandboxEnv {
393
471
  continue;
394
472
  const stats = await this.fs.stat(entryPath);
395
473
  if (stats.isDirectory)
396
- entries.set(entryPath, { type: 'directory', mtime: stats.mtime ?? new Date(), ...(stats.mode !== undefined ? { mode: Number(stats.mode) } : {}) });
474
+ entries.set(entryPath, {
475
+ type: "directory",
476
+ mtime: stats.mtime ?? new Date(),
477
+ ...(stats.mode !== undefined ? { mode: Number(stats.mode) } : {}),
478
+ });
397
479
  else if (stats.isFile)
398
- entries.set(entryPath, { type: 'file', content: await this.fs.readFileBuffer(entryPath), mtime: stats.mtime ?? new Date(), ...(stats.mode !== undefined ? { mode: Number(stats.mode) } : {}) });
480
+ entries.set(entryPath, {
481
+ type: "file",
482
+ content: await this.fs.readFileBuffer(entryPath),
483
+ mtime: stats.mtime ?? new Date(),
484
+ ...(stats.mode !== undefined ? { mode: Number(stats.mode) } : {}),
485
+ });
399
486
  }
400
487
  return entries;
401
488
  }
@@ -403,7 +490,17 @@ export class EmptySandboxEnv {
403
490
  export const VirtualSandboxEnv = EmptySandboxEnv;
404
491
  export class LocalSandboxEnv {
405
492
  cwd;
406
- capabilities = { exec: true, filesystem: true, binaryFiles: true, snapshots: true, restore: true, fork: true, network: 'egress', persistence: 'durable', isolation: 'process' };
493
+ capabilities = {
494
+ exec: true,
495
+ filesystem: true,
496
+ binaryFiles: true,
497
+ snapshots: true,
498
+ restore: true,
499
+ fork: true,
500
+ network: "egress",
501
+ persistence: "durable",
502
+ isolation: "process",
503
+ };
407
504
  env;
408
505
  snapshotRoot;
409
506
  outputLimitBytes;
@@ -419,35 +516,45 @@ export class LocalSandboxEnv {
419
516
  this.outputLimitBytes = options.outputLimitBytes ?? 1024 * 1024;
420
517
  if (options.defaultTimeoutMs !== undefined)
421
518
  this.defaultTimeoutMs = options.defaultTimeoutMs;
422
- this.snapshotRoot = path.resolve(options.snapshotRoot ?? path.join(this.cwd, '.fabricharness', 'checkpoints', sanitizeId(options.sessionId ?? 'local')));
519
+ this.snapshotRoot = path.resolve(options.snapshotRoot ??
520
+ path.join(this.cwd, ".fabricharness", "checkpoints", sanitizeId(options.sessionId ?? "local")));
423
521
  this.allowedRoots = (options.allowedPaths ?? []).map((entry) => path.resolve(this.cwd, entry));
424
522
  }
425
523
  async exec(command, options = {}) {
426
- const startedAt = Date.now();
524
+ const startedAt = performance.now();
427
525
  const cwd = options.cwd ? await this.resolveExistingPath(options.cwd) : this.cwd;
428
- await assertLocalCommandConfined(command, cwd, { workspaceRoot: this.cwd, allowedRoots: this.allowedRoots });
526
+ await assertLocalCommandConfined(command, cwd, {
527
+ workspaceRoot: this.cwd,
528
+ allowedRoots: this.allowedRoots,
529
+ });
429
530
  const childEnv = { ...this.env, ...options.env };
531
+ if (options.signal?.aborted) {
532
+ return {
533
+ command,
534
+ exitCode: 130,
535
+ stdout: "",
536
+ stderr: "Command aborted.\n",
537
+ durationMs: Math.max(0, Math.round(performance.now() - startedAt)),
538
+ };
539
+ }
430
540
  return new Promise((resolve) => {
431
- const child = spawn(command, {
541
+ const child = spawn(process.execPath, ["--input-type=commonjs", "-e", LOCAL_PROCESS_SUPERVISOR], {
432
542
  cwd,
433
- env: childEnv,
434
- shell: true,
543
+ // Command loaders and native injection settings must not affect the
544
+ // process-group owner. Pass the complete command environment over IPC.
545
+ env: safeHostEnv(),
435
546
  windowsHide: true,
436
- detached: process.platform !== 'win32',
547
+ detached: process.platform !== "win32",
548
+ stdio: ["ignore", "pipe", "pipe", "ipc"],
437
549
  });
438
- let stdout = '';
439
- let stderr = '';
550
+ let stdout = "";
551
+ let stderr = "";
440
552
  let timedOut = false;
441
553
  let aborted = false;
554
+ let commandResult;
442
555
  const terminate = () => {
443
- if (process.platform !== 'win32' && child.pid) {
444
- try {
445
- process.kill(-child.pid, 'SIGTERM');
446
- return;
447
- }
448
- catch { }
449
- }
450
- child.kill('SIGTERM');
556
+ if (child.connected)
557
+ child.send({ type: "terminate" }, () => { });
451
558
  };
452
559
  const abort = () => {
453
560
  aborted = true;
@@ -456,7 +563,7 @@ export class LocalSandboxEnv {
456
563
  if (options.signal?.aborted)
457
564
  abort();
458
565
  else
459
- options.signal?.addEventListener('abort', abort, { once: true });
566
+ options.signal?.addEventListener("abort", abort, { once: true });
460
567
  const effectiveTimeout = options.timeout ?? this.defaultTimeoutMs;
461
568
  const timeout = effectiveTimeout
462
569
  ? setTimeout(() => {
@@ -464,49 +571,83 @@ export class LocalSandboxEnv {
464
571
  terminate();
465
572
  }, effectiveTimeout)
466
573
  : undefined;
467
- child.stdout?.setEncoding('utf8');
468
- child.stderr?.setEncoding('utf8');
469
- child.stdout?.on('data', (chunk) => {
574
+ child.on("message", (message) => {
575
+ if (typeof message !== "object" ||
576
+ !message ||
577
+ !("type" in message) ||
578
+ message.type !== "result")
579
+ return;
580
+ if (aborted || timedOut)
581
+ return;
582
+ commandResult = message;
583
+ if (timeout)
584
+ clearTimeout(timeout);
585
+ options.signal?.removeEventListener("abort", abort);
586
+ if (child.connected)
587
+ child.send({ type: "release" }, () => { });
588
+ });
589
+ if (child.connected)
590
+ child.send({ type: "start", command, env: childEnv }, () => { });
591
+ child.on("exit", () => {
592
+ if (child.connected)
593
+ child.disconnect();
594
+ if (commandResult)
595
+ return;
596
+ if (!aborted && !timedOut) {
597
+ stderr = appendLimited(stderr, "Local process supervisor exited unexpectedly; descendant cleanup could not be confirmed.\n", this.outputLimitBytes);
598
+ }
599
+ // Descendants may still hold these pipes. Do not hang waiting for them,
600
+ // or signal a numeric process-group id after its live owner has died.
601
+ child.stdout?.destroy();
602
+ child.stderr?.destroy();
603
+ });
604
+ child.stdout?.setEncoding("utf8");
605
+ child.stderr?.setEncoding("utf8");
606
+ child.stdout?.on("data", (chunk) => {
470
607
  const text = String(chunk);
471
608
  stdout = appendLimited(stdout, text, this.outputLimitBytes);
472
609
  options.onStdout?.(text);
473
610
  });
474
- child.stderr?.on('data', (chunk) => {
611
+ child.stderr?.on("data", (chunk) => {
475
612
  const text = String(chunk);
476
613
  stderr = appendLimited(stderr, text, this.outputLimitBytes);
477
614
  options.onStderr?.(text);
478
615
  });
479
- child.on('error', (error) => {
616
+ child.on("error", (error) => {
480
617
  if (timeout) {
481
618
  clearTimeout(timeout);
482
619
  }
483
- options.signal?.removeEventListener('abort', abort);
620
+ options.signal?.removeEventListener("abort", abort);
484
621
  resolve({
485
622
  command,
486
623
  exitCode: aborted ? 130 : 1,
487
624
  stdout,
488
625
  stderr: aborted ? `${stderr}Command aborted.\n` : `${stderr}${error.message}`,
489
- durationMs: Date.now() - startedAt,
626
+ durationMs: Math.max(0, Math.round(performance.now() - startedAt)),
490
627
  });
491
628
  });
492
- child.on('close', (code, signal) => {
629
+ child.on("close", () => {
493
630
  if (timeout) {
494
631
  clearTimeout(timeout);
495
632
  }
496
- options.signal?.removeEventListener('abort', abort);
633
+ options.signal?.removeEventListener("abort", abort);
497
634
  resolve({
498
635
  command,
499
- exitCode: aborted ? 130 : timedOut ? 124 : (code ?? 1),
636
+ exitCode: aborted ? 130 : timedOut ? 124 : (commandResult?.code ?? 1),
500
637
  stdout,
501
- stderr: aborted ? `${stderr}Command aborted.\n` : timedOut ? `${stderr}Command timed out and was terminated.\n` : stderr,
502
- durationMs: Date.now() - startedAt,
503
- ...(signal ? { signal } : {}),
638
+ stderr: aborted
639
+ ? `${stderr}Command aborted.\n`
640
+ : timedOut
641
+ ? `${stderr}Command timed out and was terminated.\n`
642
+ : stderr,
643
+ durationMs: Math.max(0, Math.round(performance.now() - startedAt)),
644
+ ...(commandResult?.signal ? { signal: commandResult.signal } : {}),
504
645
  });
505
646
  });
506
647
  });
507
648
  }
508
649
  async readFile(filePath) {
509
- return fs.readFile(await this.resolveExistingPath(filePath), 'utf8');
650
+ return fs.readFile(await this.resolveExistingPath(filePath), "utf8");
510
651
  }
511
652
  async readFileBuffer(filePath) {
512
653
  return fs.readFile(await this.resolveExistingPath(filePath));
@@ -579,20 +720,20 @@ export class LocalSandboxEnv {
579
720
  assertInsideWorkspace(resolved, original) {
580
721
  if (resolved !== this.cwd && !resolved.startsWith(`${this.cwd}${path.sep}`)) {
581
722
  throw new FabricError({
582
- code: 'SANDBOX_ESCAPE_BLOCKED',
723
+ code: "SANDBOX_ESCAPE_BLOCKED",
583
724
  message: `Path escapes sandbox workspace: ${original}`,
584
725
  details: { path: original, resolved, workspaceRoot: this.cwd },
585
726
  });
586
727
  }
587
728
  }
588
729
  async snapshot() {
589
- return snapshotWorkspace(this.cwd, this.snapshotRoot, 'local');
730
+ return snapshotWorkspace(this.cwd, this.snapshotRoot, "local");
590
731
  }
591
732
  async restore(snapshot) {
592
733
  await restoreWorkspace(this.cwd, this.snapshotRoot, snapshot);
593
734
  }
594
735
  async fork(snapshot) {
595
- const forkWorkspace = await fs.mkdtemp(path.join(tmpdir(), 'fabric-harness-local-fork-'));
736
+ const forkWorkspace = await fs.mkdtemp(path.join(tmpdir(), "fabric-harness-local-fork-"));
596
737
  const forked = new LocalSandboxEnv({
597
738
  workspacePath: forkWorkspace,
598
739
  env: this.env,
@@ -614,7 +755,7 @@ export class LocalSandboxEnv {
614
755
  }
615
756
  }
616
757
  export class DockerSandboxEnv {
617
- cwd = '/workspace';
758
+ cwd = "/workspace";
618
759
  capabilities;
619
760
  hostWorkspacePath;
620
761
  image;
@@ -631,10 +772,10 @@ export class DockerSandboxEnv {
631
772
  snapshotRoot;
632
773
  constructor(options) {
633
774
  this.hostWorkspacePath = path.resolve(options.workspacePath);
634
- this.image = options.image ?? 'node:22-alpine';
775
+ this.image = options.image ?? "node:22-alpine";
635
776
  this.env = { ...envFromAllowlist(options.envAllowlist), ...(options.env ?? {}) };
636
777
  this.network = normalizeDockerNetwork(options.network);
637
- const networkDisabled = this.network === 'none';
778
+ const networkDisabled = this.network === "none";
638
779
  this.capabilities = {
639
780
  exec: true,
640
781
  filesystem: true,
@@ -642,15 +783,15 @@ export class DockerSandboxEnv {
642
783
  snapshots: true,
643
784
  restore: true,
644
785
  fork: true,
645
- network: networkDisabled ? 'none' : options.networkBoundary ? 'restricted' : 'egress',
646
- networkEnforcement: networkDisabled || options.networkBoundary ? 'container' : 'none',
786
+ network: networkDisabled ? "none" : options.networkBoundary ? "restricted" : "egress",
787
+ networkEnforcement: networkDisabled || options.networkBoundary ? "container" : "none",
647
788
  ...(networkDisabled
648
- ? { networkBoundary: 'docker:network=none' }
789
+ ? { networkBoundary: "docker:network=none" }
649
790
  : options.networkBoundary
650
791
  ? { networkBoundary: options.networkBoundary.reference }
651
792
  : {}),
652
- persistence: 'session',
653
- isolation: 'container',
793
+ persistence: "session",
794
+ isolation: "container",
654
795
  };
655
796
  if (options.user !== undefined)
656
797
  this.user = options.user;
@@ -664,95 +805,106 @@ export class DockerSandboxEnv {
664
805
  this.mountReadOnly = options.mountReadOnly ?? false;
665
806
  this.outputLimitBytes = options.outputLimitBytes ?? 1024 * 1024;
666
807
  this.ownsWorkspace = options.ownsWorkspace ?? false;
667
- this.snapshotRoot = path.resolve(options.snapshotRoot ?? path.join(this.hostWorkspacePath, '.fabricharness', 'checkpoints', sanitizeId(options.sessionId ?? 'docker')));
808
+ this.snapshotRoot = path.resolve(options.snapshotRoot ??
809
+ path.join(this.hostWorkspacePath, ".fabricharness", "checkpoints", sanitizeId(options.sessionId ?? "docker")));
668
810
  }
669
811
  async exec(command, options = {}) {
670
812
  await fs.mkdir(this.hostWorkspacePath, { recursive: true });
671
- const startedAt = Date.now();
813
+ const startedAt = performance.now();
672
814
  const containerName = `fabric-harness-${randomUUID()}`;
673
815
  const cwd = options.cwd ? this.toContainerPath(options.cwd) : this.cwd;
674
816
  const args = [
675
- 'run',
676
- '--rm',
677
- '--name',
817
+ "run",
818
+ "--rm",
819
+ "--name",
678
820
  containerName,
679
- '--network',
821
+ "--network",
680
822
  this.network,
681
- '-v',
682
- `${this.hostWorkspacePath}:${this.cwd}${this.mountReadOnly ? ':ro' : ''}`,
683
- '-w',
823
+ "-v",
824
+ `${this.hostWorkspacePath}:${this.cwd}${this.mountReadOnly ? ":ro" : ""}`,
825
+ "-w",
684
826
  cwd,
685
827
  ];
686
828
  if (this.user)
687
- args.push('-u', this.user);
829
+ args.push("-u", this.user);
688
830
  if (this.cpus !== undefined)
689
- args.push('--cpus', String(this.cpus));
831
+ args.push("--cpus", String(this.cpus));
690
832
  if (this.memory !== undefined)
691
- args.push('--memory', this.memory);
833
+ args.push("--memory", this.memory);
692
834
  if (this.pidsLimit !== undefined)
693
- args.push('--pids-limit', String(this.pidsLimit));
835
+ args.push("--pids-limit", String(this.pidsLimit));
694
836
  if (this.readOnlyRootFilesystem)
695
- args.push('--read-only', '--tmpfs', '/tmp:rw,noexec,nosuid,size=64m');
837
+ args.push("--read-only", "--tmpfs", "/tmp:rw,noexec,nosuid,size=64m");
696
838
  for (const [key, value] of Object.entries({ ...this.env, ...options.env }))
697
- args.push('-e', `${key}=${value}`);
698
- args.push(this.image, 'sh', '-lc', command);
839
+ args.push("-e", `${key}=${value}`);
840
+ args.push(this.image, "sh", "-lc", command);
699
841
  return new Promise((resolve) => {
700
- const child = spawn('docker', args, { windowsHide: true });
701
- let stdout = '';
702
- let stderr = '';
842
+ const child = spawn("docker", args, { windowsHide: true });
843
+ let stdout = "";
844
+ let stderr = "";
703
845
  let timedOut = false;
704
846
  let aborted = false;
705
847
  const abort = () => {
706
848
  aborted = true;
707
- child.kill('SIGTERM');
708
- void runDocker(['rm', '-f', containerName]);
849
+ child.kill("SIGTERM");
850
+ void runDocker(["rm", "-f", containerName]);
709
851
  };
710
852
  if (options.signal?.aborted)
711
853
  abort();
712
854
  else
713
- options.signal?.addEventListener('abort', abort, { once: true });
855
+ options.signal?.addEventListener("abort", abort, { once: true });
714
856
  const timeout = options.timeout
715
857
  ? setTimeout(() => {
716
858
  timedOut = true;
717
- child.kill('SIGTERM');
718
- void runDocker(['rm', '-f', containerName]);
859
+ child.kill("SIGTERM");
860
+ void runDocker(["rm", "-f", containerName]);
719
861
  }, options.timeout)
720
862
  : undefined;
721
- child.stdout?.setEncoding('utf8');
722
- child.stderr?.setEncoding('utf8');
723
- child.stdout?.on('data', (chunk) => {
863
+ child.stdout?.setEncoding("utf8");
864
+ child.stderr?.setEncoding("utf8");
865
+ child.stdout?.on("data", (chunk) => {
724
866
  const text = String(chunk);
725
867
  stdout = appendLimited(stdout, text, this.outputLimitBytes);
726
868
  options.onStdout?.(text);
727
869
  });
728
- child.stderr?.on('data', (chunk) => {
870
+ child.stderr?.on("data", (chunk) => {
729
871
  const text = String(chunk);
730
872
  stderr = appendLimited(stderr, text, this.outputLimitBytes);
731
873
  options.onStderr?.(text);
732
874
  });
733
- child.on('error', (error) => {
875
+ child.on("error", (error) => {
734
876
  if (timeout)
735
877
  clearTimeout(timeout);
736
- options.signal?.removeEventListener('abort', abort);
737
- resolve({ command, exitCode: aborted ? 130 : 1, stdout, stderr: aborted ? `${stderr}Command aborted.\n` : `${stderr}${error.message}`, durationMs: Date.now() - startedAt });
878
+ options.signal?.removeEventListener("abort", abort);
879
+ resolve({
880
+ command,
881
+ exitCode: aborted ? 130 : 1,
882
+ stdout,
883
+ stderr: aborted ? `${stderr}Command aborted.\n` : `${stderr}${error.message}`,
884
+ durationMs: Math.max(0, Math.round(performance.now() - startedAt)),
885
+ });
738
886
  });
739
- child.on('close', (code, signal) => {
887
+ child.on("close", (code, signal) => {
740
888
  if (timeout)
741
889
  clearTimeout(timeout);
742
- options.signal?.removeEventListener('abort', abort);
890
+ options.signal?.removeEventListener("abort", abort);
743
891
  resolve({
744
892
  command,
745
893
  exitCode: aborted ? 130 : timedOut ? 124 : (code ?? 1),
746
894
  stdout,
747
- stderr: aborted ? `${stderr}Command aborted.\n` : timedOut ? `${stderr}Command timed out and container was terminated.\n` : stderr,
748
- durationMs: Date.now() - startedAt,
895
+ stderr: aborted
896
+ ? `${stderr}Command aborted.\n`
897
+ : timedOut
898
+ ? `${stderr}Command timed out and container was terminated.\n`
899
+ : stderr,
900
+ durationMs: Math.max(0, Math.round(performance.now() - startedAt)),
749
901
  ...(signal ? { signal } : {}),
750
902
  });
751
903
  });
752
904
  });
753
905
  }
754
906
  async readFile(filePath) {
755
- return fs.readFile(this.resolvePath(filePath), 'utf8');
907
+ return fs.readFile(this.resolvePath(filePath), "utf8");
756
908
  }
757
909
  async readFileBuffer(filePath) {
758
910
  return fs.readFile(this.resolvePath(filePath));
@@ -786,19 +938,20 @@ export class DockerSandboxEnv {
786
938
  resolvePath(filePath) {
787
939
  const relative = this.toWorkspaceRelativePath(filePath);
788
940
  const resolved = path.resolve(this.hostWorkspacePath, relative);
789
- if (resolved !== this.hostWorkspacePath && !resolved.startsWith(`${this.hostWorkspacePath}${path.sep}`)) {
941
+ if (resolved !== this.hostWorkspacePath &&
942
+ !resolved.startsWith(`${this.hostWorkspacePath}${path.sep}`)) {
790
943
  throw new Error(`Path escapes sandbox workspace: ${filePath}`);
791
944
  }
792
945
  return resolved;
793
946
  }
794
947
  async snapshot() {
795
- return snapshotWorkspace(this.hostWorkspacePath, this.snapshotRoot, 'docker');
948
+ return snapshotWorkspace(this.hostWorkspacePath, this.snapshotRoot, "docker");
796
949
  }
797
950
  async restore(snapshot) {
798
951
  await restoreWorkspace(this.hostWorkspacePath, this.snapshotRoot, snapshot);
799
952
  }
800
953
  async fork(snapshot) {
801
- const forkWorkspace = await fs.mkdtemp(path.join(tmpdir(), 'fabric-harness-docker-fork-'));
954
+ const forkWorkspace = await fs.mkdtemp(path.join(tmpdir(), "fabric-harness-docker-fork-"));
802
955
  const forked = new DockerSandboxEnv({
803
956
  workspacePath: forkWorkspace,
804
957
  image: this.image,
@@ -824,25 +977,25 @@ export class DockerSandboxEnv {
824
977
  }
825
978
  toContainerPath(filePath) {
826
979
  const relative = this.toWorkspaceRelativePath(filePath);
827
- return relative ? path.posix.join(this.cwd, relative.split(path.sep).join('/')) : this.cwd;
980
+ return relative ? path.posix.join(this.cwd, relative.split(path.sep).join("/")) : this.cwd;
828
981
  }
829
982
  toWorkspaceRelativePath(filePath) {
830
- if (filePath.startsWith('/')) {
983
+ if (filePath.startsWith("/")) {
831
984
  const resolved = path.posix.resolve(filePath);
832
985
  if (resolved !== this.cwd && !resolved.startsWith(`${this.cwd}/`)) {
833
986
  throw new Error(`Path escapes sandbox workspace: ${filePath}`);
834
987
  }
835
- return resolved.slice(this.cwd.length).replace(/^\//, '');
988
+ return resolved.slice(this.cwd.length).replace(/^\//, "");
836
989
  }
837
990
  const resolved = path.posix.resolve(this.cwd, filePath);
838
991
  if (resolved !== this.cwd && !resolved.startsWith(`${this.cwd}/`)) {
839
992
  throw new Error(`Path escapes sandbox workspace: ${filePath}`);
840
993
  }
841
- return resolved.slice(this.cwd.length).replace(/^\//, '');
994
+ return resolved.slice(this.cwd.length).replace(/^\//, "");
842
995
  }
843
996
  }
844
997
  export async function pruneSnapshots(snapshotRoot, options = {}) {
845
- if (!await fileExists(snapshotRoot))
998
+ if (!(await fileExists(snapshotRoot)))
846
999
  return { removed: [], kept: [] };
847
1000
  const entries = await fs.readdir(snapshotRoot, { withFileTypes: true });
848
1001
  const snapshots = [];
@@ -850,11 +1003,11 @@ export async function pruneSnapshots(snapshotRoot, options = {}) {
850
1003
  if (!entry.isDirectory())
851
1004
  continue;
852
1005
  const snapshotPath = path.join(snapshotRoot, entry.name);
853
- const manifestPath = path.join(snapshotPath, 'manifest.json');
1006
+ const manifestPath = path.join(snapshotPath, "manifest.json");
854
1007
  let createdAt = (await fs.stat(snapshotPath)).mtimeMs;
855
1008
  if (await fileExists(manifestPath)) {
856
1009
  try {
857
- const manifest = JSON.parse(await fs.readFile(manifestPath, 'utf8'));
1010
+ const manifest = JSON.parse(await fs.readFile(manifestPath, "utf8"));
858
1011
  if (manifest.createdAt)
859
1012
  createdAt = new Date(manifest.createdAt).getTime();
860
1013
  }
@@ -885,7 +1038,7 @@ export async function pruneSnapshots(snapshotRoot, options = {}) {
885
1038
  async function snapshotWorkspace(workspaceRoot, snapshotRoot, backend) {
886
1039
  const id = `${backend}-snapshot-${Date.now()}-${randomUUID()}`;
887
1040
  const snapshotDir = path.join(snapshotRoot, id);
888
- const filesDir = path.join(snapshotDir, 'files');
1041
+ const filesDir = path.join(snapshotDir, "files");
889
1042
  await fs.mkdir(filesDir, { recursive: true });
890
1043
  await copyDirectory(workspaceRoot, filesDir, { excludeRoots: [snapshotRoot] });
891
1044
  const files = await snapshotFileManifest(filesDir);
@@ -899,12 +1052,12 @@ async function snapshotWorkspace(workspaceRoot, snapshotRoot, backend) {
899
1052
  files,
900
1053
  totalBytes: files.reduce((sum, file) => sum + file.bytes, 0),
901
1054
  };
902
- await fs.writeFile(path.join(snapshotDir, 'manifest.json'), `${JSON.stringify(manifest, null, 2)}\n`);
1055
+ await fs.writeFile(path.join(snapshotDir, "manifest.json"), `${JSON.stringify(manifest, null, 2)}\n`);
903
1056
  return { id, metadata: { path: snapshotDir, backend } };
904
1057
  }
905
1058
  async function restoreWorkspace(workspaceRoot, snapshotRoot, snapshot) {
906
1059
  const snapshotDir = resolveSnapshotDir(snapshotRoot, snapshot);
907
- const filesDir = path.join(snapshotDir, 'files');
1060
+ const filesDir = path.join(snapshotDir, "files");
908
1061
  const stat = await fs.stat(filesDir);
909
1062
  if (!stat.isDirectory())
910
1063
  throw new Error(`Snapshot files directory not found: ${snapshot.id}`);
@@ -914,10 +1067,10 @@ async function restoreWorkspace(workspaceRoot, snapshotRoot, snapshot) {
914
1067
  await copyDirectory(filesDir, workspaceRoot);
915
1068
  }
916
1069
  async function verifySnapshotIntegrity(snapshotDir, filesDir) {
917
- const manifestPath = path.join(snapshotDir, 'manifest.json');
918
- if (!await fileExists(manifestPath))
1070
+ const manifestPath = path.join(snapshotDir, "manifest.json");
1071
+ if (!(await fileExists(manifestPath)))
919
1072
  return;
920
- const manifest = JSON.parse(await fs.readFile(manifestPath, 'utf8'));
1073
+ const manifest = JSON.parse(await fs.readFile(manifestPath, "utf8"));
921
1074
  if (!Array.isArray(manifest.files))
922
1075
  return;
923
1076
  for (const file of manifest.files) {
@@ -937,7 +1090,11 @@ async function snapshotFileManifest(root) {
937
1090
  const manifest = [];
938
1091
  for (const file of files) {
939
1092
  const stat = await fs.stat(file);
940
- manifest.push({ path: toPosix(path.relative(root, file)), bytes: stat.size, sha256: await sha256File(file) });
1093
+ manifest.push({
1094
+ path: toPosix(path.relative(root, file)),
1095
+ bytes: stat.size,
1096
+ sha256: await sha256File(file),
1097
+ });
941
1098
  }
942
1099
  return manifest.sort((a, b) => a.path.localeCompare(b.path));
943
1100
  }
@@ -947,14 +1104,16 @@ async function listRegularFiles(root) {
947
1104
  for (const entry of entries) {
948
1105
  const entryPath = path.join(root, entry.name);
949
1106
  if (entry.isDirectory())
950
- files.push(...await listRegularFiles(entryPath));
1107
+ files.push(...(await listRegularFiles(entryPath)));
951
1108
  else if (entry.isFile())
952
1109
  files.push(entryPath);
953
1110
  }
954
1111
  return files;
955
1112
  }
956
1113
  async function sha256File(filePath) {
957
- return createHash('sha256').update(await fs.readFile(filePath)).digest('hex');
1114
+ return createHash("sha256")
1115
+ .update(await fs.readFile(filePath))
1116
+ .digest("hex");
958
1117
  }
959
1118
  async function fileExists(filePath) {
960
1119
  try {
@@ -966,10 +1125,10 @@ async function fileExists(filePath) {
966
1125
  }
967
1126
  }
968
1127
  function toPosix(value) {
969
- return value.split(path.sep).join('/');
1128
+ return value.split(path.sep).join("/");
970
1129
  }
971
1130
  function resolveSnapshotDir(snapshotRoot, snapshot) {
972
- const metadataPath = typeof snapshot.metadata?.path === 'string' ? snapshot.metadata.path : undefined;
1131
+ const metadataPath = typeof snapshot.metadata?.path === "string" ? snapshot.metadata.path : undefined;
973
1132
  const candidate = path.resolve(metadataPath ?? path.join(snapshotRoot, snapshot.id));
974
1133
  const root = path.resolve(snapshotRoot);
975
1134
  if (candidate !== root && !candidate.startsWith(`${root}${path.sep}`)) {
@@ -1024,13 +1183,13 @@ function containsExcludedRoot(candidate, excludeRoots) {
1024
1183
  });
1025
1184
  }
1026
1185
  function sanitizeId(value) {
1027
- return value.replace(/[^a-zA-Z0-9._:-]/g, '_');
1186
+ return value.replace(/[^a-zA-Z0-9._:-]/g, "_");
1028
1187
  }
1029
1188
  function normalizeDockerNetwork(network) {
1030
1189
  if (network === true)
1031
- return 'bridge';
1190
+ return "bridge";
1032
1191
  if (network === false || network === undefined)
1033
- return 'none';
1192
+ return "none";
1034
1193
  return network;
1035
1194
  }
1036
1195
  function envFromAllowlist(allowlist) {
@@ -1045,20 +1204,20 @@ function envFromAllowlist(allowlist) {
1045
1204
  return env;
1046
1205
  }
1047
1206
  const SAFE_HOST_ENV_KEYS = [
1048
- 'PATH',
1049
- 'HOME',
1050
- 'USER',
1051
- 'LOGNAME',
1052
- 'HOSTNAME',
1053
- 'SHELL',
1054
- 'LANG',
1055
- 'LC_ALL',
1056
- 'LC_CTYPE',
1057
- 'TZ',
1058
- 'TERM',
1059
- 'TMPDIR',
1060
- 'TMP',
1061
- 'TEMP',
1207
+ "PATH",
1208
+ "HOME",
1209
+ "USER",
1210
+ "LOGNAME",
1211
+ "HOSTNAME",
1212
+ "SHELL",
1213
+ "LANG",
1214
+ "LC_ALL",
1215
+ "LC_CTYPE",
1216
+ "TZ",
1217
+ "TERM",
1218
+ "TMPDIR",
1219
+ "TMP",
1220
+ "TEMP",
1062
1221
  ];
1063
1222
  function safeHostEnv() {
1064
1223
  return envFromAllowlist(SAFE_HOST_ENV_KEYS);
@@ -1071,18 +1230,18 @@ function emitCollectedOutput(options, result) {
1071
1230
  }
1072
1231
  function appendLimited(current, chunk, limit) {
1073
1232
  if (limit <= 0)
1074
- return '';
1233
+ return "";
1075
1234
  const next = `${current}${chunk}`;
1076
- if (Buffer.byteLength(next, 'utf8') <= limit)
1235
+ if (Buffer.byteLength(next, "utf8") <= limit)
1077
1236
  return next;
1078
- const marker = '\n[output truncated by TechFabric Harness]\n';
1237
+ const marker = "\n[output truncated by TechFabric Harness]\n";
1079
1238
  return `${next.slice(Math.max(0, next.length - limit + marker.length))}${marker}`;
1080
1239
  }
1081
1240
  function runDocker(args) {
1082
1241
  return new Promise((resolve) => {
1083
- const child = spawn('docker', args, { stdio: 'ignore', windowsHide: true });
1084
- child.on('close', () => resolve());
1085
- child.on('error', () => resolve());
1242
+ const child = spawn("docker", args, { stdio: "ignore", windowsHide: true });
1243
+ child.on("close", () => resolve());
1244
+ child.on("error", () => resolve());
1086
1245
  });
1087
1246
  }
1088
1247
  export class UnimplementedSandboxEnv extends EmptySandboxEnv {
@@ -1090,8 +1249,8 @@ export class UnimplementedSandboxEnv extends EmptySandboxEnv {
1090
1249
  return {
1091
1250
  command,
1092
1251
  exitCode: 127,
1093
- stdout: '',
1094
- stderr: 'Sandbox runtime not implemented yet.',
1252
+ stdout: "",
1253
+ stderr: "Sandbox runtime not implemented yet.",
1095
1254
  };
1096
1255
  }
1097
1256
  }
@@ -1102,26 +1261,28 @@ export async function createSandboxEnv(options = {}) {
1102
1261
  async function wrapWithIdleSuspend(env, options) {
1103
1262
  if (!options.idleSuspendMs || options.idleSuspendMs <= 0)
1104
1263
  return env;
1105
- if (typeof env.suspend !== 'function')
1264
+ if (typeof env.suspend !== "function")
1106
1265
  return env;
1107
- const { withIdleSuspend } = await import('./suspending-sandbox.js');
1266
+ const { withIdleSuspend } = await import("./suspending-sandbox.js");
1108
1267
  return withIdleSuspend(env, {
1109
1268
  idleSuspendMs: options.idleSuspendMs,
1110
- ...(options.autoResumeOnAccess !== undefined ? { autoResumeOnAccess: options.autoResumeOnAccess } : {}),
1269
+ ...(options.autoResumeOnAccess !== undefined
1270
+ ? { autoResumeOnAccess: options.autoResumeOnAccess }
1271
+ : {}),
1111
1272
  });
1112
1273
  }
1113
1274
  async function createSandboxEnvInner(options) {
1114
- const backend = options.backend ?? 'empty';
1115
- if (backend === 'empty') {
1275
+ const backend = options.backend ?? "empty";
1276
+ if (backend === "empty") {
1116
1277
  return new EmptySandboxEnv();
1117
1278
  }
1118
- if (backend === 'virtual') {
1119
- const { createVirtualSandboxEnv } = await import('./virtual-sandbox.js');
1279
+ if (backend === "virtual") {
1280
+ const { createVirtualSandboxEnv } = await import("./virtual-sandbox.js");
1120
1281
  return createVirtualSandboxEnv({
1121
1282
  ...(options.workspacePath ? { workspacePath: options.workspacePath } : {}),
1122
1283
  });
1123
1284
  }
1124
- if (backend === 'local') {
1285
+ if (backend === "local") {
1125
1286
  const localOptions = {};
1126
1287
  if (options.workspacePath !== undefined) {
1127
1288
  localOptions.workspacePath = options.workspacePath;
@@ -1132,23 +1293,23 @@ async function createSandboxEnvInner(options) {
1132
1293
  if (options.sessionId !== undefined) {
1133
1294
  localOptions.sessionId = options.sessionId;
1134
1295
  }
1135
- if (typeof options.metadata?.snapshotRoot === 'string') {
1296
+ if (typeof options.metadata?.snapshotRoot === "string") {
1136
1297
  localOptions.snapshotRoot = options.metadata.snapshotRoot;
1137
1298
  }
1138
- if (typeof options.metadata?.outputLimitBytes === 'number')
1299
+ if (typeof options.metadata?.outputLimitBytes === "number")
1139
1300
  localOptions.outputLimitBytes = options.metadata.outputLimitBytes;
1140
- if (typeof options.metadata?.defaultTimeoutMs === 'number')
1301
+ if (typeof options.metadata?.defaultTimeoutMs === "number")
1141
1302
  localOptions.defaultTimeoutMs = options.metadata.defaultTimeoutMs;
1142
- if (typeof options.metadata?.inheritSafeEnv === 'boolean')
1303
+ if (typeof options.metadata?.inheritSafeEnv === "boolean")
1143
1304
  localOptions.inheritSafeEnv = options.metadata.inheritSafeEnv;
1144
1305
  if (Array.isArray(options.metadata?.envAllowlist))
1145
- localOptions.envAllowlist = options.metadata.envAllowlist.filter((value) => typeof value === 'string');
1306
+ localOptions.envAllowlist = options.metadata.envAllowlist.filter((value) => typeof value === "string");
1146
1307
  if (Array.isArray(options.metadata?.allowedPaths))
1147
- localOptions.allowedPaths = options.metadata.allowedPaths.filter((value) => typeof value === 'string');
1308
+ localOptions.allowedPaths = options.metadata.allowedPaths.filter((value) => typeof value === "string");
1148
1309
  return new LocalSandboxEnv(localOptions);
1149
1310
  }
1150
- if (backend === 'docker') {
1151
- const workspacePath = options.workspacePath ?? await fs.mkdtemp(path.join(tmpdir(), 'fabric-harness-docker-'));
1311
+ if (backend === "docker") {
1312
+ const workspacePath = options.workspacePath ?? (await fs.mkdtemp(path.join(tmpdir(), "fabric-harness-docker-")));
1152
1313
  const dockerOptions = {
1153
1314
  workspacePath,
1154
1315
  ownsWorkspace: options.workspacePath === undefined,
@@ -1157,30 +1318,31 @@ async function createSandboxEnvInner(options) {
1157
1318
  dockerOptions.env = options.env;
1158
1319
  if (options.sessionId !== undefined)
1159
1320
  dockerOptions.sessionId = options.sessionId;
1160
- if (typeof options.metadata?.snapshotRoot === 'string')
1321
+ if (typeof options.metadata?.snapshotRoot === "string")
1161
1322
  dockerOptions.snapshotRoot = options.metadata.snapshotRoot;
1162
- if (typeof options.metadata?.image === 'string')
1323
+ if (typeof options.metadata?.image === "string")
1163
1324
  dockerOptions.image = options.metadata.image;
1164
- if (typeof options.metadata?.dockerImage === 'string')
1325
+ if (typeof options.metadata?.dockerImage === "string")
1165
1326
  dockerOptions.image = options.metadata.dockerImage;
1166
- if (typeof options.metadata?.network === 'string' || typeof options.metadata?.network === 'boolean')
1327
+ if (typeof options.metadata?.network === "string" ||
1328
+ typeof options.metadata?.network === "boolean")
1167
1329
  dockerOptions.network = options.metadata.network;
1168
- if (typeof options.metadata?.user === 'string')
1330
+ if (typeof options.metadata?.user === "string")
1169
1331
  dockerOptions.user = options.metadata.user;
1170
- if (typeof options.metadata?.cpus === 'string' || typeof options.metadata?.cpus === 'number')
1332
+ if (typeof options.metadata?.cpus === "string" || typeof options.metadata?.cpus === "number")
1171
1333
  dockerOptions.cpus = options.metadata.cpus;
1172
- if (typeof options.metadata?.memory === 'string')
1334
+ if (typeof options.metadata?.memory === "string")
1173
1335
  dockerOptions.memory = options.metadata.memory;
1174
- if (typeof options.metadata?.pidsLimit === 'number')
1336
+ if (typeof options.metadata?.pidsLimit === "number")
1175
1337
  dockerOptions.pidsLimit = options.metadata.pidsLimit;
1176
- if (typeof options.metadata?.readOnlyRootFilesystem === 'boolean')
1338
+ if (typeof options.metadata?.readOnlyRootFilesystem === "boolean")
1177
1339
  dockerOptions.readOnlyRootFilesystem = options.metadata.readOnlyRootFilesystem;
1178
- if (typeof options.metadata?.mountReadOnly === 'boolean')
1340
+ if (typeof options.metadata?.mountReadOnly === "boolean")
1179
1341
  dockerOptions.mountReadOnly = options.metadata.mountReadOnly;
1180
- if (typeof options.metadata?.outputLimitBytes === 'number')
1342
+ if (typeof options.metadata?.outputLimitBytes === "number")
1181
1343
  dockerOptions.outputLimitBytes = options.metadata.outputLimitBytes;
1182
1344
  if (Array.isArray(options.metadata?.envAllowlist))
1183
- dockerOptions.envAllowlist = options.metadata.envAllowlist.filter((value) => typeof value === 'string');
1345
+ dockerOptions.envAllowlist = options.metadata.envAllowlist.filter((value) => typeof value === "string");
1184
1346
  return new DockerSandboxEnv(dockerOptions);
1185
1347
  }
1186
1348
  const factory = sandboxBackendFactories.get(backend);