@finalai/agent-provider 0.1.6 → 0.1.7

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.
@@ -3,6 +3,7 @@ import { readAllBytes } from "../sandbox/bytes.mjs";
3
3
  import { streamToString } from "../sandbox/convenience.mjs";
4
4
  import { createInMemoryHandleNetwork } from "../sandbox/testing.mjs";
5
5
  import {
6
+ NetworkPolicy,
6
7
  noSandboxActingUser,
7
8
  noSandboxGuides,
8
9
  noSandboxRepositories,
@@ -211,6 +212,7 @@ const startFromProvider = async (args, provider, overrides = {}) => {
211
212
  variables: noSandboxVariables,
212
213
  repositories: noSandboxRepositories,
213
214
  actingUser: noSandboxActingUser,
215
+ platformNetworkPolicy: async () => void 0,
214
216
  ...args.startContext,
215
217
  ...overrides.startContext
216
218
  };
@@ -222,8 +224,11 @@ const startFromProvider = async (args, provider, overrides = {}) => {
222
224
  conversationId: null
223
225
  };
224
226
  }
225
- const { handle } = await implementation.start(startContext, args.openOptions, artifact);
226
- return handle;
227
+ const { handle, state } = await implementation.start(startContext, args.openOptions, artifact);
228
+ return {
229
+ handle,
230
+ awaitRunning: (timeoutMs) => implementation.awaitRunning(startContext, state, { timeoutMs })
231
+ };
227
232
  };
228
233
  const PLATFORM_VARIABLE = "FINAL_CONFORMANCE_PLATFORM";
229
234
  const SPEC_VARIABLE = "FINAL_CONFORMANCE_SPEC";
@@ -258,7 +263,7 @@ const runPlatformCases = async (args) => {
258
263
  const order = [];
259
264
  const withPlatform = { handle: null };
260
265
  await record("platform environment: provider start", async () => {
261
- withPlatform.handle = await startFromProvider(kit, provider, {
266
+ ({ handle: withPlatform.handle } = await startFromProvider(kit, provider, {
262
267
  environmentOptions: platform.environmentOptions({ env: SPEC_ENV }),
263
268
  startContext: {
264
269
  platformFiles: async () => {
@@ -271,7 +276,7 @@ const runPlatformCases = async (args) => {
271
276
  }
272
277
  },
273
278
  ownBinding: true
274
- });
279
+ }));
275
280
  });
276
281
  const sandbox = withPlatform.handle?.sandbox;
277
282
  if (sandbox != null) {
@@ -309,12 +314,26 @@ const runPlatformCases = async (args) => {
309
314
  }
310
315
  }
311
316
  const withoutPlatform = { handle: null };
317
+ const reported = [];
318
+ const reportOrder = [];
319
+ const allowlistContext = (platformNetworkPolicy) => ({
320
+ platformEnvironment: void 0,
321
+ platformEgressHosts: PLATFORM_EGRESS_HOSTS,
322
+ platformNetworkPolicy,
323
+ platformFiles: async () => {
324
+ reportOrder.push("files");
325
+ return {};
326
+ }
327
+ });
312
328
  await record("platform environment: provider start without it", async () => {
313
- withoutPlatform.handle = await startFromProvider(kit, provider, {
329
+ ({ handle: withoutPlatform.handle } = await startFromProvider(kit, provider, {
314
330
  environmentOptions: platform.environmentOptions({ env: SPEC_ENV, allow: SPEC_ALLOW }),
315
- startContext: { platformEnvironment: void 0, platformEgressHosts: PLATFORM_EGRESS_HOSTS },
331
+ startContext: allowlistContext(async (policy) => {
332
+ reportOrder.push("policy");
333
+ reported.push(policy);
334
+ }),
316
335
  ownBinding: true
317
- });
336
+ }));
318
337
  });
319
338
  const plain = withoutPlatform.handle?.sandbox;
320
339
  if (plain != null) {
@@ -330,17 +349,54 @@ const runPlatformCases = async (args) => {
330
349
  const observe = platform.observedAllowlist;
331
350
  if (observe == null) {
332
351
  args.skip("platform egress hosts: appended to an allowlist", "no observedAllowlist");
352
+ args.skip("platform network policy: reported as applied", "no observedAllowlist");
333
353
  } else {
334
354
  await record("platform egress hosts: appended to an allowlist", async () => {
335
355
  const allow = await observe(plain) ?? [];
336
356
  for (const host of [...SPEC_ALLOW, ...PLATFORM_EGRESS_HOSTS])
337
357
  check(allow.includes(host), `allowlist ${JSON.stringify(allow)} lacks ${host}`);
338
358
  });
359
+ await record("platform network policy: reported as applied", async () => {
360
+ const last = reported.at(-1);
361
+ check(
362
+ last?.mode === NetworkPolicy.Allowlist,
363
+ `reported ${JSON.stringify(reported)}, expected an allowlist`
364
+ );
365
+ const applied = [...await observe(plain) ?? []].sort();
366
+ const allow = [...last?.allow ?? []].sort();
367
+ check(
368
+ JSON.stringify(allow) === JSON.stringify(applied),
369
+ `reported ${JSON.stringify(allow)}, applied ${JSON.stringify(applied)}`
370
+ );
371
+ check(
372
+ reportOrder.indexOf("policy") < reportOrder.indexOf("files"),
373
+ `platformFiles were written before the policy was reported: ${reportOrder.join(", ")}`
374
+ );
375
+ });
339
376
  }
340
377
  } finally {
341
378
  await withoutPlatform.handle?.onSandboxDelete({ reason: "conformance" }).catch(() => void 0);
342
379
  }
343
380
  }
381
+ if (platform.observedAllowlist == null) {
382
+ args.skip("platform network policy: a rejected report fails the start", "no observedAllowlist");
383
+ } else {
384
+ await record("platform network policy: a rejected report fails the start", async () => {
385
+ const started = await startFromProvider(kit, provider, {
386
+ environmentOptions: platform.environmentOptions({ env: SPEC_ENV, allow: SPEC_ALLOW }),
387
+ startContext: allowlistContext(async () => {
388
+ throw new Error("conformance: the policy was not recorded");
389
+ }),
390
+ ownBinding: true
391
+ }).then(
392
+ ({ handle }) => handle,
393
+ () => null
394
+ );
395
+ if (started == null) return;
396
+ await started.onSandboxDelete({ reason: "conformance" }).catch(() => void 0);
397
+ throw new Error("a start whose policy report failed returned a sandbox");
398
+ });
399
+ }
344
400
  await record("platform environment: reserved names refused", async () => {
345
401
  const started = await startFromProvider(kit, provider, {
346
402
  environmentOptions: platform.environmentOptions({
@@ -348,7 +404,7 @@ const runPlatformCases = async (args) => {
348
404
  }),
349
405
  ownBinding: true
350
406
  }).then(
351
- (handle) => handle,
407
+ ({ handle }) => handle,
352
408
  () => null
353
409
  );
354
410
  if (started == null) return;
@@ -387,8 +443,17 @@ const runSandboxConformance = async (args) => {
387
443
  throw new Error("runSandboxConformance needs a handle or a provider");
388
444
  const provider = args.provider;
389
445
  await record("provider start", async () => {
390
- started.handle = await startFromProvider(args, provider);
446
+ ({ handle: started.handle, awaitRunning: started.awaitRunning } = await startFromProvider(
447
+ args,
448
+ provider
449
+ ));
391
450
  });
451
+ const awaitRunning = started.awaitRunning;
452
+ if (awaitRunning != null)
453
+ await record(
454
+ "provider awaitRunning: resolves for a started sandbox",
455
+ () => awaitRunning(timeoutMs)
456
+ );
392
457
  sandbox = started.handle?.sandbox ?? null;
393
458
  }
394
459
  if (sandbox == null) return { passed: false, cases };
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../../src/conformance/sandbox-kit.ts"],
4
- "sourcesContent": ["import type { JsonValue } from \"../json.mjs\";\nimport { SandboxAccess } from \"../manifest.mjs\";\nimport { readAllBytes } from \"../sandbox/bytes.mjs\";\nimport { streamToString } from \"../sandbox/convenience.mjs\";\nimport { createInMemoryHandleNetwork } from \"../sandbox/testing.mjs\";\nimport {\n noSandboxActingUser,\n noSandboxGuides,\n noSandboxRepositories,\n noSandboxVariables,\n SandboxEntryType,\n type AnySandboxProviderIface,\n type NetworkSandboxSessionIface,\n type SandboxPrepareContextIface,\n type SandboxProviderHandleIface,\n type SandboxStartContextIface,\n} from \"../sandbox/types.mjs\";\nimport { HandleRpcErrorCode, isHandleRpcError } from \"../sandbox/wire.mjs\";\nimport { ConformanceCaseStatus, type ConformanceCaseResultIface } from \"./harness-kit.mjs\";\n\n// Sandbox conformance: files, streams with\n// multi-megabyte content, ranged reads, process I/O and kill, run directly on\n// the handle and again through the handle RPC (client and server over an\n// in-memory connection), plus the server's read-only access policy. Commands\n// used: echo, cat, sleep and `exit` under `shell: true`, and printenv for the\n// platform environment cases.\n\nexport interface RunSandboxConformanceArgsIface {\n // Either a started handle, or a provider the kit prepares and starts.\n handle?: NetworkSandboxSessionIface;\n provider?: AnySandboxProviderIface;\n environmentOptions?: JsonValue;\n openOptions?: JsonValue;\n prepareContext?: Partial<SandboxPrepareContextIface>;\n startContext?: Partial<SandboxStartContextIface>;\n // Also run the cases through the handle RPC (default true).\n viaWire?: boolean;\n largeFileBytes?: number;\n timeoutMs?: number;\n // Also run the platform environment cases, on sandboxes of their own (needs `provider`).\n platform?: SandboxPlatformConformanceIface;\n}\n\n// How the platform environment cases declare a spec for the provider under test.\nexport interface SandboxPlatformConformanceIface {\n // Environment options whose spec sets `env` as plain variables for every\n // process and, when `allow` is given, an allowlist egress policy of those hosts.\n environmentOptions(args: { env: Record<string, string>; allow?: string[] }): JsonValue;\n // The allowlist the provider gave its backend for this sandbox. Absent: the\n // egress hosts case is skipped.\n observedAllowlist?(sandbox: NetworkSandboxSessionIface): Promise<readonly string[] | null>;\n}\n\nexport interface SandboxConformanceReportIface {\n passed: boolean;\n cases: ConformanceCaseResultIface[];\n}\n\ninterface StartedProviderIface {\n handle: SandboxProviderHandleIface<NetworkSandboxSessionIface> | null;\n}\n\nconst check = (condition: boolean, message: string) => {\n if (!condition) throw new Error(message);\n};\n\nconst patternBytes = (size: number, seed: number): Uint8Array => {\n const bytes = new Uint8Array(size);\n let state = seed >>> 0;\n for (let i = 0; i < size; i += 1) {\n state = (Math.imul(state, 1664525) + 1013904223) >>> 0;\n bytes[i] = state >>> 24;\n }\n return bytes;\n};\n\nconst chunked = (bytes: Uint8Array, chunk: number): ReadableStream<Uint8Array> => {\n let offset = 0;\n return new ReadableStream<Uint8Array>({\n pull: (controller) => {\n if (offset >= bytes.byteLength) {\n controller.close();\n return;\n }\n controller.enqueue(bytes.slice(offset, offset + chunk));\n offset += chunk;\n },\n });\n};\n\nconst sameBytes = (a: Uint8Array, b: Uint8Array) =>\n a.byteLength === b.byteLength && a.every((value, i) => value === b[i]);\n\nconst withTimeout = async <T>(promise: Promise<T>, ms: number, what: string): Promise<T> => {\n let timer: ReturnType<typeof setTimeout> | null = null;\n try {\n return await Promise.race([\n promise,\n new Promise<never>((_, reject) => {\n timer = setTimeout(() => reject(new Error(`${what} timed out after ${ms} ms`)), ms);\n }),\n ]);\n } finally {\n if (timer != null) clearTimeout(timer);\n }\n};\n\ntype SandboxCase = {\n name: string;\n run: (sandbox: NetworkSandboxSessionIface, root: string) => Promise<string | void>;\n};\n\nconst sandboxCases = (largeFileBytes: number): SandboxCase[] => [\n {\n name: 'describe',\n run: async (sandbox) => {\n check(sandbox.id.length > 0, 'empty id');\n check(\n sandbox.defaultWorkingDirectory.startsWith('/'),\n 'defaultWorkingDirectory is not absolute',\n );\n check(\n sandbox.resolvePath('a/b') === `${sandbox.defaultWorkingDirectory.replace(/\\/$/, '')}/a/b`,\n 'resolvePath',\n );\n },\n },\n {\n name: 'text files',\n run: async (sandbox, root) => {\n const path = `${root}/nested/dir/a.txt`;\n await sandbox.writeTextFile({ path, content: 'first' });\n await sandbox.writeTextFile({ path, content: 'h\u00E9llo\\n' });\n check((await sandbox.readTextFile({ path })) === 'h\u00E9llo\\n', 'text round trip');\n check(\n (await sandbox.readTextFile({ path: `${root}/missing.txt` })) == null,\n 'missing text file is not null',\n );\n check(\n (await sandbox.readFile({ path: `${root}/missing.txt` })) == null,\n 'missing file stream is not null',\n );\n },\n },\n {\n name: 'ranged reads',\n run: async (sandbox, root) => {\n const path = `${root}/lines.txt`;\n await sandbox.writeTextFile({ path, content: 'l1\\nl2\\nl3\\nl4\\n' });\n check(\n (await sandbox.readTextFile({ path, startLine: 2, endLine: 3 })) === 'l2\\nl3\\n',\n 'lines 2-3',\n );\n check(\n (await sandbox.readTextFile({ path, startLine: 4, endLine: 99 })) === 'l4\\n',\n 'endLine past EOF',\n );\n },\n },\n {\n name: 'multi-megabyte streams',\n run: async (sandbox, root) => {\n const path = `${root}/large.bin`;\n const content = patternBytes(largeFileBytes, largeFileBytes);\n await sandbox.writeFile({ path, content: chunked(content, 300_000) });\n const stream = await sandbox.readFile({ path });\n check(stream != null, 'large file not found');\n if (stream == null) return;\n check(sameBytes(await readAllBytes(stream), content), 'streamed bytes differ');\n const binary = await sandbox.readBinaryFile({ path });\n check(binary != null && sameBytes(binary, content), 'readBinaryFile differs');\n const small = patternBytes(1000, 7);\n await sandbox.writeBinaryFile({ path: `${root}/small.bin`, content: small });\n const back = await sandbox.readBinaryFile({ path: `${root}/small.bin` });\n check(back != null && sameBytes(back, small), 'binary round trip');\n return `${largeFileBytes} bytes`;\n },\n },\n {\n name: 'stat, readDir, removePath',\n run: async (sandbox, root) => {\n await sandbox.writeTextFile({ path: `${root}/tree/x.txt`, content: 'xyz' });\n await sandbox.writeTextFile({ path: `${root}/tree/sub/y.txt`, content: 'y' });\n const stat = await sandbox.stat({ path: `${root}/tree/x.txt` });\n check(stat?.type === SandboxEntryType.File && stat.size === 3, 'file stat');\n check(\n (await sandbox.stat({ path: `${root}/tree` }))?.type === SandboxEntryType.Directory,\n 'directory stat',\n );\n check(\n (await sandbox.stat({ path: `${root}/tree/none` })) == null,\n 'missing stat is not null',\n );\n const names = (await sandbox.readDir({ path: `${root}/tree` }))\n .map((entry) => entry.name)\n .sort();\n check(\n JSON.stringify(names) === JSON.stringify(['sub', 'x.txt']),\n `readDir returned ${names.join(',')}`,\n );\n await sandbox.removePath({ path: `${root}/tree/none`, force: true });\n await sandbox.removePath({ path: `${root}/tree`, recursive: true });\n check(\n (await sandbox.stat({ path: `${root}/tree/x.txt` })) == null,\n 'recursive remove left files',\n );\n },\n },\n {\n name: 'process output and exit codes',\n run: async (sandbox) => {\n const echo = await sandbox.run({ command: 'echo', args: ['hello', 'world'] });\n check(\n echo.exitCode === 0 && echo.stdout === 'hello world\\n',\n `echo: ${JSON.stringify(echo)}`,\n );\n const shell = await sandbox.run({ command: 'echo out; echo err >&2; exit 3', shell: true });\n check(\n shell.exitCode === 3 && shell.stdout === 'out\\n' && shell.stderr === 'err\\n',\n `shell: ${JSON.stringify(shell)}`,\n );\n },\n },\n {\n name: 'process stdin',\n run: async (sandbox) => {\n const piped = await sandbox.run({ command: 'cat', stdin: 'from stdin' });\n check(piped.stdout === 'from stdin', `run stdin: ${JSON.stringify(piped)}`);\n const cat = await sandbox.spawn({ command: 'cat' });\n const output = streamToString(cat.stdout);\n await cat.write('a');\n await cat.write('b', { end: true });\n check((await output) === 'ab', 'spawned cat echoed wrong data');\n check((await cat.wait()).exitCode === 0, 'cat exit code');\n },\n },\n {\n name: 'process kill',\n run: async (sandbox) => {\n const sleeper = await sandbox.spawn({ command: 'sleep', args: ['30'] });\n await sleeper.kill();\n const result = await withTimeout(sleeper.wait(), 5_000, 'wait after kill');\n check(result.exitCode !== 0, 'killed process exited 0');\n },\n },\n];\n\nconst startFromProvider = async (\n args: RunSandboxConformanceArgsIface,\n provider: AnySandboxProviderIface,\n overrides: {\n environmentOptions?: JsonValue;\n startContext?: Partial<SandboxStartContextIface>;\n // A binding (and so a sandbox) of its own, whatever session the caller's context names.\n ownBinding?: boolean;\n } = {},\n): Promise<SandboxProviderHandleIface<NetworkSandboxSessionIface>> => {\n const implementation = provider.definition.environment(\n overrides.environmentOptions ?? args.environmentOptions,\n );\n const prepareContext: SandboxPrepareContextIface = {\n files: {},\n resources: {},\n sourceRevision: 'conformance',\n storagePath: '/tmp/final-conformance',\n organizationId: 'conformance',\n guides: noSandboxGuides,\n actingUser: noSandboxActingUser,\n ...args.prepareContext,\n };\n const artifact = await implementation.prepare(prepareContext);\n const startContext: SandboxStartContextIface = {\n session: {\n id: crypto.randomUUID(),\n organizationId: 'conformance',\n conversationId: null,\n definitionId: 'conformance',\n bindingId: crypto.randomUUID(),\n target: 'conformance',\n },\n storagePath: '/tmp/final-conformance',\n guides: noSandboxGuides,\n variables: noSandboxVariables,\n repositories: noSandboxRepositories,\n actingUser: noSandboxActingUser,\n ...args.startContext,\n ...overrides.startContext,\n };\n if (overrides.ownBinding === true) {\n startContext.session = {\n ...startContext.session,\n id: crypto.randomUUID(),\n bindingId: crypto.randomUUID(),\n conversationId: null,\n };\n }\n const { handle } = await implementation.start(startContext, args.openOptions, artifact);\n return handle;\n};\n\nconst PLATFORM_VARIABLE = 'FINAL_CONFORMANCE_PLATFORM';\nconst SPEC_VARIABLE = 'FINAL_CONFORMANCE_SPEC';\nconst SHARED_VARIABLE = 'FINAL_CONFORMANCE_SHARED';\nconst SPEC_ENV = { [SPEC_VARIABLE]: 'spec', [SHARED_VARIABLE]: 'spec' };\nconst SPEC_ALLOW = ['conformance.example.com'];\nconst PLATFORM_EGRESS_HOSTS = ['egress.conformance.example.com'];\n\n// A variable as a spawned process sees it; null when unset.\nconst variableIn = async (\n sandbox: NetworkSandboxSessionIface,\n name: string,\n): Promise<string | null> => {\n const process = await sandbox.spawn({ command: 'printenv', args: [name] });\n const [stdout, { exitCode }] = await Promise.all([\n streamToString(process.stdout),\n process.wait(),\n ]);\n return exitCode === 0 ? stdout.replace(/\\n$/, '') : null;\n};\n\nconst expectVariables = async (\n sandbox: NetworkSandboxSessionIface,\n expected: Record<string, string | null>,\n) => {\n for (const [name, value] of Object.entries(expected)) {\n const actual = await variableIn(sandbox, name);\n check(\n actual === value,\n `${name} is ${JSON.stringify(actual)}, expected ${JSON.stringify(value)}`,\n );\n }\n};\n\ntype RecordCase = (name: string, run: () => Promise<string | void>) => Promise<void>;\n\n// The start context's platformFiles are written before any process runs;\n// platformEnvironment reaches every process, read again for each one and over\n// the spec's env; platformEgressHosts join an allowlist;\n// a spec naming a platform variable is refused.\nconst runPlatformCases = async (args: {\n kit: RunSandboxConformanceArgsIface;\n provider: AnySandboxProviderIface;\n platform: SandboxPlatformConformanceIface;\n record: RecordCase;\n skip: (name: string, detail: string) => void;\n}) => {\n const { kit, provider, platform, record } = args;\n let platformValues: Record<string, string> = {\n [PLATFORM_VARIABLE]: 'first',\n [SHARED_VARIABLE]: 'platform',\n };\n const filePath = `/tmp/final-conformance-${crypto.randomUUID().slice(0, 8)}/platform/ca.pem`;\n const order: string[] = [];\n const withPlatform: StartedProviderIface = { handle: null };\n await record('platform environment: provider start', async () => {\n withPlatform.handle = await startFromProvider(kit, provider, {\n environmentOptions: platform.environmentOptions({ env: SPEC_ENV }),\n startContext: {\n platformFiles: async () => {\n order.push('files');\n return { [filePath]: 'conformance CA\\n' };\n },\n platformEnvironment: async () => {\n order.push('environment');\n return { ...platformValues };\n },\n },\n ownBinding: true,\n });\n });\n const sandbox = withPlatform.handle?.sandbox;\n if (sandbox != null) {\n try {\n await record('platform files: written before any process', async () => {\n check(\n order.indexOf('files') === 0,\n `platformEnvironment was read before platformFiles: ${order.join(', ')}`,\n );\n const content = await sandbox.readTextFile({ path: filePath });\n check(content === 'conformance CA\\n', `${filePath} holds ${JSON.stringify(content)}`);\n });\n await record('platform environment: reaches spawned processes', async () => {\n await expectVariables(sandbox, { [PLATFORM_VARIABLE]: 'first' });\n const run = await sandbox.run({ command: 'printenv', args: [PLATFORM_VARIABLE] });\n check(run.stdout === 'first\\n', `run saw ${JSON.stringify(run.stdout)}`);\n });\n await record('platform environment: read again for every process', async () => {\n platformValues = { ...platformValues, [PLATFORM_VARIABLE]: 'second' };\n await expectVariables(sandbox, { [PLATFORM_VARIABLE]: 'second' });\n });\n await record('platform environment: overrides the spec env', async () => {\n await expectVariables(sandbox, { [SHARED_VARIABLE]: 'platform', [SPEC_VARIABLE]: 'spec' });\n });\n await record('platform environment: {} leaves the spec env', async () => {\n platformValues = {};\n await expectVariables(sandbox, {\n [PLATFORM_VARIABLE]: null,\n [SHARED_VARIABLE]: 'spec',\n [SPEC_VARIABLE]: 'spec',\n });\n });\n } finally {\n await withPlatform.handle?.onSandboxDelete({ reason: 'conformance' }).catch(() => undefined);\n }\n }\n\n const withoutPlatform: StartedProviderIface = { handle: null };\n await record('platform environment: provider start without it', async () => {\n withoutPlatform.handle = await startFromProvider(kit, provider, {\n environmentOptions: platform.environmentOptions({ env: SPEC_ENV, allow: SPEC_ALLOW }),\n startContext: { platformEnvironment: undefined, platformEgressHosts: PLATFORM_EGRESS_HOSTS },\n ownBinding: true,\n });\n });\n const plain = withoutPlatform.handle?.sandbox;\n if (plain != null) {\n try {\n await record('platform environment: absent leaves the spec env', () =>\n expectVariables(plain, {\n [PLATFORM_VARIABLE]: null,\n [SHARED_VARIABLE]: 'spec',\n [SPEC_VARIABLE]: 'spec',\n }),\n );\n const observe = platform.observedAllowlist;\n if (observe == null) {\n args.skip('platform egress hosts: appended to an allowlist', 'no observedAllowlist');\n } else {\n await record('platform egress hosts: appended to an allowlist', async () => {\n const allow = (await observe(plain)) ?? [];\n for (const host of [...SPEC_ALLOW, ...PLATFORM_EGRESS_HOSTS])\n check(allow.includes(host), `allowlist ${JSON.stringify(allow)} lacks ${host}`);\n });\n }\n } finally {\n await withoutPlatform.handle\n ?.onSandboxDelete({ reason: 'conformance' })\n .catch(() => undefined);\n }\n }\n\n await record('platform environment: reserved names refused', async () => {\n const started = await startFromProvider(kit, provider, {\n environmentOptions: platform.environmentOptions({\n env: { HTTPS_PROXY: 'http://spec.example.com' },\n }),\n ownBinding: true,\n }).then(\n (handle) => handle,\n () => null,\n );\n if (started == null) return;\n await started.onSandboxDelete({ reason: 'conformance' }).catch(() => undefined);\n throw new Error('a spec setting HTTPS_PROXY started');\n });\n};\n\nexport const runSandboxConformance = async (\n args: RunSandboxConformanceArgsIface,\n): Promise<SandboxConformanceReportIface> => {\n const timeoutMs = args.timeoutMs ?? 30_000;\n const cases: ConformanceCaseResultIface[] = [];\n const record: RecordCase = async (name, run) => {\n const started = Date.now();\n try {\n const detail = await withTimeout(run(), timeoutMs, name);\n cases.push({\n name,\n status: ConformanceCaseStatus.Passed,\n durationMs: Date.now() - started,\n error: null,\n detail: detail ?? null,\n });\n } catch (error) {\n cases.push({\n name,\n status: ConformanceCaseStatus.Failed,\n durationMs: Date.now() - started,\n error: error instanceof Error ? error.message : String(error),\n detail: null,\n });\n }\n };\n\n // A holder, so the assignment inside the closure is visible to the narrowing.\n const started: StartedProviderIface = { handle: null };\n let sandbox = args.handle ?? null;\n if (sandbox == null) {\n if (args.provider == null)\n throw new Error('runSandboxConformance needs a handle or a provider');\n const provider = args.provider;\n await record('provider start', async () => {\n started.handle = await startFromProvider(args, provider);\n });\n sandbox = started.handle?.sandbox ?? null;\n }\n if (sandbox == null) return { passed: false, cases };\n const target = sandbox;\n\n const root = target.resolvePath(`conformance-${crypto.randomUUID().slice(0, 8)}`);\n const list = sandboxCases(args.largeFileBytes ?? 5 * 1024 * 1024);\n for (const entry of list) await record(entry.name, () => entry.run(target, root));\n\n if (args.viaWire !== false) {\n const network = createInMemoryHandleNetwork();\n network.serve({ url: 'mem://conformance', sandbox: target });\n network.serve({\n url: 'mem://conformance-read',\n sandbox: target,\n access: { mode: SandboxAccess.Read, lifecycle: false },\n });\n const client = await network.connect({ url: 'mem://conformance', token: 'conformance' });\n try {\n const wireRoot = `${root}-wire`;\n for (const entry of list)\n await record(`handle rpc: ${entry.name}`, () => entry.run(client, wireRoot));\n await record('handle rpc: read-only access policy', async () => {\n const readOnly = await network.connect({\n url: 'mem://conformance-read',\n token: 'conformance',\n });\n try {\n await target.writeTextFile({ path: `${root}/ro.txt`, content: 'visible' });\n check(\n (await readOnly.readTextFile({ path: `${root}/ro.txt` })) === 'visible',\n 'read failed on a read binding',\n );\n const attempts: [string, Promise<unknown>][] = [\n [\n 'writeTextFile',\n readOnly.writeTextFile({ path: `${root}/ro.txt`, content: 'changed' }),\n ],\n ['run', readOnly.run({ command: 'echo' })],\n ['spawn', readOnly.spawn({ command: 'echo' })],\n ['removePath', readOnly.removePath({ path: `${root}/ro.txt` })],\n ];\n for (const [what, attempt] of attempts) {\n const error = await attempt.then(\n () => null,\n (cause: unknown) => cause,\n );\n check(\n isHandleRpcError(error) && error.code === HandleRpcErrorCode.Forbidden,\n `${what} was not rejected`,\n );\n }\n check(\n (await target.readTextFile({ path: `${root}/ro.txt` })) === 'visible',\n 'a read binding changed the file',\n );\n } finally {\n readOnly.close();\n }\n });\n } finally {\n client.close();\n await target\n .removePath({ path: `${root}-wire`, recursive: true, force: true })\n .catch(() => undefined);\n }\n }\n\n await target.removePath({ path: root, recursive: true, force: true }).catch(() => undefined);\n await started.handle?.onSandboxDelete({ reason: 'conformance' }).catch(() => undefined);\n\n if (args.platform != null && args.provider != null) {\n await runPlatformCases({\n kit: args,\n provider: args.provider,\n platform: args.platform,\n record,\n skip: (name, detail) =>\n cases.push({\n name,\n status: ConformanceCaseStatus.Skipped,\n durationMs: 0,\n error: null,\n detail,\n }),\n });\n }\n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AAAA,YACT;AAAA,UACF;AACA;AAAA,YACG,MAAM,OAAO,aAAa,EAAE,MAAM,GAAG,IAAI,UAAU,CAAC,MAAO;AAAA,YAC5D;AAAA,UACF;AAAA,QACF,UAAE;AACA,mBAAS,MAAM;AAAA,QACjB;AAAA,MACF,CAAC;AAAA,IACH,UAAE;AACA,aAAO,MAAM;AACb,YAAM,OACH,WAAW,EAAE,MAAM,GAAG,IAAI,SAAS,WAAW,MAAM,OAAO,KAAK,CAAC,EACjE,MAAM,MAAM,MAAS;AAAA,IAC1B;AAAA,EACF;AAEA,QAAM,OAAO,WAAW,EAAE,MAAM,MAAM,WAAW,MAAM,OAAO,KAAK,CAAC,EAAE,MAAM,MAAM,MAAS;AAC3F,QAAM,QAAQ,QAAQ,gBAAgB,EAAE,QAAQ,cAAc,CAAC,EAAE,MAAM,MAAM,MAAS;AAEtF,MAAI,KAAK,YAAY,QAAQ,KAAK,YAAY,MAAM;AAClD,UAAM,iBAAiB;AAAA,MACrB,KAAK;AAAA,MACL,UAAU,KAAK;AAAA,MACf,UAAU,KAAK;AAAA,MACf;AAAA,MACA,MAAM,CAAC,MAAM,WACX,MAAM,KAAK;AAAA,QACT;AAAA,QACA,QAAQ,sBAAsB;AAAA,QAC9B,YAAY;AAAA,QACZ,OAAO;AAAA,QACP;AAAA,MACF,CAAC;AAAA,IACL,CAAC;AAAA,EACH;AACA,SAAO,EAAE,QAAQ,MAAM,MAAM,CAAC,UAAU,MAAM,WAAW,sBAAsB,MAAM,GAAG,MAAM;AAChG;",
4
+ "sourcesContent": ["import type { JsonValue } from \"../json.mjs\";\nimport { SandboxAccess } from \"../manifest.mjs\";\nimport { readAllBytes } from \"../sandbox/bytes.mjs\";\nimport { streamToString } from \"../sandbox/convenience.mjs\";\nimport { createInMemoryHandleNetwork } from \"../sandbox/testing.mjs\";\nimport {\n NetworkPolicy,\n noSandboxActingUser,\n noSandboxGuides,\n noSandboxRepositories,\n noSandboxVariables,\n SandboxEntryType,\n type AnySandboxProviderIface,\n type NetworkPolicyIface,\n type NetworkSandboxSessionIface,\n type SandboxPrepareContextIface,\n type SandboxProviderHandleIface,\n type SandboxStartContextIface,\n} from \"../sandbox/types.mjs\";\nimport { HandleRpcErrorCode, isHandleRpcError } from \"../sandbox/wire.mjs\";\nimport { ConformanceCaseStatus, type ConformanceCaseResultIface } from \"./harness-kit.mjs\";\n\n// Sandbox conformance: files, streams with\n// multi-megabyte content, ranged reads, process I/O and kill, run directly on\n// the handle and again through the handle RPC (client and server over an\n// in-memory connection), plus the server's read-only access policy. Commands\n// used: echo, cat, sleep and `exit` under `shell: true`, and printenv for the\n// platform environment cases. A provider start also checks that awaitRunning\n// resolves for the sandbox it started.\n\nexport interface RunSandboxConformanceArgsIface {\n // Either a started handle, or a provider the kit prepares and starts.\n handle?: NetworkSandboxSessionIface;\n provider?: AnySandboxProviderIface;\n environmentOptions?: JsonValue;\n openOptions?: JsonValue;\n prepareContext?: Partial<SandboxPrepareContextIface>;\n startContext?: Partial<SandboxStartContextIface>;\n // Also run the cases through the handle RPC (default true).\n viaWire?: boolean;\n largeFileBytes?: number;\n timeoutMs?: number;\n // Also run the platform environment cases, on sandboxes of their own (needs `provider`).\n platform?: SandboxPlatformConformanceIface;\n}\n\n// How the platform environment cases declare a spec for the provider under test.\nexport interface SandboxPlatformConformanceIface {\n // Environment options whose spec sets `env` as plain variables for every\n // process and, when `allow` is given, an allowlist egress policy of those hosts.\n environmentOptions(args: { env: Record<string, string>; allow?: string[] }): JsonValue;\n // The allowlist the provider gave its backend for this sandbox. Absent: the\n // egress hosts and network policy report cases are skipped.\n observedAllowlist?(sandbox: NetworkSandboxSessionIface): Promise<readonly string[] | null>;\n}\n\nexport interface SandboxConformanceReportIface {\n passed: boolean;\n cases: ConformanceCaseResultIface[];\n}\n\ninterface StartedProviderIface {\n handle: SandboxProviderHandleIface<NetworkSandboxSessionIface> | null;\n // The provider's awaitRunning for the sandbox it started.\n awaitRunning?: (timeoutMs: number) => Promise<void>;\n}\n\ninterface ProviderStartIface {\n handle: SandboxProviderHandleIface<NetworkSandboxSessionIface>;\n awaitRunning: (timeoutMs: number) => Promise<void>;\n}\n\nconst check = (condition: boolean, message: string) => {\n if (!condition) throw new Error(message);\n};\n\nconst patternBytes = (size: number, seed: number): Uint8Array => {\n const bytes = new Uint8Array(size);\n let state = seed >>> 0;\n for (let i = 0; i < size; i += 1) {\n state = (Math.imul(state, 1664525) + 1013904223) >>> 0;\n bytes[i] = state >>> 24;\n }\n return bytes;\n};\n\nconst chunked = (bytes: Uint8Array, chunk: number): ReadableStream<Uint8Array> => {\n let offset = 0;\n return new ReadableStream<Uint8Array>({\n pull: (controller) => {\n if (offset >= bytes.byteLength) {\n controller.close();\n return;\n }\n controller.enqueue(bytes.slice(offset, offset + chunk));\n offset += chunk;\n },\n });\n};\n\nconst sameBytes = (a: Uint8Array, b: Uint8Array) =>\n a.byteLength === b.byteLength && a.every((value, i) => value === b[i]);\n\nconst withTimeout = async <T>(promise: Promise<T>, ms: number, what: string): Promise<T> => {\n let timer: ReturnType<typeof setTimeout> | null = null;\n try {\n return await Promise.race([\n promise,\n new Promise<never>((_, reject) => {\n timer = setTimeout(() => reject(new Error(`${what} timed out after ${ms} ms`)), ms);\n }),\n ]);\n } finally {\n if (timer != null) clearTimeout(timer);\n }\n};\n\ntype SandboxCase = {\n name: string;\n run: (sandbox: NetworkSandboxSessionIface, root: string) => Promise<string | void>;\n};\n\nconst sandboxCases = (largeFileBytes: number): SandboxCase[] => [\n {\n name: 'describe',\n run: async (sandbox) => {\n check(sandbox.id.length > 0, 'empty id');\n check(\n sandbox.defaultWorkingDirectory.startsWith('/'),\n 'defaultWorkingDirectory is not absolute',\n );\n check(\n sandbox.resolvePath('a/b') === `${sandbox.defaultWorkingDirectory.replace(/\\/$/, '')}/a/b`,\n 'resolvePath',\n );\n },\n },\n {\n name: 'text files',\n run: async (sandbox, root) => {\n const path = `${root}/nested/dir/a.txt`;\n await sandbox.writeTextFile({ path, content: 'first' });\n await sandbox.writeTextFile({ path, content: 'h\u00E9llo\\n' });\n check((await sandbox.readTextFile({ path })) === 'h\u00E9llo\\n', 'text round trip');\n check(\n (await sandbox.readTextFile({ path: `${root}/missing.txt` })) == null,\n 'missing text file is not null',\n );\n check(\n (await sandbox.readFile({ path: `${root}/missing.txt` })) == null,\n 'missing file stream is not null',\n );\n },\n },\n {\n name: 'ranged reads',\n run: async (sandbox, root) => {\n const path = `${root}/lines.txt`;\n await sandbox.writeTextFile({ path, content: 'l1\\nl2\\nl3\\nl4\\n' });\n check(\n (await sandbox.readTextFile({ path, startLine: 2, endLine: 3 })) === 'l2\\nl3\\n',\n 'lines 2-3',\n );\n check(\n (await sandbox.readTextFile({ path, startLine: 4, endLine: 99 })) === 'l4\\n',\n 'endLine past EOF',\n );\n },\n },\n {\n name: 'multi-megabyte streams',\n run: async (sandbox, root) => {\n const path = `${root}/large.bin`;\n const content = patternBytes(largeFileBytes, largeFileBytes);\n await sandbox.writeFile({ path, content: chunked(content, 300_000) });\n const stream = await sandbox.readFile({ path });\n check(stream != null, 'large file not found');\n if (stream == null) return;\n check(sameBytes(await readAllBytes(stream), content), 'streamed bytes differ');\n const binary = await sandbox.readBinaryFile({ path });\n check(binary != null && sameBytes(binary, content), 'readBinaryFile differs');\n const small = patternBytes(1000, 7);\n await sandbox.writeBinaryFile({ path: `${root}/small.bin`, content: small });\n const back = await sandbox.readBinaryFile({ path: `${root}/small.bin` });\n check(back != null && sameBytes(back, small), 'binary round trip');\n return `${largeFileBytes} bytes`;\n },\n },\n {\n name: 'stat, readDir, removePath',\n run: async (sandbox, root) => {\n await sandbox.writeTextFile({ path: `${root}/tree/x.txt`, content: 'xyz' });\n await sandbox.writeTextFile({ path: `${root}/tree/sub/y.txt`, content: 'y' });\n const stat = await sandbox.stat({ path: `${root}/tree/x.txt` });\n check(stat?.type === SandboxEntryType.File && stat.size === 3, 'file stat');\n check(\n (await sandbox.stat({ path: `${root}/tree` }))?.type === SandboxEntryType.Directory,\n 'directory stat',\n );\n check(\n (await sandbox.stat({ path: `${root}/tree/none` })) == null,\n 'missing stat is not null',\n );\n const names = (await sandbox.readDir({ path: `${root}/tree` }))\n .map((entry) => entry.name)\n .sort();\n check(\n JSON.stringify(names) === JSON.stringify(['sub', 'x.txt']),\n `readDir returned ${names.join(',')}`,\n );\n await sandbox.removePath({ path: `${root}/tree/none`, force: true });\n await sandbox.removePath({ path: `${root}/tree`, recursive: true });\n check(\n (await sandbox.stat({ path: `${root}/tree/x.txt` })) == null,\n 'recursive remove left files',\n );\n },\n },\n {\n name: 'process output and exit codes',\n run: async (sandbox) => {\n const echo = await sandbox.run({ command: 'echo', args: ['hello', 'world'] });\n check(\n echo.exitCode === 0 && echo.stdout === 'hello world\\n',\n `echo: ${JSON.stringify(echo)}`,\n );\n const shell = await sandbox.run({ command: 'echo out; echo err >&2; exit 3', shell: true });\n check(\n shell.exitCode === 3 && shell.stdout === 'out\\n' && shell.stderr === 'err\\n',\n `shell: ${JSON.stringify(shell)}`,\n );\n },\n },\n {\n name: 'process stdin',\n run: async (sandbox) => {\n const piped = await sandbox.run({ command: 'cat', stdin: 'from stdin' });\n check(piped.stdout === 'from stdin', `run stdin: ${JSON.stringify(piped)}`);\n const cat = await sandbox.spawn({ command: 'cat' });\n const output = streamToString(cat.stdout);\n await cat.write('a');\n await cat.write('b', { end: true });\n check((await output) === 'ab', 'spawned cat echoed wrong data');\n check((await cat.wait()).exitCode === 0, 'cat exit code');\n },\n },\n {\n name: 'process kill',\n run: async (sandbox) => {\n const sleeper = await sandbox.spawn({ command: 'sleep', args: ['30'] });\n await sleeper.kill();\n const result = await withTimeout(sleeper.wait(), 5_000, 'wait after kill');\n check(result.exitCode !== 0, 'killed process exited 0');\n },\n },\n];\n\nconst startFromProvider = async (\n args: RunSandboxConformanceArgsIface,\n provider: AnySandboxProviderIface,\n overrides: {\n environmentOptions?: JsonValue;\n startContext?: Partial<SandboxStartContextIface>;\n // A binding (and so a sandbox) of its own, whatever session the caller's context names.\n ownBinding?: boolean;\n } = {},\n): Promise<ProviderStartIface> => {\n const implementation = provider.definition.environment(\n overrides.environmentOptions ?? args.environmentOptions,\n );\n const prepareContext: SandboxPrepareContextIface = {\n files: {},\n resources: {},\n sourceRevision: 'conformance',\n storagePath: '/tmp/final-conformance',\n organizationId: 'conformance',\n guides: noSandboxGuides,\n actingUser: noSandboxActingUser,\n ...args.prepareContext,\n };\n const artifact = await implementation.prepare(prepareContext);\n const startContext: SandboxStartContextIface = {\n session: {\n id: crypto.randomUUID(),\n organizationId: 'conformance',\n conversationId: null,\n definitionId: 'conformance',\n bindingId: crypto.randomUUID(),\n target: 'conformance',\n },\n storagePath: '/tmp/final-conformance',\n guides: noSandboxGuides,\n variables: noSandboxVariables,\n repositories: noSandboxRepositories,\n actingUser: noSandboxActingUser,\n platformNetworkPolicy: async () => undefined,\n ...args.startContext,\n ...overrides.startContext,\n };\n if (overrides.ownBinding === true) {\n startContext.session = {\n ...startContext.session,\n id: crypto.randomUUID(),\n bindingId: crypto.randomUUID(),\n conversationId: null,\n };\n }\n const { handle, state } = await implementation.start(startContext, args.openOptions, artifact);\n return {\n handle,\n awaitRunning: (timeoutMs) => implementation.awaitRunning(startContext, state, { timeoutMs }),\n };\n};\n\nconst PLATFORM_VARIABLE = 'FINAL_CONFORMANCE_PLATFORM';\nconst SPEC_VARIABLE = 'FINAL_CONFORMANCE_SPEC';\nconst SHARED_VARIABLE = 'FINAL_CONFORMANCE_SHARED';\nconst SPEC_ENV = { [SPEC_VARIABLE]: 'spec', [SHARED_VARIABLE]: 'spec' };\nconst SPEC_ALLOW = ['conformance.example.com'];\nconst PLATFORM_EGRESS_HOSTS = ['egress.conformance.example.com'];\n\n// A variable as a spawned process sees it; null when unset.\nconst variableIn = async (\n sandbox: NetworkSandboxSessionIface,\n name: string,\n): Promise<string | null> => {\n const process = await sandbox.spawn({ command: 'printenv', args: [name] });\n const [stdout, { exitCode }] = await Promise.all([\n streamToString(process.stdout),\n process.wait(),\n ]);\n return exitCode === 0 ? stdout.replace(/\\n$/, '') : null;\n};\n\nconst expectVariables = async (\n sandbox: NetworkSandboxSessionIface,\n expected: Record<string, string | null>,\n) => {\n for (const [name, value] of Object.entries(expected)) {\n const actual = await variableIn(sandbox, name);\n check(\n actual === value,\n `${name} is ${JSON.stringify(actual)}, expected ${JSON.stringify(value)}`,\n );\n }\n};\n\ntype RecordCase = (name: string, run: () => Promise<string | void>) => Promise<void>;\n\n// The start context's platformFiles are written before any process runs;\n// platformEnvironment reaches every process, read again for each one and over\n// the spec's env; platformEgressHosts join an allowlist, and the policy is\n// reported through platformNetworkPolicy before platformFiles are written (a\n// rejected report fails the start); a spec naming a platform variable is refused.\nconst runPlatformCases = async (args: {\n kit: RunSandboxConformanceArgsIface;\n provider: AnySandboxProviderIface;\n platform: SandboxPlatformConformanceIface;\n record: RecordCase;\n skip: (name: string, detail: string) => void;\n}) => {\n const { kit, provider, platform, record } = args;\n let platformValues: Record<string, string> = {\n [PLATFORM_VARIABLE]: 'first',\n [SHARED_VARIABLE]: 'platform',\n };\n const filePath = `/tmp/final-conformance-${crypto.randomUUID().slice(0, 8)}/platform/ca.pem`;\n const order: string[] = [];\n const withPlatform: StartedProviderIface = { handle: null };\n await record('platform environment: provider start', async () => {\n ({ handle: withPlatform.handle } = await startFromProvider(kit, provider, {\n environmentOptions: platform.environmentOptions({ env: SPEC_ENV }),\n startContext: {\n platformFiles: async () => {\n order.push('files');\n return { [filePath]: 'conformance CA\\n' };\n },\n platformEnvironment: async () => {\n order.push('environment');\n return { ...platformValues };\n },\n },\n ownBinding: true,\n }));\n });\n const sandbox = withPlatform.handle?.sandbox;\n if (sandbox != null) {\n try {\n await record('platform files: written before any process', async () => {\n check(\n order.indexOf('files') === 0,\n `platformEnvironment was read before platformFiles: ${order.join(', ')}`,\n );\n const content = await sandbox.readTextFile({ path: filePath });\n check(content === 'conformance CA\\n', `${filePath} holds ${JSON.stringify(content)}`);\n });\n await record('platform environment: reaches spawned processes', async () => {\n await expectVariables(sandbox, { [PLATFORM_VARIABLE]: 'first' });\n const run = await sandbox.run({ command: 'printenv', args: [PLATFORM_VARIABLE] });\n check(run.stdout === 'first\\n', `run saw ${JSON.stringify(run.stdout)}`);\n });\n await record('platform environment: read again for every process', async () => {\n platformValues = { ...platformValues, [PLATFORM_VARIABLE]: 'second' };\n await expectVariables(sandbox, { [PLATFORM_VARIABLE]: 'second' });\n });\n await record('platform environment: overrides the spec env', async () => {\n await expectVariables(sandbox, { [SHARED_VARIABLE]: 'platform', [SPEC_VARIABLE]: 'spec' });\n });\n await record('platform environment: {} leaves the spec env', async () => {\n platformValues = {};\n await expectVariables(sandbox, {\n [PLATFORM_VARIABLE]: null,\n [SHARED_VARIABLE]: 'spec',\n [SPEC_VARIABLE]: 'spec',\n });\n });\n } finally {\n await withPlatform.handle?.onSandboxDelete({ reason: 'conformance' }).catch(() => undefined);\n }\n }\n\n const withoutPlatform: StartedProviderIface = { handle: null };\n const reported: NetworkPolicyIface[] = [];\n const reportOrder: string[] = [];\n const allowlistContext = (\n platformNetworkPolicy: (policy: NetworkPolicyIface) => Promise<void>,\n ): Partial<SandboxStartContextIface> => ({\n platformEnvironment: undefined,\n platformEgressHosts: PLATFORM_EGRESS_HOSTS,\n platformNetworkPolicy,\n platformFiles: async () => {\n reportOrder.push('files');\n return {};\n },\n });\n await record('platform environment: provider start without it', async () => {\n ({ handle: withoutPlatform.handle } = await startFromProvider(kit, provider, {\n environmentOptions: platform.environmentOptions({ env: SPEC_ENV, allow: SPEC_ALLOW }),\n startContext: allowlistContext(async (policy) => {\n reportOrder.push('policy');\n reported.push(policy);\n }),\n ownBinding: true,\n }));\n });\n const plain = withoutPlatform.handle?.sandbox;\n if (plain != null) {\n try {\n await record('platform environment: absent leaves the spec env', () =>\n expectVariables(plain, {\n [PLATFORM_VARIABLE]: null,\n [SHARED_VARIABLE]: 'spec',\n [SPEC_VARIABLE]: 'spec',\n }),\n );\n const observe = platform.observedAllowlist;\n if (observe == null) {\n args.skip('platform egress hosts: appended to an allowlist', 'no observedAllowlist');\n args.skip('platform network policy: reported as applied', 'no observedAllowlist');\n } else {\n await record('platform egress hosts: appended to an allowlist', async () => {\n const allow = (await observe(plain)) ?? [];\n for (const host of [...SPEC_ALLOW, ...PLATFORM_EGRESS_HOSTS])\n check(allow.includes(host), `allowlist ${JSON.stringify(allow)} lacks ${host}`);\n });\n await record('platform network policy: reported as applied', async () => {\n const last = reported.at(-1);\n check(\n last?.mode === NetworkPolicy.Allowlist,\n `reported ${JSON.stringify(reported)}, expected an allowlist`,\n );\n const applied = [...((await observe(plain)) ?? [])].sort();\n const allow = [...(last?.allow ?? [])].sort();\n check(\n JSON.stringify(allow) === JSON.stringify(applied),\n `reported ${JSON.stringify(allow)}, applied ${JSON.stringify(applied)}`,\n );\n check(\n reportOrder.indexOf('policy') < reportOrder.indexOf('files'),\n `platformFiles were written before the policy was reported: ${reportOrder.join(', ')}`,\n );\n });\n }\n } finally {\n await withoutPlatform.handle\n ?.onSandboxDelete({ reason: 'conformance' })\n .catch(() => undefined);\n }\n }\n\n if (platform.observedAllowlist == null) {\n args.skip('platform network policy: a rejected report fails the start', 'no observedAllowlist');\n } else {\n await record('platform network policy: a rejected report fails the start', async () => {\n const started = await startFromProvider(kit, provider, {\n environmentOptions: platform.environmentOptions({ env: SPEC_ENV, allow: SPEC_ALLOW }),\n startContext: allowlistContext(async () => {\n throw new Error('conformance: the policy was not recorded');\n }),\n ownBinding: true,\n }).then(\n ({ handle }) => handle,\n () => null,\n );\n if (started == null) return;\n await started.onSandboxDelete({ reason: 'conformance' }).catch(() => undefined);\n throw new Error('a start whose policy report failed returned a sandbox');\n });\n }\n\n await record('platform environment: reserved names refused', async () => {\n const started = await startFromProvider(kit, provider, {\n environmentOptions: platform.environmentOptions({\n env: { HTTPS_PROXY: 'http://spec.example.com' },\n }),\n ownBinding: true,\n }).then(\n ({ handle }) => handle,\n () => null,\n );\n if (started == null) return;\n await started.onSandboxDelete({ reason: 'conformance' }).catch(() => undefined);\n throw new Error('a spec setting HTTPS_PROXY started');\n });\n};\n\nexport const runSandboxConformance = async (\n args: RunSandboxConformanceArgsIface,\n): Promise<SandboxConformanceReportIface> => {\n const timeoutMs = args.timeoutMs ?? 30_000;\n const cases: ConformanceCaseResultIface[] = [];\n const record: RecordCase = async (name, run) => {\n const started = Date.now();\n try {\n const detail = await withTimeout(run(), timeoutMs, name);\n cases.push({\n name,\n status: ConformanceCaseStatus.Passed,\n durationMs: Date.now() - started,\n error: null,\n detail: detail ?? null,\n });\n } catch (error) {\n cases.push({\n name,\n status: ConformanceCaseStatus.Failed,\n durationMs: Date.now() - started,\n error: error instanceof Error ? error.message : String(error),\n detail: null,\n });\n }\n };\n\n // A holder, so the assignment inside the closure is visible to the narrowing.\n const started: StartedProviderIface = { handle: null };\n let sandbox = args.handle ?? null;\n if (sandbox == null) {\n if (args.provider == null)\n throw new Error('runSandboxConformance needs a handle or a provider');\n const provider = args.provider;\n await record('provider start', async () => {\n ({ handle: started.handle, awaitRunning: started.awaitRunning } = await startFromProvider(\n args,\n provider,\n ));\n });\n const awaitRunning = started.awaitRunning;\n if (awaitRunning != null)\n await record('provider awaitRunning: resolves for a started sandbox', () =>\n awaitRunning(timeoutMs),\n );\n sandbox = started.handle?.sandbox ?? null;\n }\n if (sandbox == null) return { passed: false, cases };\n const target = sandbox;\n\n const root = target.resolvePath(`conformance-${crypto.randomUUID().slice(0, 8)}`);\n const list = sandboxCases(args.largeFileBytes ?? 5 * 1024 * 1024);\n for (const entry of list) await record(entry.name, () => entry.run(target, root));\n\n if (args.viaWire !== false) {\n const network = createInMemoryHandleNetwork();\n network.serve({ url: 'mem://conformance', sandbox: target });\n network.serve({\n url: 'mem://conformance-read',\n sandbox: target,\n access: { mode: SandboxAccess.Read, lifecycle: false },\n });\n const client = await network.connect({ url: 'mem://conformance', token: 'conformance' });\n try {\n const wireRoot = `${root}-wire`;\n for (const entry of list)\n await record(`handle rpc: ${entry.name}`, () => entry.run(client, wireRoot));\n await record('handle rpc: read-only access policy', async () => {\n const readOnly = await network.connect({\n url: 'mem://conformance-read',\n token: 'conformance',\n });\n try {\n await target.writeTextFile({ path: `${root}/ro.txt`, content: 'visible' });\n check(\n (await readOnly.readTextFile({ path: `${root}/ro.txt` })) === 'visible',\n 'read failed on a read binding',\n );\n const attempts: [string, Promise<unknown>][] = [\n [\n 'writeTextFile',\n readOnly.writeTextFile({ path: `${root}/ro.txt`, content: 'changed' }),\n ],\n ['run', readOnly.run({ command: 'echo' })],\n ['spawn', readOnly.spawn({ command: 'echo' })],\n ['removePath', readOnly.removePath({ path: `${root}/ro.txt` })],\n ];\n for (const [what, attempt] of attempts) {\n const error = await attempt.then(\n () => null,\n (cause: unknown) => cause,\n );\n check(\n isHandleRpcError(error) && error.code === HandleRpcErrorCode.Forbidden,\n `${what} was not rejected`,\n );\n }\n check(\n (await target.readTextFile({ path: `${root}/ro.txt` })) === 'visible',\n 'a read binding changed the file',\n );\n } finally {\n readOnly.close();\n }\n });\n } finally {\n client.close();\n await target\n .removePath({ path: `${root}-wire`, recursive: true, force: true })\n .catch(() => undefined);\n }\n }\n\n await target.removePath({ path: root, recursive: true, force: true }).catch(() => undefined);\n await started.handle?.onSandboxDelete({ reason: 'conformance' }).catch(() => undefined);\n\n if (args.platform != null && args.provider != null) {\n await runPlatformCases({\n kit: args,\n provider: args.provider,\n platform: args.platform,\n record,\n skip: (name, detail) =>\n cases.push({\n name,\n status: ConformanceCaseStatus.Skipped,\n durationMs: 0,\n error: null,\n detail,\n }),\n });\n }\n return { passed: cases.every((entry) => entry.status !== ConformanceCaseStatus.Failed), cases };\n};\n"],
5
+ "mappings": "AACA,SAAS,qBAAqB;AAC9B,SAAS,oBAAoB;AAC7B,SAAS,sBAAsB;AAC/B,SAAS,mCAAmC;AAC5C;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OAOK;AACP,SAAS,oBAAoB,wBAAwB;AACrD,SAAS,6BAA8D;AAoDv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MAAM,WAAW,sBAAsB,MAAM,GAAG,MAAM;AAChG;",
6
6
  "names": ["started"]
7
7
  }
@@ -9,7 +9,9 @@ import {
9
9
  PLATFORM_ENVIRONMENT_NAMES,
10
10
  platformProcessEnvironment,
11
11
  PortProtocol,
12
+ reportPlatformNetworkPolicy,
12
13
  SandboxEntryType,
14
+ withPlatformEgressHosts,
13
15
  writePlatformFiles
14
16
  } from "./types.mjs";
15
17
  const fsError = (code, message) => Object.assign(new Error(`${code}: ${message}`), { code });
@@ -372,7 +374,9 @@ const memoryEnvironmentSchema = z.object({
372
374
  cwd: z.string().optional(),
373
375
  ports: z.array(z.number().int()).optional(),
374
376
  // Plain variables for every process, under the platform's.
375
- env: z.record(z.string(), z.string()).optional()
377
+ env: z.record(z.string(), z.string()).optional(),
378
+ // Recorded, not enforced: the memory sandbox has no network.
379
+ networkPolicy: z.object({ mode: z.nativeEnum(NetworkPolicy), allow: z.array(z.string()).optional() }).optional()
376
380
  }).nullable().optional();
377
381
  const fingerprint = (value) => {
378
382
  let hash = 2166136261;
@@ -406,14 +410,22 @@ const memorySandboxProvider = defineSandboxProvider({
406
410
  files: artifact.files,
407
411
  cwd: artifact.cwd,
408
412
  ports: artifact.ports,
413
+ networkPolicy: options.networkPolicy != null,
409
414
  baseEnv: platformProcessEnvironment(ctx, specEnv)
410
415
  });
416
+ if (options.networkPolicy != null) {
417
+ const policy = withPlatformEgressHosts(ctx, options.networkPolicy);
418
+ await sandbox.setNetworkPolicy?.(policy);
419
+ await reportPlatformNetworkPolicy(ctx, policy);
420
+ }
411
421
  await writePlatformFiles(ctx, sandbox);
412
422
  return sandbox;
413
423
  };
414
424
  return {
415
425
  artifactKey: async (ctx) => `memory:${fingerprint(JSON.stringify(artifactFor(ctx.files)))}`,
416
426
  prepare: async (ctx) => artifactFor(ctx.files),
427
+ // An in-memory sandbox runs from the moment it exists.
428
+ awaitRunning: async () => void 0,
417
429
  start: async (ctx, _openOptions, artifact) => ({
418
430
  handle: memoryHandle(await open(ctx, ctx.session.bindingId, artifact)),
419
431
  state: { id: ctx.session.bindingId }
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../../src/sandbox/memory-sandbox.ts"],
4
- "sourcesContent": ["import * as z from 'zod';\nimport type { JsonValue } from \"../json.mjs\";\nimport { encodeSandboxText, readAllBytes, utf8Encode } from \"./bytes.mjs\";\nimport { readTextFileStream, runCollect } from \"./convenience.mjs\";\nimport { runMemoryArgv, runMemoryScript, type MemoryShellFsIface } from \"./memory-shell.mjs\";\nimport { normalizePosixPath, posixDirname, resolvePosixPath } from \"./paths.mjs\";\nimport {\n defineSandboxProvider,\n NetworkPolicy,\n PLATFORM_ENVIRONMENT_NAMES,\n platformProcessEnvironment,\n PortProtocol,\n SandboxEntryType,\n writePlatformFiles,\n type DirEntryIface,\n type NetworkPolicyIface,\n type NetworkSandboxSessionIface,\n type SandboxMcpEndpoint,\n type SandboxProcessIface,\n type SandboxProcessOptionsIface,\n type SandboxProviderHandleIface,\n type SandboxStartContextIface,\n type StatIface,\n} from \"./types.mjs\";\n\n// An in-memory reference sandbox: a virtual filesystem plus a tiny command\n// interpreter (memory-shell.ts). Used by tests and the conformance kit, and as\n// the smallest complete example of the sandbox contract.\n\nexport interface MemorySandboxIface extends NetworkSandboxSessionIface {\n readonly networkPolicy: NetworkPolicyIface;\n readonly stopped: boolean;\n}\n\nexport interface CreateMemorySandboxArgsIface {\n id?: string;\n files?: Record<string, string | Uint8Array>;\n cwd?: string;\n ports?: number[];\n portUrl?: (args: { port: number; protocol: PortProtocol }) => string;\n // Optional capabilities; present only when given.\n computerUse?: () => Promise<SandboxMcpEndpoint>;\n screen?: NetworkSandboxSessionIface['screen'];\n localMcp?: () => Promise<SandboxMcpEndpoint[]>;\n networkPolicy?: boolean;\n // Every process's environment, under per-call env; read again for each process.\n baseEnv?: () => Promise<Record<string, string>>;\n now?: () => Date;\n}\n\ntype MemoryEntry =\n | { type: 'file'; data: Uint8Array; modifiedAt: Date }\n | { type: 'directory'; modifiedAt: Date };\n\ninterface ProcessOutputsIface {\n stdout: ReadableStreamDefaultController<Uint8Array> | null;\n stderr: ReadableStreamDefaultController<Uint8Array> | null;\n}\n\nconst fsError = (code: string, message: string) =>\n Object.assign(new Error(`${code}: ${message}`), { code });\n\nconst abortableSleep = (ms: number, signal: AbortSignal): Promise<void> =>\n new Promise<void>((resolve, reject) => {\n if (signal.aborted) {\n reject(signal.reason);\n return;\n }\n const timer = setTimeout(() => {\n signal.removeEventListener('abort', onAbort);\n resolve();\n }, ms);\n const onAbort = () => {\n clearTimeout(timer);\n reject(signal.reason);\n };\n signal.addEventListener('abort', onAbort, { once: true });\n });\n\nconst signalExitCode = (signal: string | undefined): number => {\n if (signal === 'SIGKILL' || signal === 'KILL' || signal === '9') return 137;\n if (signal === 'SIGINT' || signal === 'INT') return 130;\n return 143;\n};\n\nexport const createMemorySandbox = (\n args: CreateMemorySandboxArgsIface = {},\n): MemorySandboxIface => {\n const id = args.id ?? `memory-${crypto.randomUUID()}`;\n const cwd = normalizePosixPath(args.cwd ?? '/workspace');\n const now = args.now ?? (() => new Date());\n const entries = new Map<string, MemoryEntry>();\n const processes = new Set<SandboxProcessIface>();\n let networkPolicy: NetworkPolicyIface = { mode: NetworkPolicy.AllowAll };\n let stopped = false;\n\n const resolve = (path: string) => resolvePosixPath(cwd, path);\n\n const ensureDirectory = (path: string) => {\n const normalized = normalizePosixPath(path);\n const existing = entries.get(normalized);\n if (existing?.type === 'directory') return;\n if (existing?.type === 'file') throw fsError('ENOTDIR', `${normalized} is a file`);\n if (normalized !== '/') ensureDirectory(posixDirname(normalized));\n entries.set(normalized, { type: 'directory', modifiedAt: now() });\n };\n\n const putFile = (path: string, data: Uint8Array) => {\n const normalized = normalizePosixPath(path);\n if (entries.get(normalized)?.type === 'directory')\n throw fsError('EISDIR', `${normalized} is a directory`);\n ensureDirectory(posixDirname(normalized));\n entries.set(normalized, { type: 'file', data, modifiedAt: now() });\n };\n\n const children = (path: string): string[] => {\n const prefix = path === '/' ? '/' : `${path}/`;\n const names: string[] = [];\n for (const key of entries.keys()) {\n if (key !== path && key.startsWith(prefix) && !key.slice(prefix.length).includes('/')) {\n names.push(key.slice(prefix.length));\n }\n }\n return names.sort();\n };\n\n ensureDirectory('/');\n ensureDirectory(cwd);\n for (const [path, content] of Object.entries(args.files ?? {})) {\n putFile(resolve(path), content instanceof Uint8Array ? content : utf8Encode(content));\n }\n\n const shellFs: MemoryShellFsIface = {\n readFile: (path) => {\n const entry = entries.get(normalizePosixPath(path));\n return entry?.type === 'file' ? entry.data : null;\n },\n writeFile: (path, data, options) => {\n const entry = entries.get(normalizePosixPath(path));\n if (options.append && entry?.type === 'file') {\n const merged = new Uint8Array(entry.data.byteLength + data.byteLength);\n merged.set(entry.data, 0);\n merged.set(data, entry.data.byteLength);\n putFile(path, merged);\n return;\n }\n putFile(path, data);\n },\n kind: (path) => {\n const entry = entries.get(normalizePosixPath(path));\n return entry == null ? null : entry.type;\n },\n list: (path) => {\n const normalized = normalizePosixPath(path);\n return entries.get(normalized)?.type === 'directory' ? children(normalized) : null;\n },\n mkdir: (path, options) => {\n const normalized = normalizePosixPath(path);\n if (!options.parents && entries.get(posixDirname(normalized))?.type !== 'directory') {\n throw fsError('ENOENT', 'No such file or directory');\n }\n if (!options.parents && entries.has(normalized)) throw fsError('EEXIST', 'File exists');\n ensureDirectory(normalized);\n },\n };\n\n const statOf = (path: string): StatIface | null => {\n const entry = entries.get(path);\n if (entry == null) return null;\n return {\n path,\n type: entry.type === 'file' ? SandboxEntryType.File : SandboxEntryType.Directory,\n size: entry.type === 'file' ? entry.data.byteLength : 0,\n modifiedAt: entry.modifiedAt.toISOString(),\n mode: entry.type === 'file' ? 0o644 : 0o755,\n };\n };\n\n const spawn = async (options: SandboxProcessOptionsIface): Promise<SandboxProcessIface> => {\n const env = { ...(await args.baseEnv?.()), ...options.env };\n const controller = new AbortController();\n let killedWith: string | null = null;\n const outputs: ProcessOutputsIface = { stdout: null, stderr: null };\n const stdout = new ReadableStream<Uint8Array>({\n start: (c) => {\n outputs.stdout = c;\n },\n });\n const stderr = new ReadableStream<Uint8Array>({\n start: (c) => {\n outputs.stderr = c;\n },\n });\n let self: SandboxProcessIface | null = null;\n let stdinWriter: WritableStreamDefaultWriter<Uint8Array> | null = null;\n let stdinSource: ReadableStream<Uint8Array>;\n if (options.stdin == null) {\n const pipe = new TransformStream<Uint8Array, Uint8Array>();\n stdinWriter = pipe.writable.getWriter();\n stdinSource = pipe.readable;\n } else if (options.stdin instanceof ReadableStream) {\n stdinSource = options.stdin;\n } else {\n const bytes = utf8Encode(options.stdin);\n stdinSource = new ReadableStream<Uint8Array>({\n start: (c) => {\n if (bytes.byteLength > 0) c.enqueue(bytes);\n c.close();\n },\n });\n }\n const stdinReader = stdinSource.getReader();\n const abortPromise = new Promise<null>((resolveAbort) =>\n controller.signal.addEventListener('abort', () => resolveAbort(null), { once: true }),\n );\n const readStdin = async (): Promise<Uint8Array | null> => {\n const result = await Promise.race([stdinReader.read(), abortPromise]);\n if (result == null) throw controller.signal.reason;\n return result.done ? null : result.value;\n };\n const emit = (\n target: ReadableStreamDefaultController<Uint8Array> | null,\n bytes: Uint8Array,\n ) => {\n if (bytes.byteLength > 0) target?.enqueue(bytes.slice());\n };\n const context = {\n fs: shellFs,\n io: {\n readStdin,\n stdout: (bytes: Uint8Array) => emit(outputs.stdout, bytes),\n stderr: (bytes: Uint8Array) => emit(outputs.stderr, bytes),\n signal: controller.signal,\n },\n cwd: options.cwd == null ? cwd : resolve(options.cwd),\n env,\n sleep: abortableSleep,\n };\n const timeout =\n options.timeoutMs == null\n ? null\n : setTimeout(() => {\n killedWith = 'timeout';\n controller.abort(new Error('timed out'));\n }, options.timeoutMs);\n const onAbortSignal = () => {\n killedWith ??= 'SIGTERM';\n controller.abort(new Error('aborted'));\n };\n options.abortSignal?.addEventListener('abort', onAbortSignal, { once: true });\n const exited = (async (): Promise<{ exitCode: number }> => {\n let exitCode: number;\n try {\n if (context.fs.kind(context.cwd) !== 'directory') {\n context.io.stderr(utf8Encode(`cd: ${context.cwd}: No such file or directory\\n`));\n exitCode = 1;\n } else if (options.shell === true) {\n const script = [options.command, ...(options.args ?? [])].join(' ');\n exitCode = await runMemoryScript({ ...context, script });\n } else {\n exitCode = await runMemoryArgv({\n ...context,\n argv: [options.command, ...(options.args ?? [])],\n });\n }\n } catch (error) {\n if (!controller.signal.aborted) {\n context.io.stderr(\n utf8Encode(`${error instanceof Error ? error.message : String(error)}\\n`),\n );\n exitCode = 1;\n } else {\n exitCode = killedWith === 'timeout' ? 124 : signalExitCode(killedWith ?? undefined);\n }\n }\n if (timeout != null) clearTimeout(timeout);\n options.abortSignal?.removeEventListener('abort', onAbortSignal);\n stdinReader.cancel().catch(() => undefined);\n outputs.stdout?.close();\n outputs.stderr?.close();\n if (self != null) processes.delete(self);\n return { exitCode };\n })();\n const child: SandboxProcessIface = {\n pid: null,\n stdout,\n stderr,\n write: async (data, writeOptions) => {\n if (stdinWriter == null) throw new Error('stdin was provided at spawn');\n const bytes = data instanceof Uint8Array ? data : utf8Encode(data);\n if (bytes.byteLength > 0) await stdinWriter.write(bytes);\n if (writeOptions?.end === true) await stdinWriter.close();\n },\n wait: () => exited,\n kill: async (signal) => {\n killedWith ??= signal ?? 'SIGTERM';\n controller.abort(new Error(`killed (${signal ?? 'SIGTERM'})`));\n await exited;\n },\n };\n self = child;\n processes.add(child);\n return child;\n };\n\n const sandbox: MemorySandboxIface = {\n id,\n defaultWorkingDirectory: cwd,\n ports: args.ports ?? [],\n get description() {\n return `In-memory sandbox ${id}. Working directory ${cwd}. Commands: echo, cat, ls, pwd, cd, true, false, sleep, exit, mkdir, sh -c.`;\n },\n get networkPolicy() {\n return networkPolicy;\n },\n get stopped() {\n return stopped;\n },\n readFile: async (options) => {\n const path = resolve(options.path);\n const entry = entries.get(path);\n if (entry == null) return null;\n if (entry.type === 'directory') throw fsError('EISDIR', `${path} is a directory`);\n const data = entry.data;\n const chunkBytes = 64 * 1024;\n let offset = 0;\n return new ReadableStream<Uint8Array>({\n pull: (controller) => {\n if (offset >= data.byteLength) {\n controller.close();\n return;\n }\n const end = Math.min(data.byteLength, offset + chunkBytes);\n controller.enqueue(data.slice(offset, end));\n offset = end;\n },\n });\n },\n readBinaryFile: async (options) => {\n const stream = await sandbox.readFile(options);\n return stream == null ? null : readAllBytes(stream);\n },\n readTextFile: async (options) => {\n const stream = await sandbox.readFile(options);\n return stream == null ? null : readTextFileStream(stream, options);\n },\n writeFile: async (options) => {\n const data = await readAllBytes(options.content);\n putFile(resolve(options.path), data);\n },\n writeBinaryFile: async (options) => {\n putFile(resolve(options.path), options.content.slice());\n },\n writeTextFile: async (options) => {\n putFile(resolve(options.path), encodeSandboxText(options.content, options.encoding));\n },\n spawn,\n run: (options) => runCollect({ spawn }, options),\n stat: async (options) => statOf(resolve(options.path)),\n readDir: async (options): Promise<DirEntryIface[]> => {\n const path = resolve(options.path);\n const entry = entries.get(path);\n if (entry == null) throw fsError('ENOENT', `${path}: No such file or directory`);\n if (entry.type !== 'directory') throw fsError('ENOTDIR', `${path} is not a directory`);\n return children(path).map((name) => {\n const childPath = path === '/' ? `/${name}` : `${path}/${name}`;\n const child = entries.get(childPath);\n return {\n name,\n path: childPath,\n type: child?.type === 'file' ? SandboxEntryType.File : SandboxEntryType.Directory,\n size: child?.type === 'file' ? child.data.byteLength : null,\n };\n });\n },\n resolvePath: resolve,\n removePath: async (options) => {\n const path = resolve(options.path);\n const entry = entries.get(path);\n if (entry == null) {\n if (options.force === true) return;\n throw fsError('ENOENT', `${path}: No such file or directory`);\n }\n if (path === '/') throw fsError('EPERM', 'refusing to remove /');\n if (entry.type === 'directory') {\n const prefix = `${path}/`;\n const nested = [...entries.keys()].filter((key) => key.startsWith(prefix));\n if (nested.length > 0 && options.recursive !== true)\n throw fsError('ENOTEMPTY', `${path}: Directory not empty`);\n for (const key of nested) entries.delete(key);\n }\n entries.delete(path);\n },\n getPortEndpoint: async (options) => {\n const protocol = options.protocol ?? PortProtocol.Http;\n return {\n url:\n args.portUrl?.({ port: options.port, protocol }) ??\n `${protocol}://127.0.0.1:${options.port}`,\n };\n },\n getPortUrl: async (options) => (await sandbox.getPortEndpoint(options)).url,\n stop: async () => {\n stopped = true;\n await Promise.all([...processes].map((child) => child.kill()));\n },\n destroy: async () => {\n await sandbox.stop();\n entries.clear();\n ensureDirectory('/');\n },\n };\n if (args.networkPolicy === true) {\n sandbox.setNetworkPolicy = async (policy) => {\n networkPolicy = policy;\n };\n }\n if (args.computerUse != null) sandbox.computerUse = args.computerUse;\n if (args.screen != null) sandbox.screen = args.screen;\n if (args.localMcp != null) sandbox.localMcp = args.localMcp;\n return sandbox;\n};\n\n// Every file of a memory sandbox as path \u2192 base64-free UTF-8 text (binary\n// files are skipped); handy for assertions.\nexport const memorySandboxTextFiles = async (\n sandbox: NetworkSandboxSessionIface,\n root = '/',\n): Promise<Record<string, string>> => {\n const out: Record<string, string> = {};\n const walk = async (path: string) => {\n for (const entry of await sandbox.readDir({ path })) {\n if (entry.type === SandboxEntryType.Directory) await walk(entry.path);\n else {\n const text = await sandbox.readTextFile({ path: entry.path });\n if (text != null) out[entry.path] = text;\n }\n }\n };\n await walk(root);\n return out;\n};\n\nconst memoryEnvironmentSchema = z\n .object({\n files: z.record(z.string(), z.string()).optional(),\n cwd: z.string().optional(),\n ports: z.array(z.number().int()).optional(),\n // Plain variables for every process, under the platform's.\n env: z.record(z.string(), z.string()).optional(),\n })\n .nullable()\n .optional();\n\nexport type MemorySandboxArtifact = { files: Record<string, string>; cwd: string; ports: number[] };\nexport type MemorySandboxState = { id: string };\n\nconst fingerprint = (value: string): string => {\n // FNV-1a, enough for a content key in an example provider.\n let hash = 0x811c9dc5;\n for (let i = 0; i < value.length; i += 1) {\n hash ^= value.charCodeAt(i);\n hash = Math.imul(hash, 0x01000193) >>> 0;\n }\n return hash.toString(16).padStart(8, '0');\n};\n\nconst memoryHandle = (\n sandbox: MemorySandboxIface,\n): SandboxProviderHandleIface<MemorySandboxIface> => ({\n sandbox,\n onSandboxStop: () => sandbox.stop(),\n onSandboxDelete: () => sandbox.destroy(),\n onRuntimeShutdown: () => sandbox.stop(),\n});\n\n// Example provider over the memory sandbox. Ephemeral: `resume` starts again\n// from the prepared artifact, so files written before a park are lost.\nexport const memorySandboxProvider = defineSandboxProvider<\n JsonValue,\n JsonValue,\n MemorySandboxArtifact,\n MemorySandboxState,\n MemorySandboxIface\n>({\n name: 'memory',\n environment: (rawOptions) => {\n const options = memoryEnvironmentSchema.parse(rawOptions) ?? {};\n const artifactFor = (files: Record<string, string>): MemorySandboxArtifact => ({\n files: { ...options.files, ...files },\n cwd: options.cwd ?? '/workspace',\n ports: options.ports ?? [],\n });\n const specEnv = options.env ?? {};\n const open = async (\n ctx: SandboxStartContextIface,\n bindingId: string,\n artifact: MemorySandboxArtifact,\n ) => {\n for (const name of Object.keys(specEnv))\n if (PLATFORM_ENVIRONMENT_NAMES.has(name)) throw new Error(`${name} is reserved`);\n const sandbox = createMemorySandbox({\n id: bindingId,\n files: artifact.files,\n cwd: artifact.cwd,\n ports: artifact.ports,\n baseEnv: platformProcessEnvironment(ctx, specEnv),\n });\n await writePlatformFiles(ctx, sandbox);\n return sandbox;\n };\n return {\n artifactKey: async (ctx) => `memory:${fingerprint(JSON.stringify(artifactFor(ctx.files)))}`,\n prepare: async (ctx) => artifactFor(ctx.files),\n start: async (ctx, _openOptions, artifact) => ({\n handle: memoryHandle(await open(ctx, ctx.session.bindingId, artifact)),\n state: { id: ctx.session.bindingId },\n }),\n resume: async (ctx, artifact, state) => memoryHandle(await open(ctx, state.id, artifact)),\n park: async (_ctx, _artifact, state) => state,\n };\n },\n});\n"],
5
- "mappings": "AAAA,YAAY,OAAO;AAEnB,SAAS,mBAAmB,cAAc,kBAAkB;AAC5D,SAAS,oBAAoB,kBAAkB;AAC/C,SAAS,eAAe,uBAAgD;AACxE,SAAS,oBAAoB,cAAc,wBAAwB;AACnE;AAAA,EACE;A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AAAA,MACpB,OAAO,QAAQ,SAAS,CAAC;AAAA,IAC3B;AACA,UAAM,UAAU,QAAQ,OAAO,CAAC;AAChC,UAAM,OAAO,OACX,KACA,WACA,aACG;AACH,iBAAW,QAAQ,OAAO,KAAK,OAAO;AACpC,YAAI,2BAA2B,IAAI,IAAI,EAAG,OAAM,IAAI,MAAM,GAAG,IAAI,cAAc;AACjF,YAAM,UAAU,oBAAoB;AAAA,QAClC,IAAI;AAAA,QACJ,OAAO,SAAS;AAAA,QAChB,KAAK,SAAS;AAAA,QACd,OAAO,SAAS;AAAA,QAChB,SAAS,2BAA2B,KAAK,OAAO;AAAA,MAClD,CAAC;AACD,YAAM,mBAAmB,KAAK,OAAO;AACrC,aAAO;AAAA,IACT;AACA,WAAO;AAAA,MACL,aAAa,OAAO,QAAQ,UAAU,YAAY,KAAK,UAAU,YAAY,IAAI,KAAK,CAAC,CAAC,CAAC;AAAA,MACzF,SAAS,OAAO,QAAQ,YAAY,IAAI,KAAK;AAAA,MAC7C,OAAO,OAAO,KAAK,cAAc,cAAc;AAAA,QAC7C,QAAQ,aAAa,MAAM,KAAK,KAAK,IAAI,QAAQ,WAAW,QAAQ,CAAC;AAAA,QACrE,OAAO,EAAE,IAAI,IAAI,QAAQ,UAAU;AAAA,MACrC;AAAA,MACA,QAAQ,OAAO,KAAK,UAAU,UAAU,aAAa,MAAM,KAAK,KAAK,MAAM,IAAI,QAAQ,CAAC;AAAA,MACxF,MAAM,OAAO,MAAM,WAAW,UAAU;AAAA,IAC1C;AAAA,EACF;AACF,CAAC;",
4
+ "sourcesContent": ["import * as z from 'zod';\nimport type { JsonValue } from \"../json.mjs\";\nimport { encodeSandboxText, readAllBytes, utf8Encode } from \"./bytes.mjs\";\nimport { readTextFileStream, runCollect } from \"./convenience.mjs\";\nimport { runMemoryArgv, runMemoryScript, type MemoryShellFsIface } from \"./memory-shell.mjs\";\nimport { normalizePosixPath, posixDirname, resolvePosixPath } from \"./paths.mjs\";\nimport {\n defineSandboxProvider,\n NetworkPolicy,\n PLATFORM_ENVIRONMENT_NAMES,\n platformProcessEnvironment,\n PortProtocol,\n reportPlatformNetworkPolicy,\n SandboxEntryType,\n withPlatformEgressHosts,\n writePlatformFiles,\n type DirEntryIface,\n type NetworkPolicyIface,\n type NetworkSandboxSessionIface,\n type SandboxMcpEndpoint,\n type SandboxProcessIface,\n type SandboxProcessOptionsIface,\n type SandboxProviderHandleIface,\n type SandboxStartContextIface,\n type StatIface,\n} from \"./types.mjs\";\n\n// An in-memory reference sandbox: a virtual filesystem plus a tiny command\n// interpreter (memory-shell.ts). Used by tests and the conformance kit, and as\n// the smallest complete example of the sandbox contract.\n\nexport interface MemorySandboxIface extends NetworkSandboxSessionIface {\n readonly networkPolicy: NetworkPolicyIface;\n readonly stopped: boolean;\n}\n\nexport interface CreateMemorySandboxArgsIface {\n id?: string;\n files?: Record<string, string | Uint8Array>;\n cwd?: string;\n ports?: number[];\n portUrl?: (args: { port: number; protocol: PortProtocol }) => string;\n // Optional capabilities; present only when given.\n computerUse?: () => Promise<SandboxMcpEndpoint>;\n screen?: NetworkSandboxSessionIface['screen'];\n localMcp?: () => Promise<SandboxMcpEndpoint[]>;\n networkPolicy?: boolean;\n // Every process's environment, under per-call env; read again for each process.\n baseEnv?: () => Promise<Record<string, string>>;\n now?: () => Date;\n}\n\ntype MemoryEntry =\n | { type: 'file'; data: Uint8Array; modifiedAt: Date }\n | { type: 'directory'; modifiedAt: Date };\n\ninterface ProcessOutputsIface {\n stdout: ReadableStreamDefaultController<Uint8Array> | null;\n stderr: ReadableStreamDefaultController<Uint8Array> | null;\n}\n\nconst fsError = (code: string, message: string) =>\n Object.assign(new Error(`${code}: ${message}`), { code });\n\nconst abortableSleep = (ms: number, signal: AbortSignal): Promise<void> =>\n new Promise<void>((resolve, reject) => {\n if (signal.aborted) {\n reject(signal.reason);\n return;\n }\n const timer = setTimeout(() => {\n signal.removeEventListener('abort', onAbort);\n resolve();\n }, ms);\n const onAbort = () => {\n clearTimeout(timer);\n reject(signal.reason);\n };\n signal.addEventListener('abort', onAbort, { once: true });\n });\n\nconst signalExitCode = (signal: string | undefined): number => {\n if (signal === 'SIGKILL' || signal === 'KILL' || signal === '9') return 137;\n if (signal === 'SIGINT' || signal === 'INT') return 130;\n return 143;\n};\n\nexport const createMemorySandbox = (\n args: CreateMemorySandboxArgsIface = {},\n): MemorySandboxIface => {\n const id = args.id ?? `memory-${crypto.randomUUID()}`;\n const cwd = normalizePosixPath(args.cwd ?? '/workspace');\n const now = args.now ?? (() => new Date());\n const entries = new Map<string, MemoryEntry>();\n const processes = new Set<SandboxProcessIface>();\n let networkPolicy: NetworkPolicyIface = { mode: NetworkPolicy.AllowAll };\n let stopped = false;\n\n const resolve = (path: string) => resolvePosixPath(cwd, path);\n\n const ensureDirectory = (path: string) => {\n const normalized = normalizePosixPath(path);\n const existing = entries.get(normalized);\n if (existing?.type === 'directory') return;\n if (existing?.type === 'file') throw fsError('ENOTDIR', `${normalized} is a file`);\n if (normalized !== '/') ensureDirectory(posixDirname(normalized));\n entries.set(normalized, { type: 'directory', modifiedAt: now() });\n };\n\n const putFile = (path: string, data: Uint8Array) => {\n const normalized = normalizePosixPath(path);\n if (entries.get(normalized)?.type === 'directory')\n throw fsError('EISDIR', `${normalized} is a directory`);\n ensureDirectory(posixDirname(normalized));\n entries.set(normalized, { type: 'file', data, modifiedAt: now() });\n };\n\n const children = (path: string): string[] => {\n const prefix = path === '/' ? '/' : `${path}/`;\n const names: string[] = [];\n for (const key of entries.keys()) {\n if (key !== path && key.startsWith(prefix) && !key.slice(prefix.length).includes('/')) {\n names.push(key.slice(prefix.length));\n }\n }\n return names.sort();\n };\n\n ensureDirectory('/');\n ensureDirectory(cwd);\n for (const [path, content] of Object.entries(args.files ?? {})) {\n putFile(resolve(path), content instanceof Uint8Array ? content : utf8Encode(content));\n }\n\n const shellFs: MemoryShellFsIface = {\n readFile: (path) => {\n const entry = entries.get(normalizePosixPath(path));\n return entry?.type === 'file' ? entry.data : null;\n },\n writeFile: (path, data, options) => {\n const entry = entries.get(normalizePosixPath(path));\n if (options.append && entry?.type === 'file') {\n const merged = new Uint8Array(entry.data.byteLength + data.byteLength);\n merged.set(entry.data, 0);\n merged.set(data, entry.data.byteLength);\n putFile(path, merged);\n return;\n }\n putFile(path, data);\n },\n kind: (path) => {\n const entry = entries.get(normalizePosixPath(path));\n return entry == null ? null : entry.type;\n },\n list: (path) => {\n const normalized = normalizePosixPath(path);\n return entries.get(normalized)?.type === 'directory' ? children(normalized) : null;\n },\n mkdir: (path, options) => {\n const normalized = normalizePosixPath(path);\n if (!options.parents && entries.get(posixDirname(normalized))?.type !== 'directory') {\n throw fsError('ENOENT', 'No such file or directory');\n }\n if (!options.parents && entries.has(normalized)) throw fsError('EEXIST', 'File exists');\n ensureDirectory(normalized);\n },\n };\n\n const statOf = (path: string): StatIface | null => {\n const entry = entries.get(path);\n if (entry == null) return null;\n return {\n path,\n type: entry.type === 'file' ? SandboxEntryType.File : SandboxEntryType.Directory,\n size: entry.type === 'file' ? entry.data.byteLength : 0,\n modifiedAt: entry.modifiedAt.toISOString(),\n mode: entry.type === 'file' ? 0o644 : 0o755,\n };\n };\n\n const spawn = async (options: SandboxProcessOptionsIface): Promise<SandboxProcessIface> => {\n const env = { ...(await args.baseEnv?.()), ...options.env };\n const controller = new AbortController();\n let killedWith: string | null = null;\n const outputs: ProcessOutputsIface = { stdout: null, stderr: null };\n const stdout = new ReadableStream<Uint8Array>({\n start: (c) => {\n outputs.stdout = c;\n },\n });\n const stderr = new ReadableStream<Uint8Array>({\n start: (c) => {\n outputs.stderr = c;\n },\n });\n let self: SandboxProcessIface | null = null;\n let stdinWriter: WritableStreamDefaultWriter<Uint8Array> | null = null;\n let stdinSource: ReadableStream<Uint8Array>;\n if (options.stdin == null) {\n const pipe = new TransformStream<Uint8Array, Uint8Array>();\n stdinWriter = pipe.writable.getWriter();\n stdinSource = pipe.readable;\n } else if (options.stdin instanceof ReadableStream) {\n stdinSource = options.stdin;\n } else {\n const bytes = utf8Encode(options.stdin);\n stdinSource = new ReadableStream<Uint8Array>({\n start: (c) => {\n if (bytes.byteLength > 0) c.enqueue(bytes);\n c.close();\n },\n });\n }\n const stdinReader = stdinSource.getReader();\n const abortPromise = new Promise<null>((resolveAbort) =>\n controller.signal.addEventListener('abort', () => resolveAbort(null), { once: true }),\n );\n const readStdin = async (): Promise<Uint8Array | null> => {\n const result = await Promise.race([stdinReader.read(), abortPromise]);\n if (result == null) throw controller.signal.reason;\n return result.done ? null : result.value;\n };\n const emit = (\n target: ReadableStreamDefaultController<Uint8Array> | null,\n bytes: Uint8Array,\n ) => {\n if (bytes.byteLength > 0) target?.enqueue(bytes.slice());\n };\n const context = {\n fs: shellFs,\n io: {\n readStdin,\n stdout: (bytes: Uint8Array) => emit(outputs.stdout, bytes),\n stderr: (bytes: Uint8Array) => emit(outputs.stderr, bytes),\n signal: controller.signal,\n },\n cwd: options.cwd == null ? cwd : resolve(options.cwd),\n env,\n sleep: abortableSleep,\n };\n const timeout =\n options.timeoutMs == null\n ? null\n : setTimeout(() => {\n killedWith = 'timeout';\n controller.abort(new Error('timed out'));\n }, options.timeoutMs);\n const onAbortSignal = () => {\n killedWith ??= 'SIGTERM';\n controller.abort(new Error('aborted'));\n };\n options.abortSignal?.addEventListener('abort', onAbortSignal, { once: true });\n const exited = (async (): Promise<{ exitCode: number }> => {\n let exitCode: number;\n try {\n if (context.fs.kind(context.cwd) !== 'directory') {\n context.io.stderr(utf8Encode(`cd: ${context.cwd}: No such file or directory\\n`));\n exitCode = 1;\n } else if (options.shell === true) {\n const script = [options.command, ...(options.args ?? [])].join(' ');\n exitCode = await runMemoryScript({ ...context, script });\n } else {\n exitCode = await runMemoryArgv({\n ...context,\n argv: [options.command, ...(options.args ?? [])],\n });\n }\n } catch (error) {\n if (!controller.signal.aborted) {\n context.io.stderr(\n utf8Encode(`${error instanceof Error ? error.message : String(error)}\\n`),\n );\n exitCode = 1;\n } else {\n exitCode = killedWith === 'timeout' ? 124 : signalExitCode(killedWith ?? undefined);\n }\n }\n if (timeout != null) clearTimeout(timeout);\n options.abortSignal?.removeEventListener('abort', onAbortSignal);\n stdinReader.cancel().catch(() => undefined);\n outputs.stdout?.close();\n outputs.stderr?.close();\n if (self != null) processes.delete(self);\n return { exitCode };\n })();\n const child: SandboxProcessIface = {\n pid: null,\n stdout,\n stderr,\n write: async (data, writeOptions) => {\n if (stdinWriter == null) throw new Error('stdin was provided at spawn');\n const bytes = data instanceof Uint8Array ? data : utf8Encode(data);\n if (bytes.byteLength > 0) await stdinWriter.write(bytes);\n if (writeOptions?.end === true) await stdinWriter.close();\n },\n wait: () => exited,\n kill: async (signal) => {\n killedWith ??= signal ?? 'SIGTERM';\n controller.abort(new Error(`killed (${signal ?? 'SIGTERM'})`));\n await exited;\n },\n };\n self = child;\n processes.add(child);\n return child;\n };\n\n const sandbox: MemorySandboxIface = {\n id,\n defaultWorkingDirectory: cwd,\n ports: args.ports ?? [],\n get description() {\n return `In-memory sandbox ${id}. Working directory ${cwd}. Commands: echo, cat, ls, pwd, cd, true, false, sleep, exit, mkdir, sh -c.`;\n },\n get networkPolicy() {\n return networkPolicy;\n },\n get stopped() {\n return stopped;\n },\n readFile: async (options) => {\n const path = resolve(options.path);\n const entry = entries.get(path);\n if (entry == null) return null;\n if (entry.type === 'directory') throw fsError('EISDIR', `${path} is a directory`);\n const data = entry.data;\n const chunkBytes = 64 * 1024;\n let offset = 0;\n return new ReadableStream<Uint8Array>({\n pull: (controller) => {\n if (offset >= data.byteLength) {\n controller.close();\n return;\n }\n const end = Math.min(data.byteLength, offset + chunkBytes);\n controller.enqueue(data.slice(offset, end));\n offset = end;\n },\n });\n },\n readBinaryFile: async (options) => {\n const stream = await sandbox.readFile(options);\n return stream == null ? null : readAllBytes(stream);\n },\n readTextFile: async (options) => {\n const stream = await sandbox.readFile(options);\n return stream == null ? null : readTextFileStream(stream, options);\n },\n writeFile: async (options) => {\n const data = await readAllBytes(options.content);\n putFile(resolve(options.path), data);\n },\n writeBinaryFile: async (options) => {\n putFile(resolve(options.path), options.content.slice());\n },\n writeTextFile: async (options) => {\n putFile(resolve(options.path), encodeSandboxText(options.content, options.encoding));\n },\n spawn,\n run: (options) => runCollect({ spawn }, options),\n stat: async (options) => statOf(resolve(options.path)),\n readDir: async (options): Promise<DirEntryIface[]> => {\n const path = resolve(options.path);\n const entry = entries.get(path);\n if (entry == null) throw fsError('ENOENT', `${path}: No such file or directory`);\n if (entry.type !== 'directory') throw fsError('ENOTDIR', `${path} is not a directory`);\n return children(path).map((name) => {\n const childPath = path === '/' ? `/${name}` : `${path}/${name}`;\n const child = entries.get(childPath);\n return {\n name,\n path: childPath,\n type: child?.type === 'file' ? SandboxEntryType.File : SandboxEntryType.Directory,\n size: child?.type === 'file' ? child.data.byteLength : null,\n };\n });\n },\n resolvePath: resolve,\n removePath: async (options) => {\n const path = resolve(options.path);\n const entry = entries.get(path);\n if (entry == null) {\n if (options.force === true) return;\n throw fsError('ENOENT', `${path}: No such file or directory`);\n }\n if (path === '/') throw fsError('EPERM', 'refusing to remove /');\n if (entry.type === 'directory') {\n const prefix = `${path}/`;\n const nested = [...entries.keys()].filter((key) => key.startsWith(prefix));\n if (nested.length > 0 && options.recursive !== true)\n throw fsError('ENOTEMPTY', `${path}: Directory not empty`);\n for (const key of nested) entries.delete(key);\n }\n entries.delete(path);\n },\n getPortEndpoint: async (options) => {\n const protocol = options.protocol ?? PortProtocol.Http;\n return {\n url:\n args.portUrl?.({ port: options.port, protocol }) ??\n `${protocol}://127.0.0.1:${options.port}`,\n };\n },\n getPortUrl: async (options) => (await sandbox.getPortEndpoint(options)).url,\n stop: async () => {\n stopped = true;\n await Promise.all([...processes].map((child) => child.kill()));\n },\n destroy: async () => {\n await sandbox.stop();\n entries.clear();\n ensureDirectory('/');\n },\n };\n if (args.networkPolicy === true) {\n sandbox.setNetworkPolicy = async (policy) => {\n networkPolicy = policy;\n };\n }\n if (args.computerUse != null) sandbox.computerUse = args.computerUse;\n if (args.screen != null) sandbox.screen = args.screen;\n if (args.localMcp != null) sandbox.localMcp = args.localMcp;\n return sandbox;\n};\n\n// Every file of a memory sandbox as path \u2192 base64-free UTF-8 text (binary\n// files are skipped); handy for assertions.\nexport const memorySandboxTextFiles = async (\n sandbox: NetworkSandboxSessionIface,\n root = '/',\n): Promise<Record<string, string>> => {\n const out: Record<string, string> = {};\n const walk = async (path: string) => {\n for (const entry of await sandbox.readDir({ path })) {\n if (entry.type === SandboxEntryType.Directory) await walk(entry.path);\n else {\n const text = await sandbox.readTextFile({ path: entry.path });\n if (text != null) out[entry.path] = text;\n }\n }\n };\n await walk(root);\n return out;\n};\n\nconst memoryEnvironmentSchema = z\n .object({\n files: z.record(z.string(), z.string()).optional(),\n cwd: z.string().optional(),\n ports: z.array(z.number().int()).optional(),\n // Plain variables for every process, under the platform's.\n env: z.record(z.string(), z.string()).optional(),\n // Recorded, not enforced: the memory sandbox has no network.\n networkPolicy: z\n .object({ mode: z.nativeEnum(NetworkPolicy), allow: z.array(z.string()).optional() })\n .optional(),\n })\n .nullable()\n .optional();\n\nexport type MemorySandboxArtifact = { files: Record<string, string>; cwd: string; ports: number[] };\nexport type MemorySandboxState = { id: string };\n\nconst fingerprint = (value: string): string => {\n // FNV-1a, enough for a content key in an example provider.\n let hash = 0x811c9dc5;\n for (let i = 0; i < value.length; i += 1) {\n hash ^= value.charCodeAt(i);\n hash = Math.imul(hash, 0x01000193) >>> 0;\n }\n return hash.toString(16).padStart(8, '0');\n};\n\nconst memoryHandle = (\n sandbox: MemorySandboxIface,\n): SandboxProviderHandleIface<MemorySandboxIface> => ({\n sandbox,\n onSandboxStop: () => sandbox.stop(),\n onSandboxDelete: () => sandbox.destroy(),\n onRuntimeShutdown: () => sandbox.stop(),\n});\n\n// Example provider over the memory sandbox. Ephemeral: `resume` starts again\n// from the prepared artifact, so files written before a park are lost.\nexport const memorySandboxProvider = defineSandboxProvider<\n JsonValue,\n JsonValue,\n MemorySandboxArtifact,\n MemorySandboxState,\n MemorySandboxIface\n>({\n name: 'memory',\n environment: (rawOptions) => {\n const options = memoryEnvironmentSchema.parse(rawOptions) ?? {};\n const artifactFor = (files: Record<string, string>): MemorySandboxArtifact => ({\n files: { ...options.files, ...files },\n cwd: options.cwd ?? '/workspace',\n ports: options.ports ?? [],\n });\n const specEnv = options.env ?? {};\n const open = async (\n ctx: SandboxStartContextIface,\n bindingId: string,\n artifact: MemorySandboxArtifact,\n ) => {\n for (const name of Object.keys(specEnv))\n if (PLATFORM_ENVIRONMENT_NAMES.has(name)) throw new Error(`${name} is reserved`);\n const sandbox = createMemorySandbox({\n id: bindingId,\n files: artifact.files,\n cwd: artifact.cwd,\n ports: artifact.ports,\n networkPolicy: options.networkPolicy != null,\n baseEnv: platformProcessEnvironment(ctx, specEnv),\n });\n if (options.networkPolicy != null) {\n const policy = withPlatformEgressHosts(ctx, options.networkPolicy);\n await sandbox.setNetworkPolicy?.(policy);\n await reportPlatformNetworkPolicy(ctx, policy);\n }\n await writePlatformFiles(ctx, sandbox);\n return sandbox;\n };\n return {\n artifactKey: async (ctx) => `memory:${fingerprint(JSON.stringify(artifactFor(ctx.files)))}`,\n prepare: async (ctx) => artifactFor(ctx.files),\n // An in-memory sandbox runs from the moment it exists.\n awaitRunning: async () => undefined,\n start: async (ctx, _openOptions, artifact) => ({\n handle: memoryHandle(await open(ctx, ctx.session.bindingId, artifact)),\n state: { id: ctx.session.bindingId },\n }),\n resume: async (ctx, artifact, state) => memoryHandle(await open(ctx, state.id, artifact)),\n park: async (_ctx, _artifact, state) => state,\n };\n },\n});\n"],
5
+ "mappings": "AAAA,YAAY,OAAO;AAEnB,SAAS,mBAAmB,cAAc,kBAAkB;AAC5D,SAAS,oBAAoB,kBAAkB;AAC/C,SAAS,eAAe,uBAAgD;AACxE,SAAS,oBAAoB,cAAc,wBAAwB;AACnE;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAA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UAAU;AAAA,IAC1C;AAAA,EACF;AACF,CAAC;",
6
6
  "names": []
7
7
  }
@@ -293,11 +293,13 @@ export interface SandboxStartContextIface {
293
293
  actingUser: SandboxActingUserIface;
294
294
  platformEnvironment?: () => Promise<Record<string, string>>;
295
295
  platformEgressHosts?: string[];
296
+ platformNetworkPolicy: (policy: NetworkPolicyIface) => Promise<void>;
296
297
  platformFiles?: () => Promise<Record<string, string>>;
297
298
  }
298
299
  export declare const PLATFORM_ENVIRONMENT_NAMES: ReadonlySet<string>;
299
300
  export declare const platformProcessEnvironment: (ctx: Pick<SandboxStartContextIface, "platformEnvironment">, specEnv: Record<string, string>) => (() => Promise<Record<string, string>>);
300
301
  export declare const writePlatformFiles: (ctx: Pick<SandboxStartContextIface, "platformFiles">, sandbox: Pick<SandboxSessionIface, "writeTextFile">) => Promise<void>;
302
+ export declare const reportPlatformNetworkPolicy: (ctx: Pick<SandboxStartContextIface, "platformNetworkPolicy">, policy: NetworkPolicyIface) => Promise<void>;
301
303
  export declare const withPlatformEgressHosts: (ctx: Pick<SandboxStartContextIface, "platformEgressHosts">, policy: NetworkPolicyIface) => NetworkPolicyIface;
302
304
  export declare enum SandboxSessionEndReason {
303
305
  Completed = "completed",
@@ -320,6 +322,9 @@ export interface SandboxProviderImplementationIface<OpenOptions, Artifact extend
320
322
  editor?(ctx: SandboxOfferContextIface, state: State, request: SandboxEditorRequestIface): Promise<SandboxEditorResultIface>;
321
323
  artifactKey(ctx: SandboxPrepareContextIface): Promise<string>;
322
324
  prepare(ctx: SandboxPrepareContextIface): Promise<Artifact>;
325
+ awaitRunning(ctx: SandboxStartContextIface, state: State, options: {
326
+ timeoutMs: number;
327
+ }): Promise<void>;
323
328
  start(ctx: SandboxStartContextIface, options: OpenOptions | undefined, artifact: Artifact): Promise<{
324
329
  handle: SandboxProviderHandleIface<S>;
325
330
  state: State;
@@ -61,6 +61,9 @@ const writePlatformFiles = async (ctx, sandbox) => {
61
61
  for (const [path, content] of Object.entries(await ctx.platformFiles?.() ?? {}))
62
62
  await sandbox.writeTextFile({ path, content });
63
63
  };
64
+ const reportPlatformNetworkPolicy = async (ctx, policy) => ctx.platformNetworkPolicy(
65
+ policy.mode === "allowlist" /* Allowlist */ ? { mode: policy.mode, allow: [...policy.allow ?? []] } : { mode: policy.mode }
66
+ );
64
67
  const withPlatformEgressHosts = (ctx, policy) => {
65
68
  const hosts = ctx.platformEgressHosts ?? [];
66
69
  if (policy.mode !== "allowlist" /* Allowlist */ || hosts.length === 0) return policy;
@@ -79,7 +82,17 @@ var SandboxWorkspace = /* @__PURE__ */ ((SandboxWorkspace2) => {
79
82
  return SandboxWorkspace2;
80
83
  })(SandboxWorkspace || {});
81
84
  const defineSandboxProvider = (definition) => ({
82
- definition,
85
+ // An implementation exists only once its options are given, so awaitRunning is
86
+ // checked as each environment is defined, before anything can start from it.
87
+ definition: {
88
+ ...definition,
89
+ environment: (options) => {
90
+ const implementation = definition.environment(options);
91
+ if (typeof implementation.awaitRunning !== "function")
92
+ throw new Error(`sandbox provider ${definition.name} does not implement awaitRunning`);
93
+ return implementation;
94
+ }
95
+ },
83
96
  name: definition.name,
84
97
  environment: (options) => ({
85
98
  providerName: definition.name,
@@ -111,6 +124,7 @@ export {
111
124
  noSandboxRepositories,
112
125
  noSandboxVariables,
113
126
  platformProcessEnvironment,
127
+ reportPlatformNetworkPolicy,
114
128
  withPlatformEgressHosts,
115
129
  writePlatformFiles
116
130
  };
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../../src/sandbox/types.ts"],
4
- "sourcesContent": ["import type { HostedBindingsIface } from \"../hosted-bindings.mjs\";\nimport type {\n ProcessInspectionRequestIface,\n ProcessInspectionResultIface,\n} from '@finalai/agent-protocol/process-inspection';\nimport type { JsonValue } from \"../json.mjs\";\nimport type { ToolDescriptorIface } from \"../manifest.mjs\";\nimport type { SandboxEditorRequestIface, SandboxEditorResultIface } from \"./editor.mjs\";\nimport { awaitableOpenRequest, type AwaitableSandboxOpenRequestIface } from \"./open-scope.mjs\";\nimport type { SandboxSnapshotRequestIface, SandboxSnapshotResponseIface } from \"./snapshots.mjs\";\n\n// Sandbox providers and consumers share the streaming session contract.\n\nexport interface AbortableIface {\n abortSignal?: AbortSignal;\n}\n\nexport interface SandboxProcessOptionsIface extends AbortableIface {\n command: string;\n args?: string[];\n cwd?: string;\n env?: Record<string, string>;\n // Run through the sandbox's login shell (`bash -lc`) instead of exec'ing.\n shell?: boolean;\n stdin?: ReadableStream<Uint8Array> | string;\n timeoutMs?: number;\n}\n\nexport interface SandboxProcessIface {\n readonly pid: string | null;\n readonly stdout: ReadableStream<Uint8Array>;\n readonly stderr: ReadableStream<Uint8Array>;\n // Writes to the process's stdin; closes stdin when `end` is true.\n write(data: Uint8Array | string, options?: { end?: boolean }): Promise<void>;\n wait(): Promise<{ exitCode: number }>;\n kill(signal?: string): Promise<void>;\n}\n\nexport interface SandboxRunResultIface {\n exitCode: number;\n stdout: string;\n stderr: string;\n}\n\nexport enum SandboxEntryType {\n File = 'file',\n Directory = 'directory',\n Symlink = 'symlink',\n Other = 'other',\n}\n\nexport interface StatIface {\n path: string;\n type: SandboxEntryType;\n size: number;\n modifiedAt: string | null;\n mode: number | null;\n}\n\nexport interface DirEntryIface {\n name: string;\n path: string;\n type: SandboxEntryType;\n size: number | null;\n}\n\nexport interface ConfinedSandboxFilesIface {\n readFile(\n options: { path: string; root: string } & AbortableIface,\n ): Promise<ReadableStream<Uint8Array> | null>;\n stat(options: { path: string; root: string } & AbortableIface): Promise<StatIface | null>;\n readDir(\n options: { path: string; root: string } & AbortableIface,\n ): Promise<DirEntryIface[] | null>;\n}\n\nexport interface SandboxSessionIface {\n readonly description: string;\n readonly confinedFileReader?: ConfinedSandboxFilesIface;\n // On the RPC surface, root confines viewer reads to this directory, rejects\n // symlink ancestors and requires Python 3 in the sandbox (confinedFiles feature).\n readFile(\n options: { path: string; root?: string } & AbortableIface,\n ): Promise<ReadableStream<Uint8Array> | null>;\n readBinaryFile(options: { path: string } & AbortableIface): Promise<Uint8Array | null>;\n readTextFile(\n options: {\n path: string;\n encoding?: string;\n startLine?: number;\n endLine?: number;\n } & AbortableIface,\n ): Promise<string | null>;\n writeFile(\n options: { path: string; content: ReadableStream<Uint8Array> } & AbortableIface,\n ): Promise<void>;\n writeBinaryFile(options: { path: string; content: Uint8Array } & AbortableIface): Promise<void>;\n // Writes create missing parent directories.\n writeTextFile(\n options: { path: string; content: string; encoding?: string } & AbortableIface,\n ): Promise<void>;\n spawn(options: SandboxProcessOptionsIface): Promise<SandboxProcessIface>;\n run(options: SandboxProcessOptionsIface): Promise<SandboxRunResultIface>;\n stat(options: { path: string; root?: string } & AbortableIface): Promise<StatIface | null>;\n readDir(options: { path: string; root?: string } & AbortableIface): Promise<DirEntryIface[]>;\n resolvePath(path: string): string;\n removePath(\n options: { path: string; recursive?: boolean; force?: boolean } & AbortableIface,\n ): Promise<void>;\n}\n\nexport enum NetworkPolicy {\n AllowAll = 'allow-all',\n DenyAll = 'deny-all',\n Allowlist = 'allowlist',\n}\n\nexport interface NetworkPolicyIface {\n mode: NetworkPolicy;\n allow?: string[];\n}\n\nexport enum PortProtocol {\n Http = 'http',\n Https = 'https',\n Ws = 'ws',\n}\n\n// An MCP transport the sandbox serves for an optional capability: an HTTP MCP\n// endpoint the harness (or the session service) can dial.\nexport interface McpEndpointIface {\n name: string;\n url: string;\n headers: Record<string, string>;\n}\n\n// A JSON-RPC message channel to an MCP server the sandbox hosts, for backends\n// whose API reaches it some other way than HTTP MCP (a byte pipe, a socket).\n// Messages are JSON-RPC objects, in order.\nexport interface McpChannelIface {\n send(message: JsonValue, options?: AbortableIface): Promise<void>;\n // The messages that arrived since the last call; [] when none did.\n receive(options?: AbortableIface): Promise<JsonValue[]>;\n close(): Promise<void>;\n}\n\n// An MCP server the sandbox hosts, opened in process by whoever runs the handle.\n// It cannot cross the handle RPC wire.\nexport interface McpChannelEndpointIface {\n name: string;\n connect(options?: AbortableIface): Promise<McpChannelIface>;\n}\n\nexport type SandboxMcpEndpoint = McpEndpointIface | McpChannelEndpointIface;\n\n// The tools of a sandbox's hosted MCP servers, as far as they are known without\n// starting it. Null: unknown until the sandbox is attached and asked.\nexport interface SandboxMcpCatalogIface {\n computerUse: ToolDescriptorIface[] | null;\n // Local MCP server name \u2192 its tools.\n localMcp: Record<string, ToolDescriptorIface[]> | null;\n}\n\nexport const isMcpChannelEndpoint = (\n endpoint: SandboxMcpEndpoint,\n): endpoint is McpChannelEndpointIface => 'connect' in endpoint;\n\nexport interface ScreenOptionsIface {\n // View-only by default; explicit input control requires execute access.\n viewOnly?: boolean;\n}\n\nexport interface ScreenSessionIface {\n // A short-lived viewer grant; providers enforce the requested input access.\n url: string;\n token: string;\n expiresAt: string;\n}\n\nexport interface NetworkSandboxSessionIface extends SandboxSessionIface {\n readonly id: string;\n readonly defaultWorkingDirectory: string;\n readonly ports: readonly number[];\n getPortEndpoint(options: {\n port: number;\n protocol?: PortProtocol;\n }): Promise<{ url: string; headers?: Record<string, string> }>;\n getPortUrl(options: { port: number; protocol?: PortProtocol }): Promise<string>;\n stop(): Promise<void>;\n destroy(): Promise<void>;\n setNetworkPolicy?(policy: NetworkPolicyIface): Promise<void>;\n computerUse?(): Promise<SandboxMcpEndpoint>;\n screen?(options?: ScreenOptionsIface): Promise<ScreenSessionIface>;\n localMcp?(): Promise<SandboxMcpEndpoint[]>;\n}\n\n// Capabilities a started sandbox advertises (and the handle RPC exposes).\nexport enum SandboxCapability {\n Files = 'files',\n Process = 'process',\n Ports = 'ports',\n NetworkPolicy = 'networkPolicy',\n ComputerUse = 'computerUse',\n Screen = 'screen',\n LocalMcp = 'localMcp',\n Browser = 'browser',\n}\n\nexport interface SandboxProviderHandleIface<S extends SandboxSessionIface> {\n readonly sandbox: S;\n onSandboxStop(): Promise<void>;\n onSandboxDelete(options?: { reason?: string }): Promise<void>;\n onRuntimeShutdown(): Promise<void>;\n}\n\n// A saved computer setup guide version: Build's versioned build-\n// and start-time inputs for a sandbox, as the session service serves them.\nexport interface SandboxGuideVersionIface {\n guideId: string;\n versionId: string;\n slug: string;\n title: string;\n number: number;\n image: string;\n // `.final/sandbox-template.yaml` v2 as JSON.\n templateConfig: JsonValue;\n // The start-time parameters this version defaults to.\n defaultParameters: JsonValue;\n instructionsMarkdown: string | null;\n // A ready build from the guide's provider, reusable independently of workspace seeds.\n preparedArtifact?: { providerRef: string; key: string; artifact: JsonValue };\n}\n\n// The organization's computer setup guides, read through the session service.\n// Every provider gets the same reader; a provider whose\n// environments name no guide never calls it.\nexport interface SandboxGuidesIface {\n get(args: { ref: string; version: number | 'latest' }): Promise<SandboxGuideVersionIface | null>;\n // The organization's default guide; null when it has none.\n default(): Promise<SandboxGuideVersionIface | null>;\n}\n\n// Where to clone a repository from, with a short-lived read credential that\n// must reach only the clone process (never a repository's git config).\nexport interface SandboxRepositoryCloneSourceIface {\n url: string;\n // Checked out after the clone; null keeps the default branch.\n ref: string | null;\n // An HTTP Authorization header value for the clone, or null.\n authorization: string | null;\n}\n\n// Repository credentials for the repositories an environment names (a Code\n// Storage id, a GitHub owner/name), resolved by the session service for the\n// session's organization only. Null: not a repository it can resolve.\nexport interface SandboxRepositoriesIface {\n cloneSource(args: {\n repository: string;\n ref: string | null;\n }): Promise<SandboxRepositoryCloneSourceIface | null>;\n}\n\n// Reads a named organization variable (managed in Build) for the session's\n// organization. Values are injected into the sandbox only, never stored in a\n// manifest, a state or the log.\nexport interface SandboxVariablesIface {\n get(name: string): Promise<string | null>;\n}\n\nexport const noSandboxGuides: SandboxGuidesIface = {\n get: async () => null,\n default: async () => null,\n};\n\nexport const noSandboxRepositories: SandboxRepositoriesIface = {\n cloneSource: async () => null,\n};\n\nexport const noSandboxVariables: SandboxVariablesIface = { get: async () => null };\n\n// The user a session acts for: the author of its running turn, else its owner,\n// else the user whose Home its conversation is. A call a person makes through\n// the platform's sandbox viewer acts for that person instead. Null when it acts\n// for no user (a turn nobody prompted in a shared conversation) and outside any\n// session (a guide build). Read on each call, because it changes between turns\n// and between callers.\nexport interface SandboxActingUserIface {\n current(): Promise<string | null>;\n}\n\nexport const noSandboxActingUser: SandboxActingUserIface = { current: async () => null };\n\n// What an environment's pre-start reads (capabilities, mcpCatalog) are given.\nexport interface SandboxOfferContextIface {\n bindings?: HostedBindingsIface;\n organizationId: string;\n actingUser: SandboxActingUserIface;\n}\n\n// What an environment's hooks are given before anything starts.\nexport interface SandboxEnvironmentContextIface {\n bindings?: HostedBindingsIface;\n organizationId: string;\n guides: SandboxGuidesIface;\n}\n\n// Scoped by the host to this organization and provider. Providers can retain\n// reusable intermediate artifacts independently of a revision's seed files.\nexport interface SandboxArtifactsIface {\n get(key: string): Promise<JsonValue | null>;\n put(key: string, artifact: JsonValue): Promise<void>;\n}\n\nexport interface SandboxPreparationSourceIface {\n sourceRevision: string;\n read(): Promise<{ files: Record<string, string>; resources: Record<string, JsonValue> }>;\n}\n\nexport interface SandboxPrepareContextIface {\n bindings?: HostedBindingsIface;\n // A host-persisted resource source; artifacts may retain its identity instead of seed contents.\n preparation?: SandboxPreparationSourceIface;\n artifacts?: SandboxArtifactsIface;\n // Agent revisions supply workspace-relative seeds; setup-guide builds supply\n // guide.json and optional instructions.md. Resources name workspace, skills or guide.\n // Model instructions remain harness config.\n files: Record<string, string>;\n resources: Record<string, JsonValue>;\n sourceRevision: string;\n storagePath: string;\n organizationId: string;\n // The guide inputs (build-time) an environment names, resolved by the platform.\n guides: SandboxGuidesIface;\n // Who the session the artifact is prepared for acts for, for environments that\n // name a backend resource relative to that user; the key must then name it.\n actingUser: SandboxActingUserIface;\n log?: (message: string) => void;\n}\n\nexport interface SandboxStartContextIface {\n bindings?: HostedBindingsIface;\n /** Passive recovery only: never wake, create, seed, or restart backend services. */\n passive?: boolean;\n preparation?: SandboxPreparationSourceIface;\n session: {\n id: string;\n organizationId: string;\n conversationId: string | null;\n definitionId: string;\n bindingId: string;\n target: string;\n };\n storagePath: string;\n // Start-time inputs: guides, the variables to inject, repository credentials.\n guides: SandboxGuidesIface;\n variables: SandboxVariablesIface;\n repositories: SandboxRepositoriesIface;\n actingUser: SandboxActingUserIface;\n // Variables the platform sets in every process of this sandbox: the egress\n // proxy, trust for its CA, and one placeholder per bound secret. Evaluated\n // again for every spawn/run, never once per session: a secret bound\n // mid-session must reach the next command. May resolve to {} (no proxy\n // configured, or not ready yet). Platform values override the spec's env.\n platformEnvironment?: () => Promise<Record<string, string>>;\n // Hosts the sandbox must be able to reach for the proxy to work, to append\n // to any allowlist-mode network policy the spec declares.\n platformEgressHosts?: string[];\n // Files the platform needs in the sandbox before any clone, setup step or\n // service runs: written right after the sandbox exists, on start and resume.\n // Paths are absolute; missing parent directories are created.\n platformFiles?: () => Promise<Record<string, string>>;\n}\n\n// The variables `platformEnvironment` owns. A spec that sets one (as a plain\n// value or an organization variable) is refused at start.\nexport const PLATFORM_ENVIRONMENT_NAMES: ReadonlySet<string> = new Set([\n 'HTTPS_PROXY',\n 'HTTP_PROXY',\n 'NO_PROXY',\n 'NODE_USE_ENV_PROXY',\n 'SSL_CERT_FILE',\n 'CURL_CA_BUNDLE',\n 'REQUESTS_CA_BUNDLE',\n 'GIT_SSL_CAINFO',\n 'CARGO_HTTP_CAINFO',\n 'DENO_CERT',\n 'NODE_EXTRA_CA_CERTS',\n 'FINAL_EGRESS_URL',\n 'FINAL_EGRESS_TOKEN',\n 'GH_TOKEN',\n 'GITHUB_TOKEN',\n]);\n\n// A process's base environment: the spec's variables under the platform's,\n// read again on every call.\nexport const platformProcessEnvironment =\n (\n ctx: Pick<SandboxStartContextIface, 'platformEnvironment'>,\n specEnv: Record<string, string>,\n ): (() => Promise<Record<string, string>>) =>\n async () => ({ ...specEnv, ...(await ctx.platformEnvironment?.()) });\n\n// Writes `platformFiles` into a sandbox that now exists, before it runs anything.\n// Relies on writeTextFile creating missing parent directories.\nexport const writePlatformFiles = async (\n ctx: Pick<SandboxStartContextIface, 'platformFiles'>,\n sandbox: Pick<SandboxSessionIface, 'writeTextFile'>,\n): Promise<void> => {\n for (const [path, content] of Object.entries((await ctx.platformFiles?.()) ?? {}))\n await sandbox.writeTextFile({ path, content });\n};\n\n// An allowlist policy with the platform's egress hosts appended; any other\n// policy unchanged.\nexport const withPlatformEgressHosts = (\n ctx: Pick<SandboxStartContextIface, 'platformEgressHosts'>,\n policy: NetworkPolicyIface,\n): NetworkPolicyIface => {\n const hosts = ctx.platformEgressHosts ?? [];\n if (policy.mode !== NetworkPolicy.Allowlist || hosts.length === 0) return policy;\n return { ...policy, allow: [...new Set([...(policy.allow ?? []), ...hosts])] };\n};\n\nexport enum SandboxSessionEndReason {\n Completed = 'completed',\n Expired = 'expired',\n Failed = 'failed',\n}\n\n// How long an environment's sandbox outlives a session: `session`\n// keeps it for the session's life; `conversation` gives every session in the\n// conversation one shared sandbox per target, surviving session resets;\n// `ephemeral` discards it when released.\nexport enum SandboxWorkspace {\n Session = 'session',\n Conversation = 'conversation',\n Ephemeral = 'ephemeral',\n}\n\nexport interface SandboxProviderImplementationIface<\n OpenOptions,\n Artifact extends JsonValue,\n State extends JsonValue,\n S extends NetworkSandboxSessionIface,\n> {\n // The workspace this environment declares, read before anything starts so the\n // session service knows which sessions share a binding. Absent or null: session.\n workspace?(ctx: SandboxEnvironmentContextIface): Promise<SandboxWorkspace | null>;\n // The capabilities this environment's sandboxes offer, read before anything\n // starts through the backend's own API. Absent or null: unknown\n // until started; local MCP is then not projected.\n capabilities?(ctx: SandboxOfferContextIface): Promise<SandboxCapability[] | null>;\n // The hosted MCP servers' tool catalogs the backend can give without starting\n // a sandbox (from its own records), so the MCP projection lists them from the\n // first `tools/list`. The projection checks a server's catalog against the\n // live server when a call first opens that server (servers a session never\n // uses stay closed) and announces a change with\n // `notifications/tools/list_changed`.\n //\n // Trade-off: a catalog left unknown (absent hook, null, or a null field) can\n // only be learned from the live sandbox, so the first `tools/list` that finds\n // it unknown starts the sandbox in the background, at session start rather\n // than on the first tool call. Otherwise those tools would never be listed,\n // and nothing would ever call them. Providers that can give the catalog keep\n // attach lazy.\n mcpCatalog?(ctx: SandboxOfferContextIface): Promise<SandboxMcpCatalogIface | null>;\n // Reads committed files without starting/resuming a sandbox. Null means the backend\n // is live or offers no snapshot. An unavailable sleeping snapshot must throw,\n // never fall through to a read that wakes it. Pin subsequent ranges by snapshotId.\n readSnapshot?(\n ctx: SandboxOfferContextIface,\n state: State,\n request: SandboxSnapshotRequestIface,\n ): Promise<SandboxSnapshotResponseIface | null>;\n // Inspect retained backend processes without opening, resuming or extending a sandbox.\n // Stop requires execute access; the provider also enforces backend ownership.\n processes?(\n ctx: SandboxOfferContextIface & { bindingId: string },\n state: State,\n request: ProcessInspectionRequestIface,\n ): Promise<ProcessInspectionResultIface>;\n // Browser editor for this provider's existing workspace. The host checks write\n // authorization; this hook never creates or wakes a backend. Credentials stay\n // in the authentication form, never the editor URL or stored provider state.\n editor?(\n ctx: SandboxOfferContextIface,\n state: State,\n request: SandboxEditorRequestIface,\n ): Promise<SandboxEditorResultIface>;\n // Content-addressed by `artifactKey`; the session service caches artifacts in\n // agent.sandbox_artifacts and calls prepare only on a miss.\n artifactKey(ctx: SandboxPrepareContextIface): Promise<string>;\n prepare(ctx: SandboxPrepareContextIface): Promise<Artifact>;\n // `region`: where the backend placed the sandbox (its own region name), so the\n // session service can place the harness near it; null when unknown.\n start(\n ctx: SandboxStartContextIface,\n options: OpenOptions | undefined,\n artifact: Artifact,\n ): Promise<{ handle: SandboxProviderHandleIface<S>; state: State; region?: string | null }>;\n resume(\n ctx: SandboxStartContextIface,\n artifact: Artifact,\n state: State,\n ): Promise<SandboxProviderHandleIface<S>>;\n // Reconnect to an already running backend after host restart for a read-only viewer.\n // Absent: viewers can use a retained live handle but cannot trigger resume.\n resumePassive?(\n ctx: SandboxStartContextIface,\n artifact: Artifact,\n state: State,\n ): Promise<SandboxProviderHandleIface<S>>;\n // Park: pause or stop the sandbox, returning the state resume needs.\n park?(ctx: SandboxStartContextIface, artifact: Artifact, state: State): Promise<State>;\n onSessionEnd?(\n ctx: SandboxStartContextIface,\n artifact: Artifact,\n state: State,\n options: { reason: SandboxSessionEndReason },\n ): Promise<void>;\n}\n\nexport interface SandboxProviderDefinitionIface<\n EnvOptions,\n OpenOptions,\n Artifact extends JsonValue,\n State extends JsonValue,\n S extends NetworkSandboxSessionIface,\n> {\n name: string;\n // The version of `State`'s shape. The session service records it with each\n // binding and refuses to resume a state written under another version (the\n // next call starts the sandbox again instead).\n stateProtocolVersion?: number;\n environment(\n options?: EnvOptions,\n ): SandboxProviderImplementationIface<OpenOptions, Artifact, State, S>;\n}\n\n// A defined provider: the definition plus authoring sugar. `environment(opts)`\n// returns an environment whose `.open(openOptions)` records a sandbox binding\n// target when authored, and is what the session service drives at run time.\nexport interface SandboxProviderIface<\n EnvOptions,\n OpenOptions,\n Artifact extends JsonValue,\n State extends JsonValue,\n S extends NetworkSandboxSessionIface,\n> {\n readonly definition: SandboxProviderDefinitionIface<EnvOptions, OpenOptions, Artifact, State, S>;\n readonly name: string;\n environment(options?: EnvOptions): AwaitableSandboxEnvironmentIface<EnvOptions, OpenOptions>;\n}\n\nexport interface SandboxEnvironmentIface<EnvOptions, OpenOptions> {\n readonly providerName: string;\n readonly options: EnvOptions | undefined;\n // Provider-authored notices shown by the compiler and Build before publication.\n readonly authoringWarnings?: readonly string[];\n // Authoring: records the open options (access, ...) for this target.\n open(options?: OpenOptions): SandboxOpenRequestIface<EnvOptions, OpenOptions>;\n}\n\n// An environment whose open request a sandbox.ts selector can await to get\n// the live session (open-scope.ts); what defineSandboxProvider and the\n// installed helpers return.\nexport interface AwaitableSandboxEnvironmentIface<\n EnvOptions,\n OpenOptions,\n> extends SandboxEnvironmentIface<EnvOptions, OpenOptions> {\n open(options?: OpenOptions): AwaitableSandboxOpenRequestIface<EnvOptions, OpenOptions>;\n}\n\nexport interface SandboxOpenRequestIface<EnvOptions, OpenOptions> {\n readonly providerName: string;\n readonly environmentOptions: EnvOptions | undefined;\n readonly openOptions: OpenOptions | undefined;\n readonly authoringWarnings?: readonly string[];\n}\n\nexport const defineSandboxProvider = <\n EnvOptions,\n OpenOptions,\n Artifact extends JsonValue,\n State extends JsonValue,\n S extends NetworkSandboxSessionIface,\n>(\n definition: SandboxProviderDefinitionIface<EnvOptions, OpenOptions, Artifact, State, S>,\n): SandboxProviderIface<EnvOptions, OpenOptions, Artifact, State, S> => ({\n definition,\n name: definition.name,\n environment: (options) => ({\n providerName: definition.name,\n options,\n open: (openOptions) =>\n awaitableOpenRequest({\n providerName: definition.name,\n environmentOptions: options,\n openOptions,\n }),\n }),\n});\n\n// Erased form the session service stores in its provider registry.\nexport type AnySandboxProviderIface = SandboxProviderIface<\n JsonValue,\n JsonValue,\n JsonValue,\n JsonValue,\n NetworkSandboxSessionIface\n>;\n\n// Events emitted through a sandbox provider's process lifecycle.\nexport enum SandboxEventKind {\n ProcessExited = 'process_exited',\n}\n"],
5
- "mappings": "AAQA,SAAS,4BAAmE;AAoCrE,IAAK,mBAAL,kBAAKA,sBAAL;AACL,EAAAA,kBAAA,UAAO;AACP,EAAAA,kBAAA,eAAY;AACZ,EAAAA,kBAAA,aAAU;AACV,EAAAA,kBAAA,WAAQ;AAJE,SAAAA;AAAA,GAAA;AAmEL,IAAK,gBAAL,kBAAKC,mBAAL;AACL,EAAAA,eAAA,cAAW;AACX,EAAAA,eAAA,aAAU;AACV,EAAAA,eAAA,eAAY;AAHF,SAAAA;AAAA,GAAA;AAWL,IAAK,eAAL,kBAAKC,kBAAL;AACL,EAAAA,cAAA,UAAO;AACP,EAAAA,cAAA,WAAQ;AACR,EAAAA,cAAA,QAAK;AAHK,SAAAA;AAAA,GAAA;AAyCL,MAAM,uBAAuB,CAClC,aACwC,aAAa;AAgChD,IAAK,oBAAL,kBAAKC,uBAAL;AACL,EAAAA,mBAAA,WAAQ;AACR,EAAAA,mBAAA,aAAU;AACV,EAAAA,mBAAA,WAAQ;AACR,EAAAA,mBAAA,mBAAgB;AAChB,EAAAA,mBAAA,iBAAc;AACd,EAAAA,mB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AACL,EAAAA,kBAAA,aAAU;AACV,EAAAA,kBAAA,kBAAe;AACf,EAAAA,kBAAA,eAAY;AAHF,SAAAA;AAAA,GAAA;AAmJL,MAAM,wBAAwB,CAOnC,gBACuE;AAAA,EACvE;AAAA,EACA,MAAM,WAAW;AAAA,EACjB,aAAa,CAAC,aAAa;AAAA,IACzB,cAAc,WAAW;AAAA,IACzB;AAAA,IACA,MAAM,CAAC,gBACL,qBAAqB;AAAA,MACnB,cAAc,WAAW;AAAA,MACzB,oBAAoB;AAAA,MACpB;AAAA,IACF,CAAC;AAAA,EACL;AACF;AAYO,IAAK,mBAAL,kBAAKC,sBAAL;AACL,EAAAA,kBAAA,mBAAgB;AADN,SAAAA;AAAA,GAAA;",
4
+ "sourcesContent": ["import type { HostedBindingsIface } from \"../hosted-bindings.mjs\";\nimport type {\n ProcessInspectionRequestIface,\n ProcessInspectionResultIface,\n} from '@finalai/agent-protocol/process-inspection';\nimport type { JsonValue } from \"../json.mjs\";\nimport type { ToolDescriptorIface } from \"../manifest.mjs\";\nimport type { SandboxEditorRequestIface, SandboxEditorResultIface } from \"./editor.mjs\";\nimport { awaitableOpenRequest, type AwaitableSandboxOpenRequestIface } from \"./open-scope.mjs\";\nimport type { SandboxSnapshotRequestIface, SandboxSnapshotResponseIface } from \"./snapshots.mjs\";\n\n// Sandbox providers and consumers share the streaming session contract.\n\nexport interface AbortableIface {\n abortSignal?: AbortSignal;\n}\n\nexport interface SandboxProcessOptionsIface extends AbortableIface {\n command: string;\n args?: string[];\n cwd?: string;\n env?: Record<string, string>;\n // Run through the sandbox's login shell (`bash -lc`) instead of exec'ing.\n shell?: boolean;\n stdin?: ReadableStream<Uint8Array> | string;\n timeoutMs?: number;\n}\n\nexport interface SandboxProcessIface {\n readonly pid: string | null;\n readonly stdout: ReadableStream<Uint8Array>;\n readonly stderr: ReadableStream<Uint8Array>;\n // Writes to the process's stdin; closes stdin when `end` is true.\n write(data: Uint8Array | string, options?: { end?: boolean }): Promise<void>;\n wait(): Promise<{ exitCode: number }>;\n kill(signal?: string): Promise<void>;\n}\n\nexport interface SandboxRunResultIface {\n exitCode: number;\n stdout: string;\n stderr: string;\n}\n\nexport enum SandboxEntryType {\n File = 'file',\n Directory = 'directory',\n Symlink = 'symlink',\n Other = 'other',\n}\n\nexport interface StatIface {\n path: string;\n type: SandboxEntryType;\n size: number;\n modifiedAt: string | null;\n mode: number | null;\n}\n\nexport interface DirEntryIface {\n name: string;\n path: string;\n type: SandboxEntryType;\n size: number | null;\n}\n\nexport interface ConfinedSandboxFilesIface {\n readFile(\n options: { path: string; root: string } & AbortableIface,\n ): Promise<ReadableStream<Uint8Array> | null>;\n stat(options: { path: string; root: string } & AbortableIface): Promise<StatIface | null>;\n readDir(\n options: { path: string; root: string } & AbortableIface,\n ): Promise<DirEntryIface[] | null>;\n}\n\nexport interface SandboxSessionIface {\n readonly description: string;\n readonly confinedFileReader?: ConfinedSandboxFilesIface;\n // On the RPC surface, root confines viewer reads to this directory, rejects\n // symlink ancestors and requires Python 3 in the sandbox (confinedFiles feature).\n readFile(\n options: { path: string; root?: string } & AbortableIface,\n ): Promise<ReadableStream<Uint8Array> | null>;\n readBinaryFile(options: { path: string } & AbortableIface): Promise<Uint8Array | null>;\n readTextFile(\n options: {\n path: string;\n encoding?: string;\n startLine?: number;\n endLine?: number;\n } & AbortableIface,\n ): Promise<string | null>;\n writeFile(\n options: { path: string; content: ReadableStream<Uint8Array> } & AbortableIface,\n ): Promise<void>;\n writeBinaryFile(options: { path: string; content: Uint8Array } & AbortableIface): Promise<void>;\n // Writes create missing parent directories.\n writeTextFile(\n options: { path: string; content: string; encoding?: string } & AbortableIface,\n ): Promise<void>;\n spawn(options: SandboxProcessOptionsIface): Promise<SandboxProcessIface>;\n run(options: SandboxProcessOptionsIface): Promise<SandboxRunResultIface>;\n stat(options: { path: string; root?: string } & AbortableIface): Promise<StatIface | null>;\n readDir(options: { path: string; root?: string } & AbortableIface): Promise<DirEntryIface[]>;\n resolvePath(path: string): string;\n removePath(\n options: { path: string; recursive?: boolean; force?: boolean } & AbortableIface,\n ): Promise<void>;\n}\n\nexport enum NetworkPolicy {\n AllowAll = 'allow-all',\n DenyAll = 'deny-all',\n Allowlist = 'allowlist',\n}\n\nexport interface NetworkPolicyIface {\n mode: NetworkPolicy;\n allow?: string[];\n}\n\nexport enum PortProtocol {\n Http = 'http',\n Https = 'https',\n Ws = 'ws',\n}\n\n// An MCP transport the sandbox serves for an optional capability: an HTTP MCP\n// endpoint the harness (or the session service) can dial.\nexport interface McpEndpointIface {\n name: string;\n url: string;\n headers: Record<string, string>;\n}\n\n// A JSON-RPC message channel to an MCP server the sandbox hosts, for backends\n// whose API reaches it some other way than HTTP MCP (a byte pipe, a socket).\n// Messages are JSON-RPC objects, in order.\nexport interface McpChannelIface {\n send(message: JsonValue, options?: AbortableIface): Promise<void>;\n // The messages that arrived since the last call; [] when none did.\n receive(options?: AbortableIface): Promise<JsonValue[]>;\n close(): Promise<void>;\n}\n\n// An MCP server the sandbox hosts, opened in process by whoever runs the handle.\n// It cannot cross the handle RPC wire.\nexport interface McpChannelEndpointIface {\n name: string;\n connect(options?: AbortableIface): Promise<McpChannelIface>;\n}\n\nexport type SandboxMcpEndpoint = McpEndpointIface | McpChannelEndpointIface;\n\n// The tools of a sandbox's hosted MCP servers, as far as they are known without\n// starting it. Null: unknown until the sandbox is attached and asked.\nexport interface SandboxMcpCatalogIface {\n computerUse: ToolDescriptorIface[] | null;\n // Local MCP server name \u2192 its tools.\n localMcp: Record<string, ToolDescriptorIface[]> | null;\n}\n\nexport const isMcpChannelEndpoint = (\n endpoint: SandboxMcpEndpoint,\n): endpoint is McpChannelEndpointIface => 'connect' in endpoint;\n\nexport interface ScreenOptionsIface {\n // View-only by default; explicit input control requires execute access.\n viewOnly?: boolean;\n}\n\nexport interface ScreenSessionIface {\n // A short-lived viewer grant; providers enforce the requested input access.\n url: string;\n token: string;\n expiresAt: string;\n}\n\nexport interface NetworkSandboxSessionIface extends SandboxSessionIface {\n readonly id: string;\n readonly defaultWorkingDirectory: string;\n readonly ports: readonly number[];\n getPortEndpoint(options: {\n port: number;\n protocol?: PortProtocol;\n }): Promise<{ url: string; headers?: Record<string, string> }>;\n getPortUrl(options: { port: number; protocol?: PortProtocol }): Promise<string>;\n stop(): Promise<void>;\n destroy(): Promise<void>;\n setNetworkPolicy?(policy: NetworkPolicyIface): Promise<void>;\n computerUse?(): Promise<SandboxMcpEndpoint>;\n screen?(options?: ScreenOptionsIface): Promise<ScreenSessionIface>;\n localMcp?(): Promise<SandboxMcpEndpoint[]>;\n}\n\n// Capabilities a started sandbox advertises (and the handle RPC exposes).\nexport enum SandboxCapability {\n Files = 'files',\n Process = 'process',\n Ports = 'ports',\n NetworkPolicy = 'networkPolicy',\n ComputerUse = 'computerUse',\n Screen = 'screen',\n LocalMcp = 'localMcp',\n Browser = 'browser',\n}\n\nexport interface SandboxProviderHandleIface<S extends SandboxSessionIface> {\n readonly sandbox: S;\n onSandboxStop(): Promise<void>;\n onSandboxDelete(options?: { reason?: string }): Promise<void>;\n onRuntimeShutdown(): Promise<void>;\n}\n\n// A saved computer setup guide version: Build's versioned build-\n// and start-time inputs for a sandbox, as the session service serves them.\nexport interface SandboxGuideVersionIface {\n guideId: string;\n versionId: string;\n slug: string;\n title: string;\n number: number;\n image: string;\n // `.final/sandbox-template.yaml` v2 as JSON.\n templateConfig: JsonValue;\n // The start-time parameters this version defaults to.\n defaultParameters: JsonValue;\n instructionsMarkdown: string | null;\n // A ready build from the guide's provider, reusable independently of workspace seeds.\n preparedArtifact?: { providerRef: string; key: string; artifact: JsonValue };\n}\n\n// The organization's computer setup guides, read through the session service.\n// Every provider gets the same reader; a provider whose\n// environments name no guide never calls it.\nexport interface SandboxGuidesIface {\n get(args: { ref: string; version: number | 'latest' }): Promise<SandboxGuideVersionIface | null>;\n // The organization's default guide; null when it has none.\n default(): Promise<SandboxGuideVersionIface | null>;\n}\n\n// Where to clone a repository from, with a short-lived read credential that\n// must reach only the clone process (never a repository's git config).\nexport interface SandboxRepositoryCloneSourceIface {\n url: string;\n // Checked out after the clone; null keeps the default branch.\n ref: string | null;\n // An HTTP Authorization header value for the clone, or null.\n authorization: string | null;\n}\n\n// Repository credentials for the repositories an environment names (a Code\n// Storage id, a GitHub owner/name), resolved by the session service for the\n// session's organization only. Null: not a repository it can resolve.\nexport interface SandboxRepositoriesIface {\n cloneSource(args: {\n repository: string;\n ref: string | null;\n }): Promise<SandboxRepositoryCloneSourceIface | null>;\n}\n\n// Reads a named organization variable (managed in Build) for the session's\n// organization. Values are injected into the sandbox only, never stored in a\n// manifest, a state or the log.\nexport interface SandboxVariablesIface {\n get(name: string): Promise<string | null>;\n}\n\nexport const noSandboxGuides: SandboxGuidesIface = {\n get: async () => null,\n default: async () => null,\n};\n\nexport const noSandboxRepositories: SandboxRepositoriesIface = {\n cloneSource: async () => null,\n};\n\nexport const noSandboxVariables: SandboxVariablesIface = { get: async () => null };\n\n// The user a session acts for: the author of its running turn, else its owner,\n// else the user whose Home its conversation is. A call a person makes through\n// the platform's sandbox viewer acts for that person instead. Null when it acts\n// for no user (a turn nobody prompted in a shared conversation) and outside any\n// session (a guide build). Read on each call, because it changes between turns\n// and between callers.\nexport interface SandboxActingUserIface {\n current(): Promise<string | null>;\n}\n\nexport const noSandboxActingUser: SandboxActingUserIface = { current: async () => null };\n\n// What an environment's pre-start reads (capabilities, mcpCatalog) are given.\nexport interface SandboxOfferContextIface {\n bindings?: HostedBindingsIface;\n organizationId: string;\n actingUser: SandboxActingUserIface;\n}\n\n// What an environment's hooks are given before anything starts.\nexport interface SandboxEnvironmentContextIface {\n bindings?: HostedBindingsIface;\n organizationId: string;\n guides: SandboxGuidesIface;\n}\n\n// Scoped by the host to this organization and provider. Providers can retain\n// reusable intermediate artifacts independently of a revision's seed files.\nexport interface SandboxArtifactsIface {\n get(key: string): Promise<JsonValue | null>;\n put(key: string, artifact: JsonValue): Promise<void>;\n}\n\nexport interface SandboxPreparationSourceIface {\n sourceRevision: string;\n read(): Promise<{ files: Record<string, string>; resources: Record<string, JsonValue> }>;\n}\n\nexport interface SandboxPrepareContextIface {\n bindings?: HostedBindingsIface;\n // A host-persisted resource source; artifacts may retain its identity instead of seed contents.\n preparation?: SandboxPreparationSourceIface;\n artifacts?: SandboxArtifactsIface;\n // Agent revisions supply workspace-relative seeds; setup-guide builds supply\n // guide.json and optional instructions.md. Resources name workspace, skills or guide.\n // Model instructions remain harness config.\n files: Record<string, string>;\n resources: Record<string, JsonValue>;\n sourceRevision: string;\n storagePath: string;\n organizationId: string;\n // The guide inputs (build-time) an environment names, resolved by the platform.\n guides: SandboxGuidesIface;\n // Who the session the artifact is prepared for acts for, for environments that\n // name a backend resource relative to that user; the key must then name it.\n actingUser: SandboxActingUserIface;\n log?: (message: string) => void;\n}\n\nexport interface SandboxStartContextIface {\n bindings?: HostedBindingsIface;\n /** Passive recovery only: never wake, create, seed, or restart backend services. */\n passive?: boolean;\n preparation?: SandboxPreparationSourceIface;\n session: {\n id: string;\n organizationId: string;\n conversationId: string | null;\n definitionId: string;\n bindingId: string;\n target: string;\n };\n storagePath: string;\n // Start-time inputs: guides, the variables to inject, repository credentials.\n guides: SandboxGuidesIface;\n variables: SandboxVariablesIface;\n repositories: SandboxRepositoriesIface;\n actingUser: SandboxActingUserIface;\n // Variables the platform sets in every process of this sandbox: the egress\n // proxy, trust for its CA, and one placeholder per bound secret. Evaluated\n // again for every spawn/run, never once per session: a secret bound\n // mid-session must reach the next command. May resolve to {} (no proxy\n // configured, or not ready yet). Platform values override the spec's env.\n platformEnvironment?: () => Promise<Record<string, string>>;\n // Hosts the sandbox must be able to reach for the proxy to work, to append\n // to any allowlist-mode network policy the spec declares.\n platformEgressHosts?: string[];\n // Reports the network policy now in force on the sandbox, exactly as the\n // provider applied it to its backend (after withPlatformEgressHosts). The\n // platform records it so the egress proxy serves only those destinations.\n // Called after awaitRunning and before platformFiles or any command, on start,\n // resume and a reused sandbox; never for a session's own setNetworkPolicy,\n // which the platform records itself. A rejection fails the start or resume.\n platformNetworkPolicy: (policy: NetworkPolicyIface) => Promise<void>;\n // Files the platform needs in the sandbox before any clone, setup step or\n // service runs: written right after the sandbox exists, on start and resume.\n // Paths are absolute; missing parent directories are created.\n platformFiles?: () => Promise<Record<string, string>>;\n}\n\n// The variables `platformEnvironment` owns. A spec that sets one (as a plain\n// value or an organization variable) is refused at start.\nexport const PLATFORM_ENVIRONMENT_NAMES: ReadonlySet<string> = new Set([\n 'HTTPS_PROXY',\n 'HTTP_PROXY',\n 'NO_PROXY',\n 'NODE_USE_ENV_PROXY',\n 'SSL_CERT_FILE',\n 'CURL_CA_BUNDLE',\n 'REQUESTS_CA_BUNDLE',\n 'GIT_SSL_CAINFO',\n 'CARGO_HTTP_CAINFO',\n 'DENO_CERT',\n 'NODE_EXTRA_CA_CERTS',\n 'FINAL_EGRESS_URL',\n 'FINAL_EGRESS_TOKEN',\n 'GH_TOKEN',\n 'GITHUB_TOKEN',\n]);\n\n// A process's base environment: the spec's variables under the platform's,\n// read again on every call.\nexport const platformProcessEnvironment =\n (\n ctx: Pick<SandboxStartContextIface, 'platformEnvironment'>,\n specEnv: Record<string, string>,\n ): (() => Promise<Record<string, string>>) =>\n async () => ({ ...specEnv, ...(await ctx.platformEnvironment?.()) });\n\n// Writes `platformFiles` into a sandbox that now exists, before it runs anything.\n// Relies on writeTextFile creating missing parent directories.\nexport const writePlatformFiles = async (\n ctx: Pick<SandboxStartContextIface, 'platformFiles'>,\n sandbox: Pick<SandboxSessionIface, 'writeTextFile'>,\n): Promise<void> => {\n for (const [path, content] of Object.entries((await ctx.platformFiles?.()) ?? {}))\n await sandbox.writeTextFile({ path, content });\n};\n\n// Reports the policy a provider just applied to its backend: `allow` only for an\n// allowlist, its entries (hosts, `*.suffix` patterns, CIDRs) unchanged.\nexport const reportPlatformNetworkPolicy = async (\n ctx: Pick<SandboxStartContextIface, 'platformNetworkPolicy'>,\n policy: NetworkPolicyIface,\n): Promise<void> =>\n ctx.platformNetworkPolicy(\n policy.mode === NetworkPolicy.Allowlist\n ? { mode: policy.mode, allow: [...(policy.allow ?? [])] }\n : { mode: policy.mode },\n );\n\n// An allowlist policy with the platform's egress hosts appended; any other\n// policy unchanged.\nexport const withPlatformEgressHosts = (\n ctx: Pick<SandboxStartContextIface, 'platformEgressHosts'>,\n policy: NetworkPolicyIface,\n): NetworkPolicyIface => {\n const hosts = ctx.platformEgressHosts ?? [];\n if (policy.mode !== NetworkPolicy.Allowlist || hosts.length === 0) return policy;\n return { ...policy, allow: [...new Set([...(policy.allow ?? []), ...hosts])] };\n};\n\nexport enum SandboxSessionEndReason {\n Completed = 'completed',\n Expired = 'expired',\n Failed = 'failed',\n}\n\n// How long an environment's sandbox outlives a session: `session`\n// keeps it for the session's life; `conversation` gives every session in the\n// conversation one shared sandbox per target, surviving session resets;\n// `ephemeral` discards it when released.\nexport enum SandboxWorkspace {\n Session = 'session',\n Conversation = 'conversation',\n Ephemeral = 'ephemeral',\n}\n\nexport interface SandboxProviderImplementationIface<\n OpenOptions,\n Artifact extends JsonValue,\n State extends JsonValue,\n S extends NetworkSandboxSessionIface,\n> {\n // The workspace this environment declares, read before anything starts so the\n // session service knows which sessions share a binding. Absent or null: session.\n workspace?(ctx: SandboxEnvironmentContextIface): Promise<SandboxWorkspace | null>;\n // The capabilities this environment's sandboxes offer, read before anything\n // starts through the backend's own API. Absent or null: unknown\n // until started; local MCP is then not projected.\n capabilities?(ctx: SandboxOfferContextIface): Promise<SandboxCapability[] | null>;\n // The hosted MCP servers' tool catalogs the backend can give without starting\n // a sandbox (from its own records), so the MCP projection lists them from the\n // first `tools/list`. The projection checks a server's catalog against the\n // live server when a call first opens that server (servers a session never\n // uses stay closed) and announces a change with\n // `notifications/tools/list_changed`.\n //\n // Trade-off: a catalog left unknown (absent hook, null, or a null field) can\n // only be learned from the live sandbox, so the first `tools/list` that finds\n // it unknown starts the sandbox in the background, at session start rather\n // than on the first tool call. Otherwise those tools would never be listed,\n // and nothing would ever call them. Providers that can give the catalog keep\n // attach lazy.\n mcpCatalog?(ctx: SandboxOfferContextIface): Promise<SandboxMcpCatalogIface | null>;\n // Reads committed files without starting/resuming a sandbox. Null means the backend\n // is live or offers no snapshot. An unavailable sleeping snapshot must throw,\n // never fall through to a read that wakes it. Pin subsequent ranges by snapshotId.\n readSnapshot?(\n ctx: SandboxOfferContextIface,\n state: State,\n request: SandboxSnapshotRequestIface,\n ): Promise<SandboxSnapshotResponseIface | null>;\n // Inspect retained backend processes without opening, resuming or extending a sandbox.\n // Stop requires execute access; the provider also enforces backend ownership.\n processes?(\n ctx: SandboxOfferContextIface & { bindingId: string },\n state: State,\n request: ProcessInspectionRequestIface,\n ): Promise<ProcessInspectionResultIface>;\n // Browser editor for this provider's existing workspace. The host checks write\n // authorization; this hook never creates or wakes a backend. Credentials stay\n // in the authentication form, never the editor URL or stored provider state.\n editor?(\n ctx: SandboxOfferContextIface,\n state: State,\n request: SandboxEditorRequestIface,\n ): Promise<SandboxEditorResultIface>;\n // Content-addressed by `artifactKey`; the session service caches artifacts in\n // agent.sandbox_artifacts and calls prepare only on a miss.\n artifactKey(ctx: SandboxPrepareContextIface): Promise<string>;\n prepare(ctx: SandboxPrepareContextIface): Promise<Artifact>;\n // Resolves once the backend sandbox named by `state` is running and will\n // accept a command or a file write; rejects with a clear error after\n // `timeoutMs`. Backend-specific: the provider chooses the readiness signal,\n // the polling cadence and the backoff for its API's rate limits. The\n // platform never polls a backend itself.\n //\n // `start`, `resume` and `resumePassive` call it on the sandbox they just\n // created, started or reused, before anything touches it: create or start \u2192\n // state \u2192 awaitRunning \u2192 platformNetworkPolicy \u2192 platformFiles \u2192 repositories,\n // seeds, setup, services \u2192 handle. On timeout `start` fails and tears down.\n awaitRunning(\n ctx: SandboxStartContextIface,\n state: State,\n options: { timeoutMs: number },\n ): Promise<void>;\n // `region`: where the backend placed the sandbox (its own region name), so the\n // session service can place the harness near it; null when unknown.\n start(\n ctx: SandboxStartContextIface,\n options: OpenOptions | undefined,\n artifact: Artifact,\n ): Promise<{ handle: SandboxProviderHandleIface<S>; state: State; region?: string | null }>;\n resume(\n ctx: SandboxStartContextIface,\n artifact: Artifact,\n state: State,\n ): Promise<SandboxProviderHandleIface<S>>;\n // Reconnect to an already running backend after host restart for a read-only viewer.\n // Absent: viewers can use a retained live handle but cannot trigger resume.\n resumePassive?(\n ctx: SandboxStartContextIface,\n artifact: Artifact,\n state: State,\n ): Promise<SandboxProviderHandleIface<S>>;\n // Park: pause or stop the sandbox, returning the state resume needs.\n park?(ctx: SandboxStartContextIface, artifact: Artifact, state: State): Promise<State>;\n onSessionEnd?(\n ctx: SandboxStartContextIface,\n artifact: Artifact,\n state: State,\n options: { reason: SandboxSessionEndReason },\n ): Promise<void>;\n}\n\nexport interface SandboxProviderDefinitionIface<\n EnvOptions,\n OpenOptions,\n Artifact extends JsonValue,\n State extends JsonValue,\n S extends NetworkSandboxSessionIface,\n> {\n name: string;\n // The version of `State`'s shape. The session service records it with each\n // binding and refuses to resume a state written under another version (the\n // next call starts the sandbox again instead).\n stateProtocolVersion?: number;\n environment(\n options?: EnvOptions,\n ): SandboxProviderImplementationIface<OpenOptions, Artifact, State, S>;\n}\n\n// A defined provider: the definition plus authoring sugar. `environment(opts)`\n// returns an environment whose `.open(openOptions)` records a sandbox binding\n// target when authored, and is what the session service drives at run time.\nexport interface SandboxProviderIface<\n EnvOptions,\n OpenOptions,\n Artifact extends JsonValue,\n State extends JsonValue,\n S extends NetworkSandboxSessionIface,\n> {\n readonly definition: SandboxProviderDefinitionIface<EnvOptions, OpenOptions, Artifact, State, S>;\n readonly name: string;\n environment(options?: EnvOptions): AwaitableSandboxEnvironmentIface<EnvOptions, OpenOptions>;\n}\n\nexport interface SandboxEnvironmentIface<EnvOptions, OpenOptions> {\n readonly providerName: string;\n readonly options: EnvOptions | undefined;\n // Provider-authored notices shown by the compiler and Build before publication.\n readonly authoringWarnings?: readonly string[];\n // Authoring: records the open options (access, ...) for this target.\n open(options?: OpenOptions): SandboxOpenRequestIface<EnvOptions, OpenOptions>;\n}\n\n// An environment whose open request a sandbox.ts selector can await to get\n// the live session (open-scope.ts); what defineSandboxProvider and the\n// installed helpers return.\nexport interface AwaitableSandboxEnvironmentIface<\n EnvOptions,\n OpenOptions,\n> extends SandboxEnvironmentIface<EnvOptions, OpenOptions> {\n open(options?: OpenOptions): AwaitableSandboxOpenRequestIface<EnvOptions, OpenOptions>;\n}\n\nexport interface SandboxOpenRequestIface<EnvOptions, OpenOptions> {\n readonly providerName: string;\n readonly environmentOptions: EnvOptions | undefined;\n readonly openOptions: OpenOptions | undefined;\n readonly authoringWarnings?: readonly string[];\n}\n\nexport const defineSandboxProvider = <\n EnvOptions,\n OpenOptions,\n Artifact extends JsonValue,\n State extends JsonValue,\n S extends NetworkSandboxSessionIface,\n>(\n definition: SandboxProviderDefinitionIface<EnvOptions, OpenOptions, Artifact, State, S>,\n): SandboxProviderIface<EnvOptions, OpenOptions, Artifact, State, S> => ({\n // An implementation exists only once its options are given, so awaitRunning is\n // checked as each environment is defined, before anything can start from it.\n definition: {\n ...definition,\n environment: (options) => {\n const implementation = definition.environment(options);\n if (typeof implementation.awaitRunning !== 'function')\n throw new Error(`sandbox provider ${definition.name} does not implement awaitRunning`);\n return implementation;\n },\n },\n name: definition.name,\n environment: (options) => ({\n providerName: definition.name,\n options,\n open: (openOptions) =>\n awaitableOpenRequest({\n providerName: definition.name,\n environmentOptions: options,\n openOptions,\n }),\n }),\n});\n\n// Erased form the session service stores in its provider registry.\nexport type AnySandboxProviderIface = SandboxProviderIface<\n JsonValue,\n JsonValue,\n JsonValue,\n JsonValue,\n NetworkSandboxSessionIface\n>;\n\n// Events emitted through a sandbox provider's process lifecycle.\nexport enum SandboxEventKind {\n ProcessExited = 'process_exited',\n}\n"],
5
+ "mappings": "AAQA,SAAS,4BAAmE;AAoCrE,IAAK,mBAAL,kBAAKA,sBAAL;AACL,EAAAA,kBAAA,UAAO;AACP,EAAAA,kBAAA,eAAY;AACZ,EAAAA,kB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B;AAAA,MACnB,cAAc,WAAW;AAAA,MACzB,oBAAoB;AAAA,MACpB;AAAA,IACF,CAAC;AAAA,EACL;AACF;AAYO,IAAK,mBAAL,kBAAKC,sBAAL;AACL,EAAAA,kBAAA,mBAAgB;AADN,SAAAA;AAAA,GAAA;",
6
6
  "names": ["SandboxEntryType", "NetworkPolicy", "PortProtocol", "SandboxCapability", "SandboxSessionEndReason", "SandboxWorkspace", "SandboxEventKind"]
7
7
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@finalai/agent-provider",
3
- "version": "0.1.6",
3
+ "version": "0.1.7",
4
4
  "private": false,
5
5
  "description": "Provider contracts for the agent stack: harnesses, sandboxes (handle, wire, MCP projection), channels, credential policies, and the conformance kit.",
6
6
  "license": "Apache-2.0",