@finalai/agent-provider 0.10.0 → 0.12.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (61) hide show
  1. package/README.md +23 -35
  2. package/dist/modules/channel.d.mts +53 -12
  3. package/dist/modules/channel.mjs +1 -0
  4. package/dist/modules/channel.mjs.map +2 -2
  5. package/dist/modules/credential-routes.d.mts +1 -3
  6. package/dist/modules/credential-routes.mjs +0 -2
  7. package/dist/modules/credential-routes.mjs.map +2 -2
  8. package/dist/modules/document.d.mts +0 -18
  9. package/dist/modules/document.mjs +1 -16
  10. package/dist/modules/document.mjs.map +3 -3
  11. package/dist/modules/index.d.mts +0 -1
  12. package/dist/modules/index.mjs +0 -1
  13. package/dist/modules/index.mjs.map +2 -2
  14. package/dist/modules/local-channel-context.d.mts +1 -1
  15. package/dist/modules/local-channel-context.mjs +1 -1
  16. package/dist/modules/local-channel-context.mjs.map +2 -2
  17. package/dist/modules/sandbox/client.mjs +0 -3
  18. package/dist/modules/sandbox/client.mjs.map +2 -2
  19. package/dist/modules/sandbox/execution-guard.d.mts +0 -1
  20. package/dist/modules/sandbox/execution-guard.mjs +0 -9
  21. package/dist/modules/sandbox/execution-guard.mjs.map +2 -2
  22. package/dist/modules/sandbox/grant.d.mts +0 -1
  23. package/dist/modules/sandbox/grant.mjs +0 -4
  24. package/dist/modules/sandbox/grant.mjs.map +2 -2
  25. package/dist/modules/sandbox/index.d.mts +0 -2
  26. package/dist/modules/sandbox/index.mjs +1 -10
  27. package/dist/modules/sandbox/index.mjs.map +2 -2
  28. package/dist/modules/sandbox/mcp-hosted.d.mts +0 -1
  29. package/dist/modules/sandbox/mcp-hosted.mjs +1 -8
  30. package/dist/modules/sandbox/mcp-hosted.mjs.map +2 -2
  31. package/dist/modules/sandbox/mcp.d.mts +2 -4
  32. package/dist/modules/sandbox/mcp.mjs +6 -52
  33. package/dist/modules/sandbox/mcp.mjs.map +2 -2
  34. package/dist/modules/sandbox/remote/body.d.mts +1 -0
  35. package/dist/modules/sandbox/remote/body.mjs +27 -0
  36. package/dist/modules/sandbox/remote/body.mjs.map +7 -0
  37. package/dist/modules/sandbox/remote/serve.mjs +3 -2
  38. package/dist/modules/sandbox/remote/serve.mjs.map +2 -2
  39. package/dist/modules/sandbox/server.mjs +0 -14
  40. package/dist/modules/sandbox/server.mjs.map +2 -2
  41. package/dist/modules/sandbox/setup/apply.d.mts +1 -2
  42. package/dist/modules/sandbox/setup/apply.mjs +6 -20
  43. package/dist/modules/sandbox/setup/apply.mjs.map +2 -2
  44. package/dist/modules/sandbox/setup/describe.mjs +1 -1
  45. package/dist/modules/sandbox/setup/describe.mjs.map +1 -1
  46. package/dist/modules/sandbox/setup/schema.d.mts +2 -1
  47. package/dist/modules/sandbox/tool-policy.mjs +1 -19
  48. package/dist/modules/sandbox/tool-policy.mjs.map +2 -2
  49. package/dist/modules/sandbox/types.d.mts +2 -16
  50. package/dist/modules/sandbox/types.mjs +4 -13
  51. package/dist/modules/sandbox/types.mjs.map +3 -3
  52. package/dist/modules/sandbox/wire.d.mts +0 -17
  53. package/dist/modules/sandbox/wire.mjs +0 -12
  54. package/dist/modules/sandbox/wire.mjs.map +2 -2
  55. package/package.json +3 -8
  56. package/dist/modules/room-surface.d.mts +0 -350
  57. package/dist/modules/room-surface.mjs +0 -156
  58. package/dist/modules/room-surface.mjs.map +0 -7
  59. package/dist/modules/sandbox/networking.d.mts +0 -73
  60. package/dist/modules/sandbox/networking.mjs +0 -157
  61. package/dist/modules/sandbox/networking.mjs.map +0 -7
@@ -44,7 +44,6 @@ const resolveEnvironment = async (setup, secrets) => {
44
44
  }
45
45
  return { environment, secretValues };
46
46
  };
47
- const isGitUrl = (value) => /^(https?:\/\/|ssh:\/\/|git@)/.test(value);
48
47
  const commandScript = (args) => [
49
48
  "#!/bin/bash",
50
49
  "set -eu",
@@ -92,44 +91,31 @@ const applySandboxSetup = async (args) => {
92
91
  const ref = repository.ref ?? null;
93
92
  const cloned = await handle.stat({ path: `${destination}/.git` }) != null;
94
93
  if (cloned && ref == null) continue;
95
- const source = await args.repositories.cloneSource({ repository: repository.repository, ref }) ?? (isGitUrl(repository.repository) ? { url: repository.repository, ref, authorization: null } : null);
96
- if (source == null)
97
- throw new Error(
98
- `repository ${repository.repository} (${repository.alias}) is not one this project can reach`
99
- );
100
- const credential = source.authorization == null ? {} : {
101
- GIT_CONFIG_COUNT: "1",
102
- GIT_CONFIG_KEY_0: "http.extraHeader",
103
- GIT_CONFIG_VALUE_0: `Authorization: ${source.authorization}`
104
- };
105
94
  const git = `git -C ${shellQuote(destination)}`;
106
- const checkout = source.ref == null ? null : [
107
- `want=$(${git} rev-parse --verify --quiet ${shellQuote(`${source.ref}^{commit}`)} || true)`,
108
- `if [ -z "$want" ] || [ "$(${git} rev-parse HEAD)" != "$want" ]; then ${git} checkout --quiet ${shellQuote(source.ref)} 2>/dev/null || { ${git} fetch --quiet origin && ${git} checkout --quiet ${shellQuote(source.ref)}; }; fi`
95
+ const checkout = ref == null ? null : [
96
+ `want=$(${git} rev-parse --verify --quiet ${shellQuote(`${ref}^{commit}`)} || true)`,
97
+ `if [ -z "$want" ] || [ "$(${git} rev-parse HEAD)" != "$want" ]; then ${git} checkout --quiet ${shellQuote(ref)} 2>/dev/null || { ${git} fetch --quiet origin && ${git} checkout --quiet ${shellQuote(ref)}; }; fi`
109
98
  ].join("; ");
110
99
  if (cloned && checkout == null) continue;
111
100
  log("sandbox_setup.checkout", { alias: repository.alias });
112
- const redact = scrubber(
113
- source.authorization == null ? secretValues : [...secretValues, source.authorization]
114
- );
115
101
  const result = await handle.run({
116
102
  command: [
117
103
  "set -eu",
118
104
  ...cloned ? [] : [
119
105
  `mkdir -p ${shellQuote(root)}`,
120
- `git clone --quiet -- ${shellQuote(source.url)} ${shellQuote(destination)}`
106
+ `git clone --quiet -- ${shellQuote(repository.url)} ${shellQuote(destination)}`
121
107
  ],
122
108
  ...checkout == null ? [] : [checkout]
123
109
  ].join("; "),
124
110
  shell: true,
125
111
  // Paths are absolute; a sandbox may refuse `/` as outside it.
126
112
  cwd: root,
127
- env: { GIT_TERMINAL_PROMPT: "0", ...credential },
113
+ env: { GIT_TERMINAL_PROMPT: "0" },
128
114
  timeoutMs: SETUP_STEP_TIMEOUT_MS
129
115
  });
130
116
  if (result.exitCode !== 0)
131
117
  throw new Error(
132
- `checkout of ${repository.alias} failed (exit ${result.exitCode}): ${redact(result.stderr.trim()).slice(-2e3)}`
118
+ `checkout of ${repository.alias} failed (exit ${result.exitCode}): ${scrub(result.stderr.trim()).slice(-2e3)}`
133
119
  );
134
120
  }
135
121
  await finish("checkout" /* Checkout */);
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../../../src/sandbox/setup/apply.ts"],
4
- "sourcesContent": ["import * as z from 'zod';\nimport { contentHash } from \"../../canonical-json.mjs\";\nimport { jsonValueSchema } from \"../../json.mjs\";\nimport type {\n NetworkSandboxSessionIface,\n SandboxRepositoriesIface,\n SandboxRunResultIface,\n} from \"../types.mjs\";\nimport { describeSandbox, SANDBOX_DESCRIPTION_PATH } from \"./describe.mjs\";\nimport { checkoutPath, commandPath, commandsDirectory, setupPath, setupRoot } from \"./paths.mjs\";\nimport type { SandboxSetupIface, SetupServiceIface } from \"./schema.mjs\";\n\n// The platform applies a sandbox setup through the standard handle, after the\n// provider reports the machine running. Each phase is idempotent and recorded\n// in the setup state the platform keeps with the sandbox, so a resumed sandbox\n// redoes only what its attach lost: a fresh disk redoes everything, a boot\n// restarts the services, a plain reconnect does nothing.\n//\n// Secrets reach process environments only. They are resolved on every apply,\n// passed as `env` to the commands that need them, never written to a file, the\n// state or a log line, and scrubbed from error text.\n\n// How long a checkout, or a setup step that names no timeout, may run.\nexport const SETUP_STEP_TIMEOUT_MS = 20 * 60_000;\n\nexport enum SandboxSetupPhase {\n Checkout = 'checkout',\n Commands = 'commands',\n Steps = 'steps',\n}\n\nexport const sandboxSetupStateSchema = z.object({\n // contentHash of the setup the recorded phases belong to.\n setup: z.string(),\n // Disk phases finished: they survive until the disk is replaced.\n done: z.array(z.nativeEnum(SandboxSetupPhase)).default([]),\n // Steps finished so far, in order; a retry resumes after them.\n steps: z.number().int().nonnegative().default(0),\n // Services started on the current boot.\n services: z.array(z.string()).default([]),\n});\n\nexport type SandboxSetupStateIface = z.output<typeof sandboxSetupStateSchema>;\n\nexport type SetupHandleIface = Pick<\n NetworkSandboxSessionIface,\n 'defaultWorkingDirectory' | 'run' | 'stat' | 'writeTextFile' | 'getPortUrl'\n>;\n\nexport interface SetupSecretsIface {\n // A project secret's value; null when it is not set.\n get(name: string): Promise<string | null>;\n}\n\nexport interface ApplySandboxSetupArgsIface {\n handle: SetupHandleIface;\n setup: SandboxSetupIface;\n secrets: SetupSecretsIface;\n // What the platform recorded for this sandbox; null before the first apply.\n state: SandboxSetupStateIface | null;\n // What the attach that produced `handle` reported (SandboxAttachmentIface).\n attachment: { fresh: boolean; booted: boolean };\n repositories: SandboxRepositoriesIface;\n // The platform's id for the sandbox, for its description.\n sandboxId: string;\n // Called after each phase or step, so progress survives a failure.\n saveState?: (state: SandboxSetupStateIface) => Promise<void>;\n log?: (message: string, fields?: Record<string, string | number | boolean | null>) => void;\n}\n\nexport interface AppliedSandboxSetupIface {\n state: SandboxSetupStateIface;\n // Every process in the sandbox gets these: the setup's variables with its\n // secrets resolved. In memory only; the platform merges them into\n // `platformEnvironment`.\n environment: Record<string, string>;\n // Where the setup's named commands are; the platform puts it on PATH so a\n // command runs by name.\n commandsDirectory: string;\n}\n\nconst shellQuote = (value: string): string => `'${value.replaceAll(\"'\", \"'\\\\''\")}'`;\n\n// Replaces every secret value in text bound for an error or a log.\nconst scrubber =\n (secrets: readonly string[]) =>\n (text: string): string =>\n secrets.reduce(\n (scrubbed, secret) => (secret.length < 4 ? scrubbed : scrubbed.replaceAll(secret, '****')),\n text,\n );\n\n// The setup's identity: phases recorded for one setup are not trusted for another.\nexport const setupHash = (setup: SandboxSetupIface): Promise<string> =>\n contentHash(jsonValueSchema.parse(JSON.parse(JSON.stringify(setup))));\n\nconst resolveEnvironment = async (\n setup: SandboxSetupIface,\n secrets: SetupSecretsIface,\n): Promise<{ environment: Record<string, string>; secretValues: string[] }> => {\n const environment: Record<string, string> = {};\n const secretValues: string[] = [];\n for (const [name, variable] of Object.entries(setup.variables)) {\n if ('value' in variable) {\n environment[name] = variable.value;\n continue;\n }\n const value = await secrets.get(variable.secret);\n if (value == null)\n throw new Error(\n `variable ${name} needs the project secret ${variable.secret}, which is not set`,\n );\n environment[name] = value;\n secretValues.push(value);\n }\n return { environment, secretValues };\n};\n\nconst isGitUrl = (value: string): boolean => /^(https?:\\/\\/|ssh:\\/\\/|git@)/.test(value);\n\nconst commandScript = (args: { name: string; cwd: string; run: string }): string =>\n [\n '#!/bin/bash',\n 'set -eu',\n `cd -- ${shellQuote(args.cwd)}`,\n `exec bash -c ${shellQuote(args.run)} ${shellQuote(args.name)} \"$@\"`,\n '',\n ].join('\\n');\n\nexport const applySandboxSetup = async (\n args: ApplySandboxSetupArgsIface,\n): Promise<AppliedSandboxSetupIface> => {\n const { handle, setup } = args;\n const log = args.log ?? (() => undefined);\n const hash = await setupHash(setup);\n const { environment, secretValues } = await resolveEnvironment(setup, args.secrets);\n const scrub = scrubber(secretValues);\n const root = setupRoot(handle);\n\n const recorded =\n args.state != null && args.state.setup === hash && !args.attachment.fresh ? args.state : null;\n let state: SandboxSetupStateIface = {\n setup: hash,\n done: recorded?.done ?? [],\n steps: recorded?.steps ?? 0,\n // A boot (or a new disk) stops every process: services start again.\n services: recorded == null || args.attachment.booted ? [] : recorded.services,\n };\n const save = async (next: SandboxSetupStateIface) => {\n state = next;\n await args.saveState?.(next);\n };\n const finish = (phase: SandboxSetupPhase) =>\n save({ ...state, done: state.done.includes(phase) ? state.done : [...state.done, phase] });\n\n const runOrThrow = async (\n label: string,\n options: Parameters<SetupHandleIface['run']>[0],\n ): Promise<SandboxRunResultIface> => {\n const result = await handle.run(options);\n if (result.exitCode !== 0)\n throw new Error(\n `${label} failed (exit ${result.exitCode}): ${scrub(result.stderr.trim()).slice(-2000)}`,\n );\n return result;\n };\n const requireDirectory = async (label: string, cwd: string | undefined): Promise<string> => {\n const path = setupPath(handle, cwd);\n if ((await handle.stat({ path })) == null)\n throw new Error(`${label} runs in ${path}, which does not exist`);\n return path;\n };\n\n if (!state.done.includes(SandboxSetupPhase.Checkout)) {\n for (const repository of setup.repositories) {\n const destination = checkoutPath(handle, repository.alias);\n const ref = repository.ref ?? null;\n const cloned = (await handle.stat({ path: `${destination}/.git` })) != null;\n // A clone with no ref to check out is done; one with a ref is checked\n // below, since an earlier attempt may have cloned and then failed.\n if (cloned && ref == null) continue;\n const source =\n (await args.repositories.cloneSource({ repository: repository.repository, ref })) ??\n (isGitUrl(repository.repository)\n ? { url: repository.repository, ref, authorization: null }\n : null);\n if (source == null)\n throw new Error(\n `repository ${repository.repository} (${repository.alias}) is not one this project can reach`,\n );\n // GIT_CONFIG_* applies the credential to this process only, never to the checkout's config.\n const credential: Record<string, string> =\n source.authorization == null\n ? {}\n : {\n GIT_CONFIG_COUNT: '1',\n GIT_CONFIG_KEY_0: 'http.extraHeader',\n GIT_CONFIG_VALUE_0: `Authorization: ${source.authorization}`,\n };\n const git = `git -C ${shellQuote(destination)}`;\n // Checks the ref out unless HEAD is already its commit; a ref the clone\n // lacks (added since) is fetched first.\n const checkout =\n source.ref == null\n ? null\n : [\n `want=$(${git} rev-parse --verify --quiet ${shellQuote(`${source.ref}^{commit}`)} || true)`,\n `if [ -z \"$want\" ] || [ \"$(${git} rev-parse HEAD)\" != \"$want\" ]; then ${git} checkout --quiet ${shellQuote(source.ref)} 2>/dev/null || { ${git} fetch --quiet origin && ${git} checkout --quiet ${shellQuote(source.ref)}; }; fi`,\n ].join('; ');\n if (cloned && checkout == null) continue;\n log('sandbox_setup.checkout', { alias: repository.alias });\n const redact = scrubber(\n source.authorization == null ? secretValues : [...secretValues, source.authorization],\n );\n const result = await handle.run({\n command: [\n 'set -eu',\n ...(cloned\n ? []\n : [\n `mkdir -p ${shellQuote(root)}`,\n `git clone --quiet -- ${shellQuote(source.url)} ${shellQuote(destination)}`,\n ]),\n ...(checkout == null ? [] : [checkout]),\n ].join('; '),\n shell: true,\n // Paths are absolute; a sandbox may refuse `/` as outside it.\n cwd: root,\n env: { GIT_TERMINAL_PROMPT: '0', ...credential },\n timeoutMs: SETUP_STEP_TIMEOUT_MS,\n });\n if (result.exitCode !== 0)\n throw new Error(\n `checkout of ${repository.alias} failed (exit ${result.exitCode}): ${redact(result.stderr.trim()).slice(-2000)}`,\n );\n }\n await finish(SandboxSetupPhase.Checkout);\n }\n\n if (!state.done.includes(SandboxSetupPhase.Commands)) {\n const names = Object.keys(setup.commands);\n for (const [name, command] of Object.entries(setup.commands))\n await handle.writeTextFile({\n path: commandPath(handle, name),\n content: commandScript({ name, cwd: setupPath(handle, command.cwd), run: command.run }),\n });\n if (names.length > 0)\n await runOrThrow('installing commands', {\n command: `chmod 0755 ${names.map((name) => shellQuote(commandPath(handle, name))).join(' ')}`,\n shell: true,\n cwd: root,\n timeoutMs: 60_000,\n });\n await finish(SandboxSetupPhase.Commands);\n }\n\n if (!state.done.includes(SandboxSetupPhase.Steps)) {\n for (const [index, step] of setup.steps.entries()) {\n if (index < state.steps) continue;\n const label = `setup step ${index + 1}${step.name == null ? '' : ` (${step.name})`}`;\n log('sandbox_setup.step', { index });\n const run = async () =>\n runOrThrow(label, {\n command: `set -eu\\n${step.run}`,\n shell: true,\n cwd: await requireDirectory(label, step.cwd),\n env: environment,\n timeoutMs:\n step.timeoutSeconds == null ? SETUP_STEP_TIMEOUT_MS : step.timeoutSeconds * 1000,\n });\n if (step.optional === true)\n await run().catch(() => log('sandbox_setup.optional_step_failed', { index }));\n else await run();\n await save({ ...state, steps: index + 1 });\n }\n await finish(SandboxSetupPhase.Steps);\n }\n\n const startService = async (service: SetupServiceIface): Promise<void> => {\n const label = `service ${service.name}`;\n const logFile = `${root}/.final/services/${service.name}.log`;\n // Detached from this call: a service outlives the connection that started it.\n await runOrThrow(`starting ${label}`, {\n command: `mkdir -p ${shellQuote(`${root}/.final/services`)} && nohup bash -lc ${shellQuote(service.run)} >${shellQuote(logFile)} 2>&1 </dev/null &`,\n shell: true,\n cwd: await requireDirectory(label, service.cwd),\n env: environment,\n timeoutMs: 60_000,\n });\n log('sandbox_setup.service_started', { service: service.name });\n };\n // Each service is recorded as it starts, so a retry on the same boot starts\n // only the ones that had not.\n for (const service of setup.services) {\n if (state.services.includes(service.name)) continue;\n await startService(service);\n await save({ ...state, services: [...state.services, service.name] });\n }\n\n const description = await describeSandbox({ handle, setup, sandboxId: args.sandboxId });\n await handle.writeTextFile({\n path: setupPath(handle, SANDBOX_DESCRIPTION_PATH),\n content: description.markdown,\n });\n return { state, environment, commandsDirectory: commandsDirectory(handle) };\n};\n"],
5
- "mappings": "AAAA,YAAY,OAAO;AACnB,SAAS,mBAAmB;AAC5B,SAAS,uBAAuB;AAMhC,SAAS,iBAAiB,gCAAgC;AAC1D,SAAS,cAAc,aAAa,mBAAmB,WAAW,iBAAiB;AAc5E,MAAM,wBAAwB,KAAK;AAEnC,IAAK,oBAAL,kBAAKA,uBAAL;AACL,EAAAA,mBAAA,cAAW;AACX,EAAAA,mBAAA,cAAW;AACX,EAAAA,mBAAA,WAAQ;AAHE,SAAAA;AAAA,GAAA;AAML,MAAM,0BAA0B,EAAE,OAAO;AAAA;AAAA,EAE9C,OAAO,EAAE,OAAO;AAAA;AAAA,EAEhB,MAAM,EAAE,MAAM,EAAE,WAAW,iBAAiB,CAAC,EAAE,QAAQ,CAAC,CAAC;AAAA;AAAA,EAEzD,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,YAAY,EAAE,QAAQ,CAAC;AAAA;AAAA,EAE/C,UAAU,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,QAAQ,CAAC,CAAC;AAC1C,CAAC;AAyCD,MAAM,aAAa,CAAC,UAA0B,IAAI,MAA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AC;AACtF,QAAM,OAAO,cAAc;AAAA,IACzB,MAAM,UAAU,QAAQ,wBAAwB;AAAA,IAChD,SAAS,YAAY;AAAA,EACvB,CAAC;AACD,SAAO,EAAE,OAAO,aAAa,mBAAmB,kBAAkB,MAAM,EAAE;AAC5E;",
4
+ "sourcesContent": ["import * as z from 'zod';\nimport { contentHash } from \"../../canonical-json.mjs\";\nimport { jsonValueSchema } from \"../../json.mjs\";\nimport type { NetworkSandboxSessionIface, SandboxRunResultIface } from \"../types.mjs\";\nimport { describeSandbox, SANDBOX_DESCRIPTION_PATH } from \"./describe.mjs\";\nimport { checkoutPath, commandPath, commandsDirectory, setupPath, setupRoot } from \"./paths.mjs\";\nimport type { SandboxSetupIface, SetupServiceIface } from \"./schema.mjs\";\n\n// The platform applies a sandbox setup through the standard handle, after the\n// provider reports the machine running. Each phase is idempotent and recorded\n// in the setup state the platform keeps with the sandbox, so a resumed sandbox\n// redoes only what its attach lost: a fresh disk redoes everything, a boot\n// restarts the services, a plain reconnect does nothing.\n//\n// Secrets reach process environments only. They are resolved on every apply,\n// passed as `env` to the commands that need them, never written to a file, the\n// state or a log line, and scrubbed from error text.\n\n// How long a checkout, or a setup step that names no timeout, may run.\nexport const SETUP_STEP_TIMEOUT_MS = 20 * 60_000;\n\nexport enum SandboxSetupPhase {\n Checkout = 'checkout',\n Commands = 'commands',\n Steps = 'steps',\n}\n\nexport const sandboxSetupStateSchema = z.object({\n // contentHash of the setup the recorded phases belong to.\n setup: z.string(),\n // Disk phases finished: they survive until the disk is replaced.\n done: z.array(z.nativeEnum(SandboxSetupPhase)).default([]),\n // Steps finished so far, in order; a retry resumes after them.\n steps: z.number().int().nonnegative().default(0),\n // Services started on the current boot.\n services: z.array(z.string()).default([]),\n});\n\nexport type SandboxSetupStateIface = z.output<typeof sandboxSetupStateSchema>;\n\nexport type SetupHandleIface = Pick<\n NetworkSandboxSessionIface,\n 'defaultWorkingDirectory' | 'run' | 'stat' | 'writeTextFile' | 'getPortUrl'\n>;\n\nexport interface SetupSecretsIface {\n // A project secret's value; null when it is not set.\n get(name: string): Promise<string | null>;\n}\n\nexport interface ApplySandboxSetupArgsIface {\n handle: SetupHandleIface;\n setup: SandboxSetupIface;\n secrets: SetupSecretsIface;\n // What the platform recorded for this sandbox; null before the first apply.\n state: SandboxSetupStateIface | null;\n // What the attach that produced `handle` reported (SandboxAttachmentIface).\n attachment: { fresh: boolean; booted: boolean };\n // The platform's id for the sandbox, for its description.\n sandboxId: string;\n // Called after each phase or step, so progress survives a failure.\n saveState?: (state: SandboxSetupStateIface) => Promise<void>;\n log?: (message: string, fields?: Record<string, string | number | boolean | null>) => void;\n}\n\nexport interface AppliedSandboxSetupIface {\n state: SandboxSetupStateIface;\n // Every process in the sandbox gets these: the setup's variables with its\n // secrets resolved. In memory only; the platform merges them into\n // `platformEnvironment`.\n environment: Record<string, string>;\n // Where the setup's named commands are; the platform puts it on PATH so a\n // command runs by name.\n commandsDirectory: string;\n}\n\nconst shellQuote = (value: string): string => `'${value.replaceAll(\"'\", \"'\\\\''\")}'`;\n\n// Replaces every secret value in text bound for an error or a log.\nconst scrubber =\n (secrets: readonly string[]) =>\n (text: string): string =>\n secrets.reduce(\n (scrubbed, secret) => (secret.length < 4 ? scrubbed : scrubbed.replaceAll(secret, '****')),\n text,\n );\n\n// The setup's identity: phases recorded for one setup are not trusted for another.\nexport const setupHash = (setup: SandboxSetupIface): Promise<string> =>\n contentHash(jsonValueSchema.parse(JSON.parse(JSON.stringify(setup))));\n\nconst resolveEnvironment = async (\n setup: SandboxSetupIface,\n secrets: SetupSecretsIface,\n): Promise<{ environment: Record<string, string>; secretValues: string[] }> => {\n const environment: Record<string, string> = {};\n const secretValues: string[] = [];\n for (const [name, variable] of Object.entries(setup.variables)) {\n if ('value' in variable) {\n environment[name] = variable.value;\n continue;\n }\n const value = await secrets.get(variable.secret);\n if (value == null)\n throw new Error(\n `variable ${name} needs the project secret ${variable.secret}, which is not set`,\n );\n environment[name] = value;\n secretValues.push(value);\n }\n return { environment, secretValues };\n};\n\nconst commandScript = (args: { name: string; cwd: string; run: string }): string =>\n [\n '#!/bin/bash',\n 'set -eu',\n `cd -- ${shellQuote(args.cwd)}`,\n `exec bash -c ${shellQuote(args.run)} ${shellQuote(args.name)} \"$@\"`,\n '',\n ].join('\\n');\n\nexport const applySandboxSetup = async (\n args: ApplySandboxSetupArgsIface,\n): Promise<AppliedSandboxSetupIface> => {\n const { handle, setup } = args;\n const log = args.log ?? (() => undefined);\n const hash = await setupHash(setup);\n const { environment, secretValues } = await resolveEnvironment(setup, args.secrets);\n const scrub = scrubber(secretValues);\n const root = setupRoot(handle);\n\n const recorded =\n args.state != null && args.state.setup === hash && !args.attachment.fresh ? args.state : null;\n let state: SandboxSetupStateIface = {\n setup: hash,\n done: recorded?.done ?? [],\n steps: recorded?.steps ?? 0,\n // A boot (or a new disk) stops every process: services start again.\n services: recorded == null || args.attachment.booted ? [] : recorded.services,\n };\n const save = async (next: SandboxSetupStateIface) => {\n state = next;\n await args.saveState?.(next);\n };\n const finish = (phase: SandboxSetupPhase) =>\n save({ ...state, done: state.done.includes(phase) ? state.done : [...state.done, phase] });\n\n const runOrThrow = async (\n label: string,\n options: Parameters<SetupHandleIface['run']>[0],\n ): Promise<SandboxRunResultIface> => {\n const result = await handle.run(options);\n if (result.exitCode !== 0)\n throw new Error(\n `${label} failed (exit ${result.exitCode}): ${scrub(result.stderr.trim()).slice(-2000)}`,\n );\n return result;\n };\n const requireDirectory = async (label: string, cwd: string | undefined): Promise<string> => {\n const path = setupPath(handle, cwd);\n if ((await handle.stat({ path })) == null)\n throw new Error(`${label} runs in ${path}, which does not exist`);\n return path;\n };\n\n if (!state.done.includes(SandboxSetupPhase.Checkout)) {\n for (const repository of setup.repositories) {\n const destination = checkoutPath(handle, repository.alias);\n const ref = repository.ref ?? null;\n const cloned = (await handle.stat({ path: `${destination}/.git` })) != null;\n // A clone with no ref to check out is done; one with a ref is checked\n // below, since an earlier attempt may have cloned and then failed.\n if (cloned && ref == null) continue;\n const git = `git -C ${shellQuote(destination)}`;\n // Checks the ref out unless HEAD is already its commit; a ref the clone\n // lacks (added since) is fetched first.\n const checkout =\n ref == null\n ? null\n : [\n `want=$(${git} rev-parse --verify --quiet ${shellQuote(`${ref}^{commit}`)} || true)`,\n `if [ -z \"$want\" ] || [ \"$(${git} rev-parse HEAD)\" != \"$want\" ]; then ${git} checkout --quiet ${shellQuote(ref)} 2>/dev/null || { ${git} fetch --quiet origin && ${git} checkout --quiet ${shellQuote(ref)}; }; fi`,\n ].join('; ');\n if (cloned && checkout == null) continue;\n // The clone carries no credential: the sandbox's egress adds one for the URL's host,\n // when an integration serving it is provided.\n log('sandbox_setup.checkout', { alias: repository.alias });\n const result = await handle.run({\n command: [\n 'set -eu',\n ...(cloned\n ? []\n : [\n `mkdir -p ${shellQuote(root)}`,\n `git clone --quiet -- ${shellQuote(repository.url)} ${shellQuote(destination)}`,\n ]),\n ...(checkout == null ? [] : [checkout]),\n ].join('; '),\n shell: true,\n // Paths are absolute; a sandbox may refuse `/` as outside it.\n cwd: root,\n env: { GIT_TERMINAL_PROMPT: '0' },\n timeoutMs: SETUP_STEP_TIMEOUT_MS,\n });\n if (result.exitCode !== 0)\n throw new Error(\n `checkout of ${repository.alias} failed (exit ${result.exitCode}): ${scrub(result.stderr.trim()).slice(-2000)}`,\n );\n }\n await finish(SandboxSetupPhase.Checkout);\n }\n\n if (!state.done.includes(SandboxSetupPhase.Commands)) {\n const names = Object.keys(setup.commands);\n for (const [name, command] of Object.entries(setup.commands))\n await handle.writeTextFile({\n path: commandPath(handle, name),\n content: commandScript({ name, cwd: setupPath(handle, command.cwd), run: command.run }),\n });\n if (names.length > 0)\n await runOrThrow('installing commands', {\n command: `chmod 0755 ${names.map((name) => shellQuote(commandPath(handle, name))).join(' ')}`,\n shell: true,\n cwd: root,\n timeoutMs: 60_000,\n });\n await finish(SandboxSetupPhase.Commands);\n }\n\n if (!state.done.includes(SandboxSetupPhase.Steps)) {\n for (const [index, step] of setup.steps.entries()) {\n if (index < state.steps) continue;\n const label = `setup step ${index + 1}${step.name == null ? '' : ` (${step.name})`}`;\n log('sandbox_setup.step', { index });\n const run = async () =>\n runOrThrow(label, {\n command: `set -eu\\n${step.run}`,\n shell: true,\n cwd: await requireDirectory(label, step.cwd),\n env: environment,\n timeoutMs:\n step.timeoutSeconds == null ? SETUP_STEP_TIMEOUT_MS : step.timeoutSeconds * 1000,\n });\n if (step.optional === true)\n await run().catch(() => log('sandbox_setup.optional_step_failed', { index }));\n else await run();\n await save({ ...state, steps: index + 1 });\n }\n await finish(SandboxSetupPhase.Steps);\n }\n\n const startService = async (service: SetupServiceIface): Promise<void> => {\n const label = `service ${service.name}`;\n const logFile = `${root}/.final/services/${service.name}.log`;\n // Detached from this call: a service outlives the connection that started it.\n await runOrThrow(`starting ${label}`, {\n command: `mkdir -p ${shellQuote(`${root}/.final/services`)} && nohup bash -lc ${shellQuote(service.run)} >${shellQuote(logFile)} 2>&1 </dev/null &`,\n shell: true,\n cwd: await requireDirectory(label, service.cwd),\n env: environment,\n timeoutMs: 60_000,\n });\n log('sandbox_setup.service_started', { service: service.name });\n };\n // Each service is recorded as it starts, so a retry on the same boot starts\n // only the ones that had not.\n for (const service of setup.services) {\n if (state.services.includes(service.name)) continue;\n await startService(service);\n await save({ ...state, services: [...state.services, service.name] });\n }\n\n const description = await describeSandbox({ handle, setup, sandboxId: args.sandboxId });\n await handle.writeTextFile({\n path: setupPath(handle, SANDBOX_DESCRIPTION_PATH),\n content: description.markdown,\n });\n return { state, environment, commandsDirectory: commandsDirectory(handle) };\n};\n"],
5
+ "mappings": "AAAA,YAAY,OAAO;AACnB,SAAS,mBAAmB;AAC5B,SAAS,uBAAuB;AAEhC,SAAS,iBAAiB,gCAAgC;AAC1D,SAAS,cAAc,aAAa,mBAAmB,WAAW,iBAAiB;AAc5E,MAAM,wBAAwB,KAAK;AAEnC,IAAK,oBAAL,kBAAKA,uBAAL;AACL,EAAAA,mBAAA,cAAW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OAAO,aAAa,mBAAmB,kBAAkB,MAAM,EAAE;AAC5E;",
6
6
  "names": ["SandboxSetupPhase"]
7
7
  }
@@ -42,7 +42,7 @@ const describeSandbox = async (args) => {
42
42
  workspace: setupRoot(handle),
43
43
  checkouts: (setup?.repositories ?? []).map((repository) => ({
44
44
  alias: repository.alias,
45
- repository: repository.repository,
45
+ repository: repository.url,
46
46
  ref: repository.ref ?? null,
47
47
  path: checkoutPath(handle, repository.alias)
48
48
  })),
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../../../src/sandbox/setup/describe.ts"],
4
- "sourcesContent": ["import type { SandboxDescriptionIface } from '@finalai/agent-protocol/agent-platform';\nimport type { NetworkSandboxSessionIface } from \"../types.mjs\";\nimport { checkoutPath, setupRoot } from \"./paths.mjs\";\nimport type { SandboxSetupIface } from \"./schema.mjs\";\n\n// What is known about a sandbox once its setup is applied: where each\n// repository really is, the URL of each service, the commands it can run by\n// name and the setup's notes, in the shape `GET \u2026/sandboxes/:id/description`\n// answers. The markdown is also written into the sandbox as\n// SANDBOX_DESCRIPTION_PATH. Nothing puts it into an agent's context; a caller\n// that wants it there adds it to the instructions.\n\nexport type { SandboxDescriptionIface } from '@finalai/agent-protocol/agent-platform';\n\n// Relative to the working directory.\nexport const SANDBOX_DESCRIPTION_PATH = '.final/sandbox.md';\n\nconst renderMarkdown = (\n description: Omit<SandboxDescriptionIface, 'markdown'>,\n commandDescriptions: Partial<Record<string, string>>,\n): string => {\n const lines = ['# This sandbox'];\n if (description.workspace != null)\n lines.push('', `Working directory: \\`${description.workspace}\\``);\n if (description.checkouts.length > 0) {\n lines.push('', '## Repositories', '');\n for (const checkout of description.checkouts)\n lines.push(\n `- \\`${checkout.path}\\`: ${checkout.repository}${checkout.ref == null ? '' : ` at ${checkout.ref}`}`,\n );\n }\n if (description.services.length > 0) {\n lines.push('', '## Services', '');\n for (const service of description.services) {\n const where = service.url ?? (service.port == null ? null : `port ${service.port}`);\n lines.push(`- ${service.name}${where == null ? '' : `: ${where}`}`);\n }\n }\n if (description.commands.length > 0) {\n lines.push('', '## Commands', '');\n for (const command of description.commands) {\n const about = commandDescriptions[command];\n lines.push(`- \\`${command}\\`${about == null ? '' : `: ${about}`}`);\n }\n }\n if (description.notes != null) lines.push('', '## Notes', '', description.notes);\n return `${lines.join('\\n')}\\n`;\n};\n\nexport const describeSandbox = async (args: {\n handle: Pick<NetworkSandboxSessionIface, 'defaultWorkingDirectory' | 'getPortUrl'>;\n setup: SandboxSetupIface | null;\n sandboxId: string;\n}): Promise<SandboxDescriptionIface> => {\n const { handle } = args;\n const setup = args.setup;\n const services: SandboxDescriptionIface['services'] = [];\n for (const service of setup?.services ?? []) {\n const url =\n service.port == null\n ? null\n : await handle.getPortUrl({ port: service.port }).catch(() => null);\n services.push({ name: service.name, port: service.port ?? null, url });\n }\n const description: Omit<SandboxDescriptionIface, 'markdown'> = {\n sandboxId: args.sandboxId,\n workspace: setupRoot(handle),\n checkouts: (setup?.repositories ?? []).map((repository) => ({\n alias: repository.alias,\n repository: repository.repository,\n ref: repository.ref ?? null,\n path: checkoutPath(handle, repository.alias),\n })),\n services,\n commands: Object.keys(setup?.commands ?? {}),\n notes: setup?.notes ?? null,\n };\n const commandDescriptions: Partial<Record<string, string>> = {};\n for (const [name, command] of Object.entries(setup?.commands ?? {}))\n if (command.description != null) commandDescriptions[name] = command.description;\n return { ...description, markdown: renderMarkdown(description, commandDescriptions) };\n};\n"],
4
+ "sourcesContent": ["import type { SandboxDescriptionIface } from '@finalai/agent-protocol/agent-platform';\nimport type { NetworkSandboxSessionIface } from \"../types.mjs\";\nimport { checkoutPath, setupRoot } from \"./paths.mjs\";\nimport type { SandboxSetupIface } from \"./schema.mjs\";\n\n// What is known about a sandbox once its setup is applied: where each\n// repository really is, the URL of each service, the commands it can run by\n// name and the setup's notes, in the shape `GET \u2026/sandboxes/:id/description`\n// answers. The markdown is also written into the sandbox as\n// SANDBOX_DESCRIPTION_PATH. Nothing puts it into an agent's context; a caller\n// that wants it there adds it to the instructions.\n\nexport type { SandboxDescriptionIface } from '@finalai/agent-protocol/agent-platform';\n\n// Relative to the working directory.\nexport const SANDBOX_DESCRIPTION_PATH = '.final/sandbox.md';\n\nconst renderMarkdown = (\n description: Omit<SandboxDescriptionIface, 'markdown'>,\n commandDescriptions: Partial<Record<string, string>>,\n): string => {\n const lines = ['# This sandbox'];\n if (description.workspace != null)\n lines.push('', `Working directory: \\`${description.workspace}\\``);\n if (description.checkouts.length > 0) {\n lines.push('', '## Repositories', '');\n for (const checkout of description.checkouts)\n lines.push(\n `- \\`${checkout.path}\\`: ${checkout.repository}${checkout.ref == null ? '' : ` at ${checkout.ref}`}`,\n );\n }\n if (description.services.length > 0) {\n lines.push('', '## Services', '');\n for (const service of description.services) {\n const where = service.url ?? (service.port == null ? null : `port ${service.port}`);\n lines.push(`- ${service.name}${where == null ? '' : `: ${where}`}`);\n }\n }\n if (description.commands.length > 0) {\n lines.push('', '## Commands', '');\n for (const command of description.commands) {\n const about = commandDescriptions[command];\n lines.push(`- \\`${command}\\`${about == null ? '' : `: ${about}`}`);\n }\n }\n if (description.notes != null) lines.push('', '## Notes', '', description.notes);\n return `${lines.join('\\n')}\\n`;\n};\n\nexport const describeSandbox = async (args: {\n handle: Pick<NetworkSandboxSessionIface, 'defaultWorkingDirectory' | 'getPortUrl'>;\n setup: SandboxSetupIface | null;\n sandboxId: string;\n}): Promise<SandboxDescriptionIface> => {\n const { handle } = args;\n const setup = args.setup;\n const services: SandboxDescriptionIface['services'] = [];\n for (const service of setup?.services ?? []) {\n const url =\n service.port == null\n ? null\n : await handle.getPortUrl({ port: service.port }).catch(() => null);\n services.push({ name: service.name, port: service.port ?? null, url });\n }\n const description: Omit<SandboxDescriptionIface, 'markdown'> = {\n sandboxId: args.sandboxId,\n workspace: setupRoot(handle),\n checkouts: (setup?.repositories ?? []).map((repository) => ({\n alias: repository.alias,\n repository: repository.url,\n ref: repository.ref ?? null,\n path: checkoutPath(handle, repository.alias),\n })),\n services,\n commands: Object.keys(setup?.commands ?? {}),\n notes: setup?.notes ?? null,\n };\n const commandDescriptions: Partial<Record<string, string>> = {};\n for (const [name, command] of Object.entries(setup?.commands ?? {}))\n if (command.description != null) commandDescriptions[name] = command.description;\n return { ...description, markdown: renderMarkdown(description, commandDescriptions) };\n};\n"],
5
5
  "mappings": "AAEA,SAAS,cAAc,iBAAiB;AAajC,MAAM,2BAA2B;AAExC,MAAM,iBAAiB,CACrB,aACA,wBACW;AACX,QAAM,QAAQ,CAAC,gBAAgB;AAC/B,MAAI,YAAY,aAAa;AAC3B,UAAM,KAAK,IAAI,wBAAwB,YAAY,SAAS,IAAI;AAClE,MAAI,YAAY,UAAU,SAAS,GAAG;AACpC,UAAM,KAAK,IAAI,mBAAmB,EAAE;AACpC,eAAW,YAAY,YAAY;AACjC,YAAM;AAAA,QACJ,OAAO,SAAS,IAAI,OAAO,SAAS,UAAU,GAAG,SAAS,OAAO,OAAO,KAAK,OAAO,SAAS,GAAG,EAAE;AAAA,MACpG;AAAA,EACJ;AACA,MAAI,YAAY,SAAS,SAAS,GAAG;AACnC,UAAM,KAAK,IAAI,eAAe,EAAE;AAChC,eAAW,WAAW,YAAY,UAAU;AAC1C,YAAM,QAAQ,QAAQ,QAAQ,QAAQ,QAAQ,OAAO,OAAO,QAAQ,QAAQ,IAAI;AAChF,YAAM,KAAK,KAAK,QAAQ,IAAI,GAAG,SAAS,OAAO,KAAK,KAAK,KAAK,EAAE,EAAE;AAAA,IACpE;AAAA,EACF;AACA,MAAI,YAAY,SAAS,SAAS,GAAG;AACnC,UAAM,KAAK,IAAI,eAAe,EAAE;AAChC,eAAW,WAAW,YAAY,UAAU;AAC1C,YAAM,QAAQ,oBAAoB,OAAO;AACzC,YAAM,KAAK,OAAO,OAAO,KAAK,SAAS,OAAO,KAAK,KAAK,KAAK,EAAE,EAAE;AAAA,IACnE;AAAA,EACF;AACA,MAAI,YAAY,SAAS,KAAM,OAAM,KAAK,IAAI,YAAY,IAAI,YAAY,KAAK;AAC/E,SAAO,GAAG,MAAM,KAAK,IAAI,CAAC;AAAA;AAC5B;AAEO,MAAM,kBAAkB,OAAO,SAIE;AACtC,QAAM,EAAE,OAAO,IAAI;AACnB,QAAM,QAAQ,KAAK;AACnB,QAAM,WAAgD,CAAC;AACvD,aAAW,WAAW,OAAO,YAAY,CAAC,GAAG;AAC3C,UAAM,MACJ,QAAQ,QAAQ,OACZ,OACA,MAAM,OAAO,WAAW,EAAE,MAAM,QAAQ,KAAK,CAAC,EAAE,MAAM,MAAM,IAAI;AACtE,aAAS,KAAK,EAAE,MAAM,QAAQ,MAAM,MAAM,QAAQ,QAAQ,MAAM,IAAI,CAAC;AAAA,EACvE;AACA,QAAM,cAAyD;AAAA,IAC7D,WAAW,KAAK;AAAA,IAChB,WAAW,UAAU,MAAM;AAAA,IAC3B,YAAY,OAAO,gBAAgB,CAAC,GAAG,IAAI,CAAC,gBAAgB;AAAA,MAC1D,OAAO,WAAW;AAAA,MAClB,YAAY,WAAW;AAAA,MACvB,KAAK,WAAW,OAAO;AAAA,MACvB,MAAM,aAAa,QAAQ,WAAW,KAAK;AAAA,IAC7C,EAAE;AAAA,IACF;AAAA,IACA,UAAU,OAAO,KAAK,OAAO,YAAY,CAAC,CAAC;AAAA,IAC3C,OAAO,OAAO,SAAS;AAAA,EACzB;AACA,QAAM,sBAAuD,CAAC;AAC9D,aAAW,CAAC,MAAM,OAAO,KAAK,OAAO,QAAQ,OAAO,YAAY,CAAC,CAAC;AAChE,QAAI,QAAQ,eAAe,KAAM,qBAAoB,IAAI,IAAI,QAAQ;AACvE,SAAO,EAAE,GAAG,aAAa,UAAU,eAAe,aAAa,mBAAmB,EAAE;AACtF;",
6
6
  "names": []
7
7
  }
@@ -8,8 +8,9 @@ export declare const SETUP_ROOT_CWD = ".";
8
8
  export declare const sandboxSetupSchema: import("zod").ZodObject<{
9
9
  repositories: import("zod").ZodDefault<import("zod").ZodArray<import("zod").ZodObject<{
10
10
  alias: import("zod").ZodString;
11
- repository: import("zod").ZodString;
11
+ url: import("zod").ZodString;
12
12
  ref: import("zod").ZodOptional<import("zod").ZodString>;
13
+ integration: import("zod").ZodOptional<import("zod").ZodString>;
13
14
  }, import("zod/v4/core").$strict>>>;
14
15
  variables: import("zod").ZodDefault<import("zod").ZodRecord<import("zod").ZodString, import("zod").ZodUnion<readonly [import("zod").ZodObject<{
15
16
  value: import("zod").ZodString;
@@ -17,7 +17,6 @@ const nativePolicyKeys = /* @__PURE__ */ new Set([
17
17
  "process",
18
18
  "ports",
19
19
  "networkPolicy",
20
- "egress",
21
20
  "computerUse",
22
21
  "screen",
23
22
  "localMcp",
@@ -26,27 +25,10 @@ const nativePolicyKeys = /* @__PURE__ */ new Set([
26
25
  "files.read",
27
26
  "files.write",
28
27
  "lifecycle",
29
- "network",
30
- "network.egress",
31
- "network.egress.configure",
32
- "network.egress.disable",
33
- "network.egress.status"
28
+ "network"
34
29
  ]);
35
30
  const resolveSandboxToolPolicy = (policy, keys) => {
36
31
  const valueOf = (key) => Object.hasOwn(policy, key) ? policy[key] : void 0;
37
- const egress = keys.includes("egress") && keys.includes("network.egress");
38
- if (egress) {
39
- const key = keys.find((candidate) => valueOf(candidate) === ToolApproval.Ask);
40
- if (key != null) return { key, decision: ToolApproval.Ask };
41
- }
42
- if (egress && (keys.includes("network.egress.configure") || keys.includes("network.egress.disable"))) {
43
- const actionKey = keys.includes("network.egress.configure") ? "network.egress.configure" : "network.egress.disable";
44
- const key = valueOf(actionKey) === ToolApproval.Allow ? actionKey : void 0;
45
- return {
46
- key: key ?? actionKey,
47
- decision: key == null ? ToolApproval.Ask : ToolApproval.Allow
48
- };
49
- }
50
32
  const hosted = keys.length > 1 && (keys.includes("localMcp") || keys.includes("computerUse"));
51
33
  for (const [index, key] of keys.entries()) {
52
34
  const decision = valueOf(key);
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../../src/sandbox/tool-policy.ts"],
4
- "sourcesContent": ["import { ToolApprovalMode as ToolApproval } from \"../document.mjs\";\n\n// Native names remain eligible for Ask, but cannot lend an Allow to a hosted tool.\nconst nativePolicyKeys = new Set([\n 'run',\n 'spawn',\n 'process_output',\n 'process_input',\n 'process_terminate',\n 'read_file',\n 'write_file',\n 'edit_file',\n 'list_dir',\n 'stat',\n 'grep',\n 'glob',\n 'get_host',\n 'files',\n 'process',\n 'ports',\n 'networkPolicy',\n 'egress',\n 'computerUse',\n 'screen',\n 'localMcp',\n 'browser',\n 'shell',\n 'files.read',\n 'files.write',\n 'lifecycle',\n 'network',\n 'network.egress',\n 'network.egress.configure',\n 'network.egress.disable',\n 'network.egress.status',\n]);\n\n// Network and lifecycle consent both apply to egress mutations; neither Allow can waive an Ask.\nexport const resolveSandboxToolPolicy = (\n policy: Record<string, ToolApproval>,\n keys: readonly string[],\n): { key: string; decision: ToolApproval } | null => {\n const valueOf = (key: string) => (Object.hasOwn(policy, key) ? policy[key] : undefined);\n const egress = keys.includes('egress') && keys.includes('network.egress');\n if (egress) {\n const key = keys.find((candidate) => valueOf(candidate) === ToolApproval.Ask);\n if (key != null) return { key, decision: ToolApproval.Ask };\n }\n if (\n egress &&\n (keys.includes('network.egress.configure') || keys.includes('network.egress.disable'))\n ) {\n const actionKey = keys.includes('network.egress.configure')\n ? 'network.egress.configure'\n : 'network.egress.disable';\n const key = valueOf(actionKey) === ToolApproval.Allow ? actionKey : undefined;\n return {\n key: key ?? actionKey,\n decision: key == null ? ToolApproval.Ask : ToolApproval.Allow,\n };\n }\n const hosted = keys.length > 1 && (keys.includes('localMcp') || keys.includes('computerUse'));\n for (const [index, key] of keys.entries()) {\n const decision = valueOf(key);\n if (hosted && index === 0 && nativePolicyKeys.has(key) && decision === ToolApproval.Allow)\n continue;\n if (decision === ToolApproval.Ask || decision === ToolApproval.Allow) return { key, decision };\n }\n return null;\n};\n"],
5
- "mappings": "AAAA,SAAS,oBAAoB,oBAAoB;AAGjD,MAAM,mBAAmB,oBAA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QAAI,aAAa,aAAa,OAAO,aAAa,aAAa,MAAO,QAAO,EAAE,KAAK,SAAS;AAAA,EAC/F;AACA,SAAO;AACT;",
4
+ "sourcesContent": ["import { ToolApprovalMode as ToolApproval } from \"../document.mjs\";\n\n// Native names remain eligible for Ask, but cannot lend an Allow to a hosted tool.\nconst nativePolicyKeys = new Set([\n 'run',\n 'spawn',\n 'process_output',\n 'process_input',\n 'process_terminate',\n 'read_file',\n 'write_file',\n 'edit_file',\n 'list_dir',\n 'stat',\n 'grep',\n 'glob',\n 'get_host',\n 'files',\n 'process',\n 'ports',\n 'networkPolicy',\n 'computerUse',\n 'screen',\n 'localMcp',\n 'browser',\n 'shell',\n 'files.read',\n 'files.write',\n 'lifecycle',\n 'network',\n]);\n\n// The first key the policy decides, most specific first. A hosted tool cannot\n// borrow an Allow from a native name it shadows.\nexport const resolveSandboxToolPolicy = (\n policy: Record<string, ToolApproval>,\n keys: readonly string[],\n): { key: string; decision: ToolApproval } | null => {\n const valueOf = (key: string) => (Object.hasOwn(policy, key) ? policy[key] : undefined);\n const hosted = keys.length > 1 && (keys.includes('localMcp') || keys.includes('computerUse'));\n for (const [index, key] of keys.entries()) {\n const decision = valueOf(key);\n if (hosted && index === 0 && nativePolicyKeys.has(key) && decision === ToolApproval.Allow)\n continue;\n if (decision === ToolApproval.Ask || decision === ToolApproval.Allow) return { key, decision };\n }\n return null;\n};\n"],
5
+ "mappings": "AAAA,SAAS,oBAAoB,oBAAoB;AAGjD,MAAM,mBAAmB,oBAAI,IAAI;AAAA,EAC/B;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,CAAC;AAIM,MAAM,2BAA2B,CACtC,QACA,SACmD;AACnD,QAAM,UAAU,CAAC,QAAiB,OAAO,OAAO,QAAQ,GAAG,IAAI,OAAO,GAAG,IAAI;AAC7E,QAAM,SAAS,KAAK,SAAS,MAAM,KAAK,SAAS,UAAU,KAAK,KAAK,SAAS,aAAa;AAC3F,aAAW,CAAC,OAAO,GAAG,KAAK,KAAK,QAAQ,GAAG;AACzC,UAAM,WAAW,QAAQ,GAAG;AAC5B,QAAI,UAAU,UAAU,KAAK,iBAAiB,IAAI,GAAG,KAAK,aAAa,aAAa;AAClF;AACF,QAAI,aAAa,aAAa,OAAO,aAAa,aAAa,MAAO,QAAO,EAAE,KAAK,SAAS;AAAA,EAC/F;AACA,SAAO;AACT;",
6
6
  "names": []
7
7
  }
@@ -3,8 +3,8 @@ import * as z from 'zod';
3
3
  import { SandboxEntryType } from "./file-kind.mjs";
4
4
  export { SandboxEntryType } from "./file-kind.mjs";
5
5
  import { type SandboxExecutionPolicyIface } from "./handle.mjs";
6
- import type { WorkspaceEgressRequestIface, WorkspaceEgressStatusIface, WorkspaceNetworkPolicyIface as NetworkPolicyIface } from '@finalai/agent-protocol/device-egress';
7
- export { WorkspaceNetworkPolicy as NetworkPolicy, type WorkspaceNetworkPolicyIface as NetworkPolicyIface, } from '@finalai/agent-protocol/device-egress';
6
+ import { type NetworkPolicyIface } from '@finalai/agent-protocol/network-policy';
7
+ export { NetworkPolicy, type NetworkPolicyIface } from '@finalai/agent-protocol/network-policy';
8
8
  import type { ProcessInspectionRequestIface, ProcessInspectionResultIface } from '@finalai/agent-protocol/process-inspection';
9
9
  import type { JsonValue } from "../json.mjs";
10
10
  import type { ToolDescriptorIface } from "../tool-descriptor.mjs";
@@ -210,7 +210,6 @@ export interface NetworkSandboxSessionIface extends SandboxSessionIface {
210
210
  stop(): Promise<void>;
211
211
  destroy(): Promise<void>;
212
212
  setNetworkPolicy?(policy: NetworkPolicyIface): Promise<void>;
213
- egress?(request: WorkspaceEgressRequestIface): Promise<WorkspaceEgressStatusIface>;
214
213
  computerUse?(): Promise<SandboxMcpEndpoint>;
215
214
  startWorker?(options: SandboxWorkerOptionsIface): Promise<SandboxWorkerStartType>;
216
215
  screen?(options?: ScreenOptionsIface): Promise<ScreenSessionIface>;
@@ -221,7 +220,6 @@ export declare enum SandboxCapability {
221
220
  Process = "process",
222
221
  Ports = "ports",
223
222
  NetworkPolicy = "networkPolicy",
224
- Egress = "egress",
225
223
  ComputerUse = "computerUse",
226
224
  Screen = "screen",
227
225
  LocalMcp = "localMcp",
@@ -239,18 +237,6 @@ export interface SandboxProviderHandleIface<S extends SandboxSessionIface> {
239
237
  }): Promise<void>;
240
238
  onRuntimeShutdown(): Promise<void>;
241
239
  }
242
- export interface SandboxRepositoryCloneSourceIface {
243
- url: string;
244
- ref: string | null;
245
- authorization: string | null;
246
- }
247
- export interface SandboxRepositoriesIface {
248
- cloneSource(args: {
249
- repository: string;
250
- ref: string | null;
251
- }): Promise<SandboxRepositoryCloneSourceIface | null>;
252
- }
253
- export declare const noSandboxRepositories: SandboxRepositoriesIface;
254
240
  export interface SandboxActingUserIface {
255
241
  current(): Promise<string | null>;
256
242
  }
@@ -4,10 +4,8 @@ import { SandboxEntryType } from "./file-kind.mjs";
4
4
  import { SandboxEntryType as SandboxEntryType2 } from "./file-kind.mjs";
5
5
  import { createSandboxHandle } from "./handle.mjs";
6
6
  import { withSandboxOverrides } from "./overrides.mjs";
7
- import { WorkspaceNetworkPolicy as NetworkPolicy } from "@finalai/agent-protocol/device-egress";
8
- import {
9
- WorkspaceNetworkPolicy
10
- } from "@finalai/agent-protocol/device-egress";
7
+ import { NetworkPolicy } from "@finalai/agent-protocol/network-policy";
8
+ import { NetworkPolicy as NetworkPolicy2 } from "@finalai/agent-protocol/network-policy";
11
9
  import {
12
10
  SandboxEditorOperation
13
11
  } from "./editor.mjs";
@@ -31,7 +29,6 @@ var SandboxCapability = /* @__PURE__ */ ((SandboxCapability2) => {
31
29
  SandboxCapability2["Process"] = "process";
32
30
  SandboxCapability2["Ports"] = "ports";
33
31
  SandboxCapability2["NetworkPolicy"] = "networkPolicy";
34
- SandboxCapability2["Egress"] = "egress";
35
32
  SandboxCapability2["ComputerUse"] = "computerUse";
36
33
  SandboxCapability2["Screen"] = "screen";
37
34
  SandboxCapability2["LocalMcp"] = "localMcp";
@@ -40,9 +37,6 @@ var SandboxCapability = /* @__PURE__ */ ((SandboxCapability2) => {
40
37
  SandboxCapability2["Workers"] = "workers";
41
38
  return SandboxCapability2;
42
39
  })(SandboxCapability || {});
43
- const noSandboxRepositories = {
44
- cloneSource: async () => null
45
- };
46
40
  const noSandboxActingUser = { current: async () => null };
47
41
  const noSandboxCredentials = { secret: async () => null };
48
42
  const sandboxCredentialRefSchema = z.strictObject({
@@ -64,9 +58,7 @@ const PLATFORM_ENVIRONMENT_NAMES = /* @__PURE__ */ new Set([
64
58
  "DENO_CERT",
65
59
  "NODE_EXTRA_CA_CERTS",
66
60
  "FINAL_EGRESS_URL",
67
- "FINAL_EGRESS_TOKEN",
68
- "GH_TOKEN",
69
- "GITHUB_TOKEN"
61
+ "FINAL_EGRESS_TOKEN"
70
62
  ]);
71
63
  const platformProcessEnvironment = (ctx, specEnv) => async () => ({ ...specEnv, ...await ctx.platformEnvironment?.() });
72
64
  const writePlatformFiles = async (ctx, sandbox) => {
@@ -141,7 +133,7 @@ var SandboxEventKind = /* @__PURE__ */ ((SandboxEventKind2) => {
141
133
  return SandboxEventKind2;
142
134
  })(SandboxEventKind || {});
143
135
  export {
144
- WorkspaceNetworkPolicy as NetworkPolicy,
136
+ NetworkPolicy2 as NetworkPolicy,
145
137
  PLATFORM_ENVIRONMENT_NAMES,
146
138
  PortProtocol,
147
139
  SandboxCapability,
@@ -154,7 +146,6 @@ export {
154
146
  noSandboxActingUser,
155
147
  noSandboxCredentials,
156
148
  noSandboxIdentity,
157
- noSandboxRepositories,
158
149
  platformProcessEnvironment,
159
150
  reportPlatformNetworkPolicy,
160
151
  sandboxCredentialRefSchema,
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../../src/sandbox/types.ts"],
4
- "sourcesContent": ["import { Capability, RuntimeKind, type CapabilityAccess } from '@finalai/agent-protocol';\nimport * as z from 'zod';\nimport { SandboxEntryType } from \"./file-kind.mjs\";\nexport { SandboxEntryType } from \"./file-kind.mjs\";\nimport { createSandboxHandle, type SandboxExecutionPolicyIface } from \"./handle.mjs\";\nimport { withSandboxOverrides } from \"./overrides.mjs\";\nimport { WorkspaceNetworkPolicy as NetworkPolicy } from '@finalai/agent-protocol/device-egress';\nimport type {\n WorkspaceEgressRequestIface,\n WorkspaceEgressStatusIface,\n WorkspaceNetworkPolicyIface as NetworkPolicyIface,\n} from '@finalai/agent-protocol/device-egress';\nexport {\n WorkspaceNetworkPolicy as NetworkPolicy,\n type WorkspaceNetworkPolicyIface as NetworkPolicyIface,\n} from '@finalai/agent-protocol/device-egress';\nimport type {\n ProcessInspectionRequestIface,\n ProcessInspectionResultIface,\n} from '@finalai/agent-protocol/process-inspection';\nimport type { JsonValue } from \"../json.mjs\";\nimport type { ToolDescriptorIface } from \"../tool-descriptor.mjs\";\nimport {\n SandboxEditorOperation,\n type SandboxEditorRequestIface,\n type SandboxEditorResultIface,\n} from \"./editor.mjs\";\nimport { SandboxExecutionOperation } from \"./execution-guard.mjs\";\nimport type { SandboxSetupIface } from \"./setup/schema.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 // Spawn only (`run` ignores it): ask for a durable process on a sandbox with\n // SandboxCapability.DurableProcesses; ignored elsewhere (the handle's `ref`\n // is then null). A durable process ends only on its own exit, `kill`,\n // `timeoutMs` (enforced inside the sandbox, not by a provider-side timer) or\n // sandbox stop/destroy. Dropping its handle (connection close, runtime\n // shutdown, `abortSignal`) detaches without killing: the handle's streams\n // fail and `wait` rejects, and `attachProcess` finds the process again.\n durable?: boolean;\n}\n\nexport interface SandboxProcessIface {\n readonly pid: string | null;\n // Opaque, provider-encoded (versioned) reference for `attachProcess`; non-null\n // only for a durable process on a sandbox with durable processes. Optional so\n // implementations without them need not set it.\n readonly ref?: 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\n// A program built for the sandbox's worker runtime, started for one harness\n// session. Its handle is a process's: what is written to it is its input\n// stream, stdout its output stream, stderr its diagnostics.\nexport interface SandboxWorkerOptionsIface extends AbortableIface {\n program: string;\n env?: Record<string, string>;\n // Handed to the program when it starts.\n input?: JsonValue;\n // As for spawn: survives the handle on a sandbox with durable processes.\n durable?: boolean;\n // A platform-identity assertion for the program's run (variant `harness-run`),\n // for a runtime that authenticates the programs it starts.\n identity?: string;\n}\n\nexport enum SandboxWorkerEndpointTransport {\n Ws = 'ws',\n Http = 'http',\n Relay = 'relay',\n}\n\n// Where a started worker program serves its stream itself, for the caller to\n// dial directly: an ACP endpoint by URL, or a relay channel.\nexport type SandboxWorkerEndpointType =\n | {\n transport: SandboxWorkerEndpointTransport.Ws | SandboxWorkerEndpointTransport.Http;\n url: string;\n headers: Record<string, string>;\n }\n | { transport: SandboxWorkerEndpointTransport.Relay; channel: string; token: string };\n\nexport interface SandboxWorkerEndpointIface {\n readonly endpoint: SandboxWorkerEndpointType;\n}\n\n// A started worker program: a process whose streams carry its stream, or an\n// endpoint it serves.\nexport type SandboxWorkerStartType = SandboxProcessIface | SandboxWorkerEndpointIface;\n\nexport const isSandboxWorkerEndpoint = (\n started: SandboxWorkerStartType,\n): started is SandboxWorkerEndpointIface => 'endpoint' in started;\n\nexport interface SandboxAttachProcessOptionsIface extends AbortableIface {\n ref: string;\n // Bytes of each stream the caller already has; output resumes there.\n stdoutOffset: number;\n stderrOffset: number;\n}\n\n// A durable process found again by its ref. Its output is read from the\n// provider, which is the source of truth for output and exit; aborting\n// `abortSignal` detaches this handle as it does a spawned durable one.\n//\n// Limitation: stdin belongs to the spawning handle only. A re-attached\n// process can be watched, waited for and killed, but not written to; a process\n// that needs input after a re-attach must read it from somewhere else (a file).\nexport interface SandboxAttachedProcessIface {\n readonly ref: string;\n // Where the streams actually start: the requested offsets, or later when the\n // provider no longer retains the earlier bytes (see each provider's retention).\n readonly stdoutOffset: number;\n readonly stderrOffset: number;\n readonly stdout: ReadableStream<Uint8Array>;\n readonly stderr: ReadableStream<Uint8Array>;\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 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 // Present on sandboxes with durable processes. Null when the process is\n // unknown: the sandbox restarted or was deleted, or the ref expired, is\n // malformed or belongs to another sandbox. Attaching after the process\n // exited still yields its retained output and exit code.\n attachProcess?(\n options: SandboxAttachProcessOptionsIface,\n ): Promise<SandboxAttachedProcessIface | null>;\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 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 host) 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 // Partial discovery retains known tools and must be retried, including after caching.\n localMcpIncomplete?: boolean;\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 egress?(request: WorkspaceEgressRequestIface): Promise<WorkspaceEgressStatusIface>;\n computerUse?(): Promise<SandboxMcpEndpoint>;\n // Present on sandboxes whose provider offers RuntimeKind.Worker.\n startWorker?(options: SandboxWorkerOptionsIface): Promise<SandboxWorkerStartType>;\n screen?(options?: ScreenOptionsIface): Promise<ScreenSessionIface>;\n localMcp?(): Promise<SandboxMcpEndpoint[]>;\n}\n\n// Features a live sandbox handle advertises over the handle RPC (`describe`).\n// Finer than the model's capabilities (`Capability`): `files` is served by the\n// file methods, `shell` by processes and ports, `computerUse` by computer use\n// and the screen; the rest are handle extensions a capability may use.\nexport enum SandboxCapability {\n Files = 'files',\n Process = 'process',\n Ports = 'ports',\n NetworkPolicy = 'networkPolicy',\n Egress = 'egress',\n ComputerUse = 'computerUse',\n Screen = 'screen',\n LocalMcp = 'localMcp',\n Browser = 'browser',\n // `spawn({ durable: true })` and `attachProcess` (see SandboxProcessOptionsIface.durable).\n DurableProcesses = 'durableProcesses',\n // `startWorker`: the sandbox runs worker programs.\n Workers = 'workers',\n}\n\n// The capabilities a provider's sandboxes serve, each with the most access a\n// session can be granted on it. A capability left out is not served.\nexport type SandboxCapabilityOffer = Partial<Record<Capability, CapabilityAccess>>;\n\nexport interface SandboxProviderHandleIface<S extends SandboxSessionIface> {\n readonly sandbox: S;\n // Pending policy; the generic handle constructor consumes it before exposing execution.\n readonly executionPolicy?: SandboxExecutionPolicyIface;\n onSandboxStop(): Promise<void>;\n onSandboxDelete(options?: { reason?: string }): Promise<void>;\n onRuntimeShutdown(): Promise<void>;\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// Clone sources for the repositories a sandbox setup names (`owner/name`, a\n// git URL), authorised against the sandbox's project. Null: not a repository\n// the project can reach.\nexport interface SandboxRepositoriesIface {\n cloneSource(args: {\n repository: string;\n ref: string | null;\n }): Promise<SandboxRepositoryCloneSourceIface | null>;\n}\n\nexport const noSandboxRepositories: SandboxRepositoriesIface = {\n cloneSource: async () => null,\n};\n\n// The person a sandbox acts for on this call: the author of the running turn,\n// else whoever opened the sandbox's viewer. Null when it acts for no person\n// (an unprompted turn, a preparation). Read on each call: it changes between\n// turns and between callers.\nexport interface SandboxActingUserIface {\n current(): Promise<string | null>;\n}\n\nexport const noSandboxActingUser: SandboxActingUserIface = { current: async () => null };\n\n// Credentials the host supplies to a provider. A provider reads no secrets of\n// its own and names no project: it gets the value of the secret its\n// environment's `credential.secretRef` names, resolved in the sandbox's project.\nexport interface SandboxCredentialsIface {\n secret(args: { secretRef: string }): Promise<string | null>;\n}\n\nexport const noSandboxCredentials: SandboxCredentialsIface = { secret: async () => null };\n\n// A provider's credential by reference, in its environment options: the name\n// of a project secret, never its value.\nexport const sandboxCredentialRefSchema = z.strictObject({\n secretRef: z.string().min(1).max(256),\n});\n\nexport type SandboxCredentialRefIface = z.infer<typeof sandboxCredentialRefSchema>;\n\n// A platform-identity assertion (`@finalai/agent-protocol/identity`) for one\n// backend audience, valid until `expiresAt`.\nexport interface SandboxIdentityTokenIface {\n token: string;\n expiresAt: string;\n}\n\n// How a provider authenticates to a backend it needs (its vendor's API): an\n// assertion for `audience`, which the platform issues only for audiences the\n// provider's registration was granted. It names the sandbox's organization,\n// project and sandbox, and the acting user at the time it was issued. Ask\n// before each backend call (hosts cache it); `refresh` asks for a new one\n// after the backend rejected the last.\nexport type SandboxIdentityFn = (args: {\n audience: string;\n refresh?: boolean;\n}) => Promise<SandboxIdentityTokenIface>;\n\nexport const noSandboxIdentity: SandboxIdentityFn = async ({ audience }) => {\n throw new Error(`no identity was granted for ${audience}`);\n};\n\n// What every provider call is given: the project the sandbox belongs to, the\n// host's credentials and the provider's identity for the backends it was\n// granted.\nexport interface SandboxProviderContextIface {\n organizationId: string;\n projectId: string;\n credentials: SandboxCredentialsIface;\n actingUser: SandboxActingUserIface;\n identity: SandboxIdentityFn;\n log?: (message: string, fields?: Record<string, string | number | boolean | null>) => void;\n}\n\n// How the platform runs a sandbox's lifecycle, for the provider to align its\n// backend with: after `parkAfterIdleMs` of idleness the platform parks the\n// sandbox (null: the provider's own default), so a backend idle timeout\n// should be longer.\nexport interface SandboxLifecycleIface {\n parkAfterIdleMs: number | null;\n}\n\n// What reads that start nothing are given (capabilities, catalogs, snapshots,\n// process inspection, the editor). `sandboxId` is set for reads about an\n// existing sandbox.\nexport interface SandboxOfferContextIface extends SandboxProviderContextIface {\n sandboxId?: string;\n executionPolicy?: SandboxExecutionPolicyIface;\n platformNetworkPolicy?: (policy: NetworkPolicyIface) => Promise<void>;\n // Retain platform transport access when an extension restores an allowlist.\n platformEgressHosts?: string[];\n}\n\n// Scoped by the host to this project and provider. Providers can retain\n// reusable intermediate artifacts independently of a sandbox'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\n// A preparation builds what an environment's sandboxes start from (an image\n// built into a base, a snapshot). It depends on the environment's options and\n// the seed files only, never on a sandbox setup.\nexport interface SandboxPrepareContextIface extends SandboxProviderContextIface {\n // A host-persisted resource source; artifacts may retain its identity instead of seed contents.\n preparation?: SandboxPreparationSourceIface;\n artifacts?: SandboxArtifactsIface;\n // Workspace-relative seed files and named resources.\n files: Record<string, string>;\n resources: Record<string, JsonValue>;\n sourceRevision: string;\n storagePath: string;\n}\n\n// What a provider is given for one sandbox: its create, attach, detach, park\n// and delete calls.\nexport interface SandboxResourceContextIface extends SandboxProviderContextIface {\n // The platform's id for the sandbox, stable for its whole life.\n sandboxId: string;\n lifecycle: SandboxLifecycleIface;\n // Host policy composes before the provider's policy, on every exposed execution path.\n executionPolicy?: SandboxExecutionPolicyIface;\n preparation?: SandboxPreparationSourceIface;\n storagePath: string;\n // Variables the platform sets in every process of this sandbox: the egress\n // proxy, trust for its CA, one placeholder per bound secret and the sandbox\n // setup's variables. Evaluated again for every spawn/run, never once per\n // attach: a secret bound later must reach the next command. May resolve to\n // {}. Platform values override the environment's own.\n platformEnvironment?: () => Promise<Record<string, string>>;\n // Hosts the sandbox must be able to reach for the proxy to work, appended\n // to any allowlist network policy.\n platformEgressHosts?: string[];\n // Reports the network policy now in force, exactly as the provider applied\n // it to its backend (after withPlatformEgressHosts); the platform permits\n // only those destinations. Called on every attach after awaitRunning and\n // before platformFiles or any command; never for a session's own\n // setNetworkPolicy. A rejection fails the attach.\n platformNetworkPolicy: (policy: NetworkPolicyIface) => Promise<void>;\n // Files the platform needs before any command runs: written right after the\n // sandbox is running, on every attach. Paths are absolute; missing parent\n // directories are created.\n platformFiles?: () => Promise<Record<string, string>>;\n}\n\n// The variables `platformEnvironment` owns. An environment that sets one is\n// refused at create.\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 environment's variables under the\n// platform's, read again on every call.\nexport const platformProcessEnvironment =\n (\n ctx: Pick<SandboxResourceContextIface, '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 is now running, before it runs anything.\n// Relies on writeTextFile creating missing parent directories.\nexport const writePlatformFiles = async (\n ctx: Pick<SandboxResourceContextIface, '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<SandboxResourceContextIface, '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<SandboxResourceContextIface, '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\n// One attach of a sandbox: the live handle, and what the attach lost, so the\n// platform knows which phases of the sandbox setup to redo.\nexport interface SandboxAttachmentIface<\n State extends JsonValue,\n S extends NetworkSandboxSessionIface,\n> {\n handle: SandboxProviderHandleIface<S>;\n // The state to keep for the next call (a resumed backend may change ids).\n state: State;\n // The disk is new: nothing written by a setup, the workspace seeds or a\n // session survives on it (first attach, or a backend that lost it).\n fresh: boolean;\n // The machine started on this attach: no process from before is running.\n booted: boolean;\n // Where the backend runs the sandbox (its own region name), so the host can\n // place the harness near it; null when unknown.\n region?: string | null;\n}\n\n// One environment of a provider, as the host drives it. A sandbox is a\n// resource the platform owns: `create` makes it (nothing need boot), `attach`\n// makes it reachable for a while, `detach` lets it go idle, `park` makes it as\n// cheap as the provider can while keeping its disk, `delete` destroys it.\n//\n// Order on attach: attach (boot or resume) \u2192 awaitRunning \u2192\n// platformNetworkPolicy \u2192 platformFiles \u2192 handle; the platform then applies\n// the sandbox setup through the handle (./setup). A provider never runs a\n// setup's steps itself.\nexport interface SandboxEnvironmentImplementationIface<\n Artifact extends JsonValue,\n State extends JsonValue,\n S extends NetworkSandboxSessionIface,\n> {\n // The capabilities this environment's sandboxes serve and the most access\n // each grants, known without creating one.\n capabilities(ctx: SandboxOfferContextIface): Promise<SandboxCapabilityOffer>;\n // What a harness can run in this environment's sandboxes: processes, worker\n // programs (`startWorker`), or both. Absent: processes when it offers `shell`.\n runtimes?(ctx: SandboxOfferContextIface): Promise<RuntimeKind[]>;\n // Handle features this environment's sandboxes advertise, read before\n // anything starts. Absent or null: unknown until attached; local MCP is then\n // not projected.\n features?(ctx: SandboxOfferContextIface): Promise<SandboxCapability[] | null>;\n // Known positive features when the rest of the pre-attach set is unknown.\n additionalFeatures?(ctx: SandboxOfferContextIface): Promise<SandboxCapability[]>;\n // The hosted MCP servers' tool catalogs the backend can give without\n // attaching, so the MCP projection lists them from the first `tools/list`.\n // A catalog left unknown can only be learned from a live sandbox, so the\n // first `tools/list` that finds it unknown attaches in the background.\n mcpCatalog?(ctx: SandboxOfferContextIface): Promise<SandboxMcpCatalogIface | null>;\n // Reads committed files without attaching. Null means the backend is live\n // or offers no snapshot. An unavailable sleeping snapshot must throw, never\n // fall through to a read that wakes it. Pin later ranges by snapshotId.\n readSnapshot?(\n ctx: SandboxOfferContextIface,\n state: State,\n request: SandboxSnapshotRequestIface,\n ): Promise<SandboxSnapshotResponseIface | null>;\n // Inspect retained backend processes without attaching or extending a sandbox.\n // Stopping one requires shell access; the provider also enforces backend ownership.\n processes?(\n ctx: SandboxOfferContextIface & { sandboxId: string },\n state: State,\n request: ProcessInspectionRequestIface,\n ): Promise<ProcessInspectionResultIface>;\n // Browser editor for an existing sandbox. 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 host caches artifacts and calls\n // prepare only on a miss.\n artifactKey(ctx: SandboxPrepareContextIface): Promise<string>;\n prepare(ctx: SandboxPrepareContextIface): Promise<Artifact>;\n // Makes the sandbox's backend resource. The setup is given so the\n // provider enforces its network policy from the first boot (or refuses);\n // its repositories, steps and services are applied by the platform.\n create(\n ctx: SandboxResourceContextIface,\n args: { artifact: Artifact; setup: SandboxSetupIface | null },\n ): Promise<{ state: State; region?: string | null }>;\n // Resolves once the backend named by `state` is running and will accept a\n // command or a file write; rejects with a clear error after `timeoutMs`.\n // The provider chooses the readiness signal and backoff; the platform never\n // polls a backend itself.\n awaitRunning(\n ctx: SandboxResourceContextIface,\n state: State,\n options: { timeoutMs: number },\n ): Promise<void>;\n // Boots or resumes the sandbox and returns a live handle.\n attach(\n ctx: SandboxResourceContextIface,\n args: { artifact: Artifact; state: State },\n ): Promise<SandboxAttachmentIface<State, S>>;\n // Reconnects to an already running backend for a read-only viewer: never\n // boots, creates, seeds or restarts anything. Absent: viewers use a live\n // handle or nothing.\n attachPassive?(\n ctx: SandboxResourceContextIface,\n args: { artifact: Artifact; state: State },\n ): Promise<SandboxProviderHandleIface<S>>;\n // The host is done with its handle for now; the sandbox may go idle on the\n // provider's own policy. Returns the state the next attach needs.\n detach(ctx: SandboxResourceContextIface, args: { state: State }): Promise<State>;\n // Pauses or stops the sandbox, keeping its disk. Returns the state the next attach needs.\n park(\n ctx: SandboxResourceContextIface,\n args: { artifact: Artifact; state: State },\n ): Promise<State>;\n // Destroys the backend resource and its disk. Deleting one already gone succeeds.\n delete(ctx: SandboxResourceContextIface, args: { state: State }): Promise<void>;\n}\n\nexport interface SandboxProviderDefinitionIface<\n EnvOptions,\n Artifact extends JsonValue,\n State extends JsonValue,\n S extends NetworkSandboxSessionIface,\n> {\n name: string;\n // The version of `State`'s shape. The host records it with each sandbox and\n // refuses to attach a state written under another version.\n stateProtocolVersion?: number;\n // Validates the options and returns the environment they describe.\n environment(options?: EnvOptions): SandboxEnvironmentImplementationIface<Artifact, State, S>;\n}\n\n// What `project.sandboxes.create(environment, \u2026)` takes: a provider by name\n// and that provider's own environment options, as plain data.\nexport interface SandboxEnvironmentValueIface<EnvOptions = JsonValue> {\n provider: string;\n environment: EnvOptions;\n}\n\n// A defined provider: the definition the host drives, and `environment(opts)`\n// returning the plain value a caller creates sandboxes from.\nexport interface SandboxProviderIface<\n EnvOptions,\n Artifact extends JsonValue,\n State extends JsonValue,\n S extends NetworkSandboxSessionIface,\n> {\n readonly definition: SandboxProviderDefinitionIface<EnvOptions, Artifact, State, S>;\n readonly name: string;\n environment(options: EnvOptions): SandboxEnvironmentValueIface<EnvOptions>;\n}\n\nexport const defineSandboxProvider = <\n EnvOptions,\n Artifact extends JsonValue,\n State extends JsonValue,\n S extends NetworkSandboxSessionIface,\n>(\n definition: SandboxProviderDefinitionIface<EnvOptions, Artifact, State, S>,\n): SandboxProviderIface<EnvOptions, Artifact, State, S> => ({\n definition: withSandboxOverrides(definition, {\n environment: (options?: EnvOptions) => {\n const implementation = definition.environment(options);\n for (const method of [\n 'create',\n 'attach',\n 'detach',\n 'park',\n 'delete',\n 'awaitRunning',\n ] as const)\n if (typeof implementation[method] !== 'function')\n throw new Error(`sandbox provider ${definition.name} does not implement ${method}`);\n const overrides: Partial<typeof implementation> = {\n attach: async (ctx, args) => {\n const attached = await implementation.attach(ctx, args);\n return {\n ...attached,\n handle: createSandboxHandle({\n handle: attached.handle,\n executionPolicy: ctx.executionPolicy,\n }),\n };\n },\n };\n if (implementation.editor != null) {\n const editor = implementation.editor.bind(implementation);\n overrides.editor = async (ctx, state, request) => {\n if (\n request.operation === SandboxEditorOperation.Open ||\n request.operation === SandboxEditorOperation.Refresh\n )\n await ctx.executionPolicy?.beforeExecution({\n operation: SandboxExecutionOperation.Editor,\n background: false,\n });\n return editor(ctx, state, request);\n };\n }\n if (implementation.attachPassive != null) {\n const attachPassive = implementation.attachPassive.bind(implementation);\n overrides.attachPassive = async (ctx, args) =>\n createSandboxHandle({\n handle: await attachPassive(ctx, args),\n executionPolicy: ctx.executionPolicy,\n });\n }\n return withSandboxOverrides(implementation, overrides);\n },\n }),\n name: definition.name,\n environment: (options) => ({ provider: definition.name, environment: options }),\n});\n\n// The runtime kinds an environment declares, or its default.\nexport const sandboxRuntimesOf = async (\n environment: Pick<\n SandboxEnvironmentImplementationIface<JsonValue, JsonValue, NetworkSandboxSessionIface>,\n 'capabilities' | 'runtimes'\n >,\n ctx: SandboxOfferContextIface,\n): Promise<RuntimeKind[]> => {\n if (environment.runtimes != null) return environment.runtimes(ctx);\n const offer = await environment.capabilities(ctx);\n return offer[Capability.Shell] == null ? [] : [RuntimeKind.Process];\n};\n\n// Erased form a host stores in its provider registry.\nexport type AnySandboxProviderIface = SandboxProviderIface<\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": "AAAA,SAAS,YAAY,mBAA0C;AAC/D,YAAY,OAAO;AACnB,SAAS,wBAAwB;AACjC,SAAS,oBAAAA,yBAAwB;AACjC,SAAS,2BAA6D;AACtE,SAAS,4BAA4B;AACrC,SAAS,0BAA0B,qBAAqB;AAMxD;AAAA,EAC4B;AAAA,OAErB;AAOP;AAAA,EACE;AAAA,OAGK;AACP,SAAS,iCAAiC;AA0DnC,IAAK,iCAAL,kBAAKC,oCAAL;AACL,EAAAA,gCAAA,QAAK;AACL,EAAAA,gCAAA,UAAO;AACP,EAAAA,gCAAA,WAAQ;AAHE,SAAAA;AAAA,GAAA;AAwBL,MAAM,0BAA0B,CACrC,YAC0C,cAAc;AAqGnD,IAAK,eAAL,kBAAKC,kBAAL;AACL,EAAAA,cAAA,UAAO;AACP,EAAAA,cAAA,WAAQ;AACR,EAAAA,cAAA,QAAK;AAHK,SAAAA;AAAA,GAAA;AA2CL,MAAM,uBAAuB,CAClC,aACwC,aAAa;AAsChD,IAAK,oBAAL,kBAAKC,uBAAL;AACL,EAAAA,mBAAA,WAAQ;AACR,EAAAA,mBAAA,aAAU;AACV,EAAAA,mBAAA,WAAQ;AACR,EAAAA,mBAAA,mBAAgB;AAChB,EAAAA,mBAAA,YAAS;AACT,EAAAA,mBAAA,iBAAc;AACd,EAAAA,mBAAA,YAAS;AACT,EAAAA,mBAAA,cAAW;AACX,EAAAA,mBAAA,aAAU;AAEV,EAAAA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Ac,KAAK,IAAI;AAAA,UACrC,iBAAiB,IAAI;AAAA,QACvB,CAAC;AAAA,MACL;AACA,aAAO,qBAAqB,gBAAgB,SAAS;AAAA,IACvD;AAAA,EACF,CAAC;AAAA,EACD,MAAM,WAAW;AAAA,EACjB,aAAa,CAAC,aAAa,EAAE,UAAU,WAAW,MAAM,aAAa,QAAQ;AAC/E;AAGO,MAAM,oBAAoB,OAC/B,aAIA,QAC2B;AAC3B,MAAI,YAAY,YAAY,KAAM,QAAO,YAAY,SAAS,GAAG;AACjE,QAAM,QAAQ,MAAM,YAAY,aAAa,GAAG;AAChD,SAAO,MAAM,WAAW,KAAK,KAAK,OAAO,CAAC,IAAI,CAAC,YAAY,OAAO;AACpE;AAWO,IAAK,mBAAL,kBAAKC,sBAAL;AACL,EAAAA,kBAAA,mBAAgB;AADN,SAAAA;AAAA,GAAA;",
6
- "names": ["SandboxEntryType", "SandboxWorkerEndpointTransport", "PortProtocol", "SandboxCapability", "SandboxEventKind"]
4
+ "sourcesContent": ["import { Capability, RuntimeKind, type CapabilityAccess } from '@finalai/agent-protocol';\nimport * as z from 'zod';\nimport { SandboxEntryType } from \"./file-kind.mjs\";\nexport { SandboxEntryType } from \"./file-kind.mjs\";\nimport { createSandboxHandle, type SandboxExecutionPolicyIface } from \"./handle.mjs\";\nimport { withSandboxOverrides } from \"./overrides.mjs\";\nimport { NetworkPolicy, type NetworkPolicyIface } from '@finalai/agent-protocol/network-policy';\nexport { NetworkPolicy, type NetworkPolicyIface } from '@finalai/agent-protocol/network-policy';\nimport type {\n ProcessInspectionRequestIface,\n ProcessInspectionResultIface,\n} from '@finalai/agent-protocol/process-inspection';\nimport type { JsonValue } from \"../json.mjs\";\nimport type { ToolDescriptorIface } from \"../tool-descriptor.mjs\";\nimport {\n SandboxEditorOperation,\n type SandboxEditorRequestIface,\n type SandboxEditorResultIface,\n} from \"./editor.mjs\";\nimport { SandboxExecutionOperation } from \"./execution-guard.mjs\";\nimport type { SandboxSetupIface } from \"./setup/schema.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 // Spawn only (`run` ignores it): ask for a durable process on a sandbox with\n // SandboxCapability.DurableProcesses; ignored elsewhere (the handle's `ref`\n // is then null). A durable process ends only on its own exit, `kill`,\n // `timeoutMs` (enforced inside the sandbox, not by a provider-side timer) or\n // sandbox stop/destroy. Dropping its handle (connection close, runtime\n // shutdown, `abortSignal`) detaches without killing: the handle's streams\n // fail and `wait` rejects, and `attachProcess` finds the process again.\n durable?: boolean;\n}\n\nexport interface SandboxProcessIface {\n readonly pid: string | null;\n // Opaque, provider-encoded (versioned) reference for `attachProcess`; non-null\n // only for a durable process on a sandbox with durable processes. Optional so\n // implementations without them need not set it.\n readonly ref?: 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\n// A program built for the sandbox's worker runtime, started for one harness\n// session. Its handle is a process's: what is written to it is its input\n// stream, stdout its output stream, stderr its diagnostics.\nexport interface SandboxWorkerOptionsIface extends AbortableIface {\n program: string;\n env?: Record<string, string>;\n // Handed to the program when it starts.\n input?: JsonValue;\n // As for spawn: survives the handle on a sandbox with durable processes.\n durable?: boolean;\n // A platform-identity assertion for the program's run (variant `harness-run`),\n // for a runtime that authenticates the programs it starts.\n identity?: string;\n}\n\nexport enum SandboxWorkerEndpointTransport {\n Ws = 'ws',\n Http = 'http',\n Relay = 'relay',\n}\n\n// Where a started worker program serves its stream itself, for the caller to\n// dial directly: an ACP endpoint by URL, or a relay channel.\nexport type SandboxWorkerEndpointType =\n | {\n transport: SandboxWorkerEndpointTransport.Ws | SandboxWorkerEndpointTransport.Http;\n url: string;\n headers: Record<string, string>;\n }\n | { transport: SandboxWorkerEndpointTransport.Relay; channel: string; token: string };\n\nexport interface SandboxWorkerEndpointIface {\n readonly endpoint: SandboxWorkerEndpointType;\n}\n\n// A started worker program: a process whose streams carry its stream, or an\n// endpoint it serves.\nexport type SandboxWorkerStartType = SandboxProcessIface | SandboxWorkerEndpointIface;\n\nexport const isSandboxWorkerEndpoint = (\n started: SandboxWorkerStartType,\n): started is SandboxWorkerEndpointIface => 'endpoint' in started;\n\nexport interface SandboxAttachProcessOptionsIface extends AbortableIface {\n ref: string;\n // Bytes of each stream the caller already has; output resumes there.\n stdoutOffset: number;\n stderrOffset: number;\n}\n\n// A durable process found again by its ref. Its output is read from the\n// provider, which is the source of truth for output and exit; aborting\n// `abortSignal` detaches this handle as it does a spawned durable one.\n//\n// Limitation: stdin belongs to the spawning handle only. A re-attached\n// process can be watched, waited for and killed, but not written to; a process\n// that needs input after a re-attach must read it from somewhere else (a file).\nexport interface SandboxAttachedProcessIface {\n readonly ref: string;\n // Where the streams actually start: the requested offsets, or later when the\n // provider no longer retains the earlier bytes (see each provider's retention).\n readonly stdoutOffset: number;\n readonly stderrOffset: number;\n readonly stdout: ReadableStream<Uint8Array>;\n readonly stderr: ReadableStream<Uint8Array>;\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 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 // Present on sandboxes with durable processes. Null when the process is\n // unknown: the sandbox restarted or was deleted, or the ref expired, is\n // malformed or belongs to another sandbox. Attaching after the process\n // exited still yields its retained output and exit code.\n attachProcess?(\n options: SandboxAttachProcessOptionsIface,\n ): Promise<SandboxAttachedProcessIface | null>;\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 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 host) 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 // Partial discovery retains known tools and must be retried, including after caching.\n localMcpIncomplete?: boolean;\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 // Present on sandboxes whose provider offers RuntimeKind.Worker.\n startWorker?(options: SandboxWorkerOptionsIface): Promise<SandboxWorkerStartType>;\n screen?(options?: ScreenOptionsIface): Promise<ScreenSessionIface>;\n localMcp?(): Promise<SandboxMcpEndpoint[]>;\n}\n\n// Features a live sandbox handle advertises over the handle RPC (`describe`).\n// Finer than the model's capabilities (`Capability`): `files` is served by the\n// file methods, `shell` by processes and ports, `computerUse` by computer use\n// and the screen; the rest are handle extensions a capability may use.\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 // `spawn({ durable: true })` and `attachProcess` (see SandboxProcessOptionsIface.durable).\n DurableProcesses = 'durableProcesses',\n // `startWorker`: the sandbox runs worker programs.\n Workers = 'workers',\n}\n\n// The capabilities a provider's sandboxes serve, each with the most access a\n// session can be granted on it. A capability left out is not served.\nexport type SandboxCapabilityOffer = Partial<Record<Capability, CapabilityAccess>>;\n\nexport interface SandboxProviderHandleIface<S extends SandboxSessionIface> {\n readonly sandbox: S;\n // Pending policy; the generic handle constructor consumes it before exposing execution.\n readonly executionPolicy?: SandboxExecutionPolicyIface;\n onSandboxStop(): Promise<void>;\n onSandboxDelete(options?: { reason?: string }): Promise<void>;\n onRuntimeShutdown(): Promise<void>;\n}\n\n// The person a sandbox acts for on this call: the author of the running turn,\n// else whoever opened the sandbox's viewer. Null when it acts for no person\n// (an unprompted turn, a preparation). Read on each call: it changes between\n// turns and between callers.\nexport interface SandboxActingUserIface {\n current(): Promise<string | null>;\n}\n\nexport const noSandboxActingUser: SandboxActingUserIface = { current: async () => null };\n\n// Credentials the host supplies to a provider. A provider reads no secrets of\n// its own and names no project: it gets the value of the secret its\n// environment's `credential.secretRef` names, resolved in the sandbox's project.\nexport interface SandboxCredentialsIface {\n secret(args: { secretRef: string }): Promise<string | null>;\n}\n\nexport const noSandboxCredentials: SandboxCredentialsIface = { secret: async () => null };\n\n// A provider's credential by reference, in its environment options: the name\n// of a project secret, never its value.\nexport const sandboxCredentialRefSchema = z.strictObject({\n secretRef: z.string().min(1).max(256),\n});\n\nexport type SandboxCredentialRefIface = z.infer<typeof sandboxCredentialRefSchema>;\n\n// A platform-identity assertion (`@finalai/agent-protocol/identity`) for one\n// backend audience, valid until `expiresAt`.\nexport interface SandboxIdentityTokenIface {\n token: string;\n expiresAt: string;\n}\n\n// How a provider authenticates to a backend it needs (its vendor's API): an\n// assertion for `audience`, which the platform issues only for audiences the\n// provider's registration was granted. It names the sandbox's organization,\n// project and sandbox, and the acting user at the time it was issued. Ask\n// before each backend call (hosts cache it); `refresh` asks for a new one\n// after the backend rejected the last.\nexport type SandboxIdentityFn = (args: {\n audience: string;\n refresh?: boolean;\n}) => Promise<SandboxIdentityTokenIface>;\n\nexport const noSandboxIdentity: SandboxIdentityFn = async ({ audience }) => {\n throw new Error(`no identity was granted for ${audience}`);\n};\n\n// What every provider call is given: the project the sandbox belongs to, the\n// host's credentials and the provider's identity for the backends it was\n// granted.\nexport interface SandboxProviderContextIface {\n organizationId: string;\n projectId: string;\n credentials: SandboxCredentialsIface;\n actingUser: SandboxActingUserIface;\n identity: SandboxIdentityFn;\n log?: (message: string, fields?: Record<string, string | number | boolean | null>) => void;\n}\n\n// How the platform runs a sandbox's lifecycle, for the provider to align its\n// backend with: after `parkAfterIdleMs` of idleness the platform parks the\n// sandbox (null: the provider's own default), so a backend idle timeout\n// should be longer.\nexport interface SandboxLifecycleIface {\n parkAfterIdleMs: number | null;\n}\n\n// What reads that start nothing are given (capabilities, catalogs, snapshots,\n// process inspection, the editor). `sandboxId` is set for reads about an\n// existing sandbox.\nexport interface SandboxOfferContextIface extends SandboxProviderContextIface {\n sandboxId?: string;\n executionPolicy?: SandboxExecutionPolicyIface;\n platformNetworkPolicy?: (policy: NetworkPolicyIface) => Promise<void>;\n // Retain platform transport access when an extension restores an allowlist.\n platformEgressHosts?: string[];\n}\n\n// Scoped by the host to this project and provider. Providers can retain\n// reusable intermediate artifacts independently of a sandbox'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\n// A preparation builds what an environment's sandboxes start from (an image\n// built into a base, a snapshot). It depends on the environment's options and\n// the seed files only, never on a sandbox setup.\nexport interface SandboxPrepareContextIface extends SandboxProviderContextIface {\n // A host-persisted resource source; artifacts may retain its identity instead of seed contents.\n preparation?: SandboxPreparationSourceIface;\n artifacts?: SandboxArtifactsIface;\n // Workspace-relative seed files and named resources.\n files: Record<string, string>;\n resources: Record<string, JsonValue>;\n sourceRevision: string;\n storagePath: string;\n}\n\n// What a provider is given for one sandbox: its create, attach, detach, park\n// and delete calls.\nexport interface SandboxResourceContextIface extends SandboxProviderContextIface {\n // The platform's id for the sandbox, stable for its whole life.\n sandboxId: string;\n lifecycle: SandboxLifecycleIface;\n // Host policy composes before the provider's policy, on every exposed execution path.\n executionPolicy?: SandboxExecutionPolicyIface;\n preparation?: SandboxPreparationSourceIface;\n storagePath: string;\n // Variables the platform sets in every process of this sandbox: the egress\n // proxy, trust for its CA, one placeholder per bound secret and the sandbox\n // setup's variables. Evaluated again for every spawn/run, never once per\n // attach: a secret bound later must reach the next command. May resolve to\n // {}. Platform values override the environment's own.\n platformEnvironment?: () => Promise<Record<string, string>>;\n // Hosts the sandbox must be able to reach for the proxy to work, appended\n // to any allowlist network policy.\n platformEgressHosts?: string[];\n // Reports the network policy now in force, exactly as the provider applied\n // it to its backend (after withPlatformEgressHosts); the platform permits\n // only those destinations. Called on every attach after awaitRunning and\n // before platformFiles or any command; never for a session's own\n // setNetworkPolicy. A rejection fails the attach.\n platformNetworkPolicy: (policy: NetworkPolicyIface) => Promise<void>;\n // Files the platform needs before any command runs: written right after the\n // sandbox is running, on every attach. Paths are absolute; missing parent\n // directories are created.\n platformFiles?: () => Promise<Record<string, string>>;\n}\n\n// The variables `platformEnvironment` owns. An environment that sets one is\n// refused at create.\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]);\n\n// A process's base environment: the environment's variables under the\n// platform's, read again on every call.\nexport const platformProcessEnvironment =\n (\n ctx: Pick<SandboxResourceContextIface, '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 is now running, before it runs anything.\n// Relies on writeTextFile creating missing parent directories.\nexport const writePlatformFiles = async (\n ctx: Pick<SandboxResourceContextIface, '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<SandboxResourceContextIface, '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<SandboxResourceContextIface, '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\n// One attach of a sandbox: the live handle, and what the attach lost, so the\n// platform knows which phases of the sandbox setup to redo.\nexport interface SandboxAttachmentIface<\n State extends JsonValue,\n S extends NetworkSandboxSessionIface,\n> {\n handle: SandboxProviderHandleIface<S>;\n // The state to keep for the next call (a resumed backend may change ids).\n state: State;\n // The disk is new: nothing written by a setup, the workspace seeds or a\n // session survives on it (first attach, or a backend that lost it).\n fresh: boolean;\n // The machine started on this attach: no process from before is running.\n booted: boolean;\n // Where the backend runs the sandbox (its own region name), so the host can\n // place the harness near it; null when unknown.\n region?: string | null;\n}\n\n// One environment of a provider, as the host drives it. A sandbox is a\n// resource the platform owns: `create` makes it (nothing need boot), `attach`\n// makes it reachable for a while, `detach` lets it go idle, `park` makes it as\n// cheap as the provider can while keeping its disk, `delete` destroys it.\n//\n// Order on attach: attach (boot or resume) \u2192 awaitRunning \u2192\n// platformNetworkPolicy \u2192 platformFiles \u2192 handle; the platform then applies\n// the sandbox setup through the handle (./setup). A provider never runs a\n// setup's steps itself.\nexport interface SandboxEnvironmentImplementationIface<\n Artifact extends JsonValue,\n State extends JsonValue,\n S extends NetworkSandboxSessionIface,\n> {\n // The capabilities this environment's sandboxes serve and the most access\n // each grants, known without creating one.\n capabilities(ctx: SandboxOfferContextIface): Promise<SandboxCapabilityOffer>;\n // What a harness can run in this environment's sandboxes: processes, worker\n // programs (`startWorker`), or both. Absent: processes when it offers `shell`.\n runtimes?(ctx: SandboxOfferContextIface): Promise<RuntimeKind[]>;\n // Handle features this environment's sandboxes advertise, read before\n // anything starts. Absent or null: unknown until attached; local MCP is then\n // not projected.\n features?(ctx: SandboxOfferContextIface): Promise<SandboxCapability[] | null>;\n // Known positive features when the rest of the pre-attach set is unknown.\n additionalFeatures?(ctx: SandboxOfferContextIface): Promise<SandboxCapability[]>;\n // The hosted MCP servers' tool catalogs the backend can give without\n // attaching, so the MCP projection lists them from the first `tools/list`.\n // A catalog left unknown can only be learned from a live sandbox, so the\n // first `tools/list` that finds it unknown attaches in the background.\n mcpCatalog?(ctx: SandboxOfferContextIface): Promise<SandboxMcpCatalogIface | null>;\n // Reads committed files without attaching. Null means the backend is live\n // or offers no snapshot. An unavailable sleeping snapshot must throw, never\n // fall through to a read that wakes it. Pin later ranges by snapshotId.\n readSnapshot?(\n ctx: SandboxOfferContextIface,\n state: State,\n request: SandboxSnapshotRequestIface,\n ): Promise<SandboxSnapshotResponseIface | null>;\n // Inspect retained backend processes without attaching or extending a sandbox.\n // Stopping one requires shell access; the provider also enforces backend ownership.\n processes?(\n ctx: SandboxOfferContextIface & { sandboxId: string },\n state: State,\n request: ProcessInspectionRequestIface,\n ): Promise<ProcessInspectionResultIface>;\n // Browser editor for an existing sandbox. 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 host caches artifacts and calls\n // prepare only on a miss.\n artifactKey(ctx: SandboxPrepareContextIface): Promise<string>;\n prepare(ctx: SandboxPrepareContextIface): Promise<Artifact>;\n // Makes the sandbox's backend resource. The setup is given so the\n // provider enforces its network policy from the first boot (or refuses);\n // its repositories, steps and services are applied by the platform.\n create(\n ctx: SandboxResourceContextIface,\n args: { artifact: Artifact; setup: SandboxSetupIface | null },\n ): Promise<{ state: State; region?: string | null }>;\n // Resolves once the backend named by `state` is running and will accept a\n // command or a file write; rejects with a clear error after `timeoutMs`.\n // The provider chooses the readiness signal and backoff; the platform never\n // polls a backend itself.\n awaitRunning(\n ctx: SandboxResourceContextIface,\n state: State,\n options: { timeoutMs: number },\n ): Promise<void>;\n // Boots or resumes the sandbox and returns a live handle.\n attach(\n ctx: SandboxResourceContextIface,\n args: { artifact: Artifact; state: State },\n ): Promise<SandboxAttachmentIface<State, S>>;\n // Reconnects to an already running backend for a read-only viewer: never\n // boots, creates, seeds or restarts anything. Absent: viewers use a live\n // handle or nothing.\n attachPassive?(\n ctx: SandboxResourceContextIface,\n args: { artifact: Artifact; state: State },\n ): Promise<SandboxProviderHandleIface<S>>;\n // The host is done with its handle for now; the sandbox may go idle on the\n // provider's own policy. Returns the state the next attach needs.\n detach(ctx: SandboxResourceContextIface, args: { state: State }): Promise<State>;\n // Pauses or stops the sandbox, keeping its disk. Returns the state the next attach needs.\n park(\n ctx: SandboxResourceContextIface,\n args: { artifact: Artifact; state: State },\n ): Promise<State>;\n // Destroys the backend resource and its disk. Deleting one already gone succeeds.\n delete(ctx: SandboxResourceContextIface, args: { state: State }): Promise<void>;\n}\n\nexport interface SandboxProviderDefinitionIface<\n EnvOptions,\n Artifact extends JsonValue,\n State extends JsonValue,\n S extends NetworkSandboxSessionIface,\n> {\n name: string;\n // The version of `State`'s shape. The host records it with each sandbox and\n // refuses to attach a state written under another version.\n stateProtocolVersion?: number;\n // Validates the options and returns the environment they describe.\n environment(options?: EnvOptions): SandboxEnvironmentImplementationIface<Artifact, State, S>;\n}\n\n// What `project.sandboxes.create(environment, \u2026)` takes: a provider by name\n// and that provider's own environment options, as plain data.\nexport interface SandboxEnvironmentValueIface<EnvOptions = JsonValue> {\n provider: string;\n environment: EnvOptions;\n}\n\n// A defined provider: the definition the host drives, and `environment(opts)`\n// returning the plain value a caller creates sandboxes from.\nexport interface SandboxProviderIface<\n EnvOptions,\n Artifact extends JsonValue,\n State extends JsonValue,\n S extends NetworkSandboxSessionIface,\n> {\n readonly definition: SandboxProviderDefinitionIface<EnvOptions, Artifact, State, S>;\n readonly name: string;\n environment(options: EnvOptions): SandboxEnvironmentValueIface<EnvOptions>;\n}\n\nexport const defineSandboxProvider = <\n EnvOptions,\n Artifact extends JsonValue,\n State extends JsonValue,\n S extends NetworkSandboxSessionIface,\n>(\n definition: SandboxProviderDefinitionIface<EnvOptions, Artifact, State, S>,\n): SandboxProviderIface<EnvOptions, Artifact, State, S> => ({\n definition: withSandboxOverrides(definition, {\n environment: (options?: EnvOptions) => {\n const implementation = definition.environment(options);\n for (const method of [\n 'create',\n 'attach',\n 'detach',\n 'park',\n 'delete',\n 'awaitRunning',\n ] as const)\n if (typeof implementation[method] !== 'function')\n throw new Error(`sandbox provider ${definition.name} does not implement ${method}`);\n const overrides: Partial<typeof implementation> = {\n attach: async (ctx, args) => {\n const attached = await implementation.attach(ctx, args);\n return {\n ...attached,\n handle: createSandboxHandle({\n handle: attached.handle,\n executionPolicy: ctx.executionPolicy,\n }),\n };\n },\n };\n if (implementation.editor != null) {\n const editor = implementation.editor.bind(implementation);\n overrides.editor = async (ctx, state, request) => {\n if (\n request.operation === SandboxEditorOperation.Open ||\n request.operation === SandboxEditorOperation.Refresh\n )\n await ctx.executionPolicy?.beforeExecution({\n operation: SandboxExecutionOperation.Editor,\n background: false,\n });\n return editor(ctx, state, request);\n };\n }\n if (implementation.attachPassive != null) {\n const attachPassive = implementation.attachPassive.bind(implementation);\n overrides.attachPassive = async (ctx, args) =>\n createSandboxHandle({\n handle: await attachPassive(ctx, args),\n executionPolicy: ctx.executionPolicy,\n });\n }\n return withSandboxOverrides(implementation, overrides);\n },\n }),\n name: definition.name,\n environment: (options) => ({ provider: definition.name, environment: options }),\n});\n\n// The runtime kinds an environment declares, or its default.\nexport const sandboxRuntimesOf = async (\n environment: Pick<\n SandboxEnvironmentImplementationIface<JsonValue, JsonValue, NetworkSandboxSessionIface>,\n 'capabilities' | 'runtimes'\n >,\n ctx: SandboxOfferContextIface,\n): Promise<RuntimeKind[]> => {\n if (environment.runtimes != null) return environment.runtimes(ctx);\n const offer = await environment.capabilities(ctx);\n return offer[Capability.Shell] == null ? [] : [RuntimeKind.Process];\n};\n\n// Erased form a host stores in its provider registry.\nexport type AnySandboxProviderIface = SandboxProviderIface<\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": "AAAA,SAAS,YAAY,mBAA0C;AAC/D,YAAY,OAAO;AACnB,SAAS,wBAAwB;AACjC,SAAS,oBAAAA,yBAAwB;AACjC,SAAS,2BAA6D;AACtE,SAAS,4BAA4B;AACrC,SAAS,qBAA8C;AACvD,SAAS,iBAAAC,sBAA8C;AAOvD;AAAA,EACE;AAAA,OAGK;AACP,SAAS,iCAAiC;AA0DnC,IAAK,iCAAL,kBAAKC,oCAAL;AACL,EAAAA,gCAAA,QAAK;AACL,EAAAA,gCAAA,UAAO;AACP,EAAAA,gCAAA,WAAQ;AAHE,SAAAA;AAAA,GAAA;AAwBL,MAAM,0BAA0B,CACrC,YAC0C,cAAc;AAqGnD,IAAK,eAAL,kBAAKC,kBAAL;AACL,EAAAA,cAAA,UAAO;AACP,EAAAA,cAAA,WAAQ;AACR,EAAAA,cAAA,QAAK;AAHK,SAAAA;AAAA,GAAA;AA2CL,MAAM,uBAAuB,CAClC,aACwC,aAAa;AAqChD,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,mBAAA,YAAS;AACT,EAAAA,mBAAA,cAAW;AACX,EAAAA,mBAAA,aAAU;AAEV,EAAAA,mBAAA,sBAAmB;AAEnB,EAAAA,mBAAA,aAAU;AAZA,SAAAA;AAAA,GAAA;AAoCL,MAAM,sBAA8C,EAAE,SAAS,YAAY,KAAK;AAShF,MAAM,uBAAgD,EAAE,QAAQ,YAAY,KAAK;AAIjF,MAA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AoB,OAC/B,aAIA,QAC2B;AAC3B,MAAI,YAAY,YAAY,KAAM,QAAO,YAAY,SAAS,GAAG;AACjE,QAAM,QAAQ,MAAM,YAAY,aAAa,GAAG;AAChD,SAAO,MAAM,WAAW,KAAK,KAAK,OAAO,CAAC,IAAI,CAAC,YAAY,OAAO;AACpE;AAWO,IAAK,mBAAL,kBAAKC,sBAAL;AACL,EAAAA,kBAAA,mBAAgB;AADN,SAAAA;AAAA,GAAA;",
6
+ "names": ["SandboxEntryType", "NetworkPolicy", "SandboxWorkerEndpointTransport", "PortProtocol", "SandboxCapability", "SandboxEventKind"]
7
7
  }
@@ -1,6 +1,5 @@
1
1
  export { statSchema, dirEntrySchema } from "./file-schemas.mjs";
2
2
  import * as z from 'zod';
3
- import { workspaceEgressRequestSchema, workspaceEgressStatusSchema } from '@finalai/agent-protocol/device-egress';
4
3
  import { type JsonValue } from "../json.mjs";
5
4
  import { NetworkPolicy, PortProtocol, SandboxCapability, SandboxWorkerEndpointTransport } from "./types.mjs";
6
5
  export declare const HANDLE_RPC_VERSION = 1;
@@ -50,7 +49,6 @@ export declare enum HandleRpcMethod {
50
49
  Stop = "sandbox/stop",
51
50
  Destroy = "sandbox/destroy",
52
51
  SetNetworkPolicy = "sandbox/setNetworkPolicy",
53
- Egress = "sandbox/egress",
54
52
  OnSandboxStop = "handle/onSandboxStop",
55
53
  OnSandboxDelete = "handle/onSandboxDelete",
56
54
  OnRuntimeShutdown = "handle/onRuntimeShutdown",
@@ -624,20 +622,6 @@ export declare const handleRpcMethodSchemas: {
624
622
  }, z.core.$strip>;
625
623
  readonly result: z.ZodObject<{}, z.core.$loose>;
626
624
  };
627
- readonly "sandbox/egress": {
628
- readonly params: z.ZodObject<{
629
- action: z.ZodEnum<typeof import("@finalai/agent-protocol").WorkspaceEgressAction>;
630
- deviceIds: z.ZodOptional<z.ZodArray<z.ZodPipe<z.ZodUUID, z.ZodTransform<string, string>>>>;
631
- dnsResolvers: z.ZodOptional<z.ZodArray<z.ZodIPv4>>;
632
- }, z.core.$strip>;
633
- readonly result: z.ZodObject<{
634
- mode: z.ZodString;
635
- leaseId: z.ZodNullable<z.ZodPipe<z.ZodString, z.ZodTransform<string, string>>>;
636
- expiresAtMs: z.ZodNullable<z.ZodNumber>;
637
- deviceId: z.ZodNullable<z.ZodString>;
638
- path: z.ZodNullable<z.ZodString>;
639
- }, z.core.$strip>;
640
- };
641
625
  readonly "sandbox/computerUse": {
642
626
  readonly params: z.ZodObject<{}, z.core.$loose>;
643
627
  readonly result: z.ZodUnion<readonly [z.ZodObject<{
@@ -800,4 +784,3 @@ export declare const encodeJsonRpc: (message: JsonValue) => string;
800
784
  export declare const handleRpcTokenFromRequest: (request: Request) => string | null;
801
785
  export declare const handleRpcClientProtocols: (token: string) => string[];
802
786
  export * from "./frame-channel.mjs";
803
- export { workspaceEgressRequestSchema, workspaceEgressStatusSchema };