@fabric-harness/sdk 6.8.0 → 6.9.1

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