@finalai/agent-provider 0.9.0 → 0.10.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 (200) hide show
  1. package/HOSTING.md +334 -245
  2. package/README.md +93 -14
  3. package/dist/modules/canonical-json.d.mts +4 -0
  4. package/dist/modules/canonical-json.mjs +33 -0
  5. package/dist/modules/canonical-json.mjs.map +7 -0
  6. package/dist/modules/channel.d.mts +0 -3
  7. package/dist/modules/channel.mjs.map +1 -1
  8. package/dist/modules/code-host/host.d.mts +10 -0
  9. package/dist/modules/code-host/host.mjs +88 -0
  10. package/dist/modules/code-host/host.mjs.map +7 -0
  11. package/dist/modules/code-host/in-process.d.mts +24 -0
  12. package/dist/modules/code-host/in-process.mjs +89 -0
  13. package/dist/modules/code-host/in-process.mjs.map +7 -0
  14. package/dist/modules/code-host/index.d.mts +4 -0
  15. package/dist/modules/code-host/index.mjs +5 -0
  16. package/dist/modules/code-host/index.mjs.map +7 -0
  17. package/dist/modules/code-host/serverless.d.mts +63 -0
  18. package/dist/modules/code-host/serverless.mjs +27 -0
  19. package/dist/modules/code-host/serverless.mjs.map +7 -0
  20. package/dist/modules/code-host/types.d.mts +152 -0
  21. package/dist/modules/code-host/types.mjs +85 -0
  22. package/dist/modules/code-host/types.mjs.map +7 -0
  23. package/dist/modules/conformance/agent.mjs +72 -6
  24. package/dist/modules/conformance/agent.mjs.map +2 -2
  25. package/dist/modules/conformance/harness-kit.d.mts +9 -2
  26. package/dist/modules/conformance/harness-kit.mjs +224 -63
  27. package/dist/modules/conformance/harness-kit.mjs.map +3 -3
  28. package/dist/modules/conformance/local-harness.d.mts +1 -4
  29. package/dist/modules/conformance/local-harness.mjs +21 -22
  30. package/dist/modules/conformance/local-harness.mjs.map +2 -2
  31. package/dist/modules/conformance/protocol.d.mts +1 -0
  32. package/dist/modules/conformance/protocol.mjs +2 -0
  33. package/dist/modules/conformance/protocol.mjs.map +2 -2
  34. package/dist/modules/conformance/sandbox-kit.d.mts +12 -4
  35. package/dist/modules/conformance/sandbox-kit.mjs +189 -103
  36. package/dist/modules/conformance/sandbox-kit.mjs.map +2 -2
  37. package/dist/modules/conformance/scripted-model/chat-completions.mjs +1 -0
  38. package/dist/modules/conformance/scripted-model/chat-completions.mjs.map +2 -2
  39. package/dist/modules/conformance/scripted-model/directives.d.mts +3 -0
  40. package/dist/modules/conformance/scripted-model/directives.mjs +26 -10
  41. package/dist/modules/conformance/scripted-model/directives.mjs.map +2 -2
  42. package/dist/modules/conformance/scripted-model/messages.mjs +1 -0
  43. package/dist/modules/conformance/scripted-model/messages.mjs.map +2 -2
  44. package/dist/modules/conformance/scripted-model/responses.mjs +2 -0
  45. package/dist/modules/conformance/scripted-model/responses.mjs.map +2 -2
  46. package/dist/modules/conformance/stdio.d.mts +21 -0
  47. package/dist/modules/conformance/stdio.mjs +158 -0
  48. package/dist/modules/conformance/stdio.mjs.map +7 -0
  49. package/dist/modules/credential-routes.d.mts +2 -0
  50. package/dist/modules/credential-routes.mjs +2 -0
  51. package/dist/modules/credential-routes.mjs.map +2 -2
  52. package/dist/modules/document.d.mts +376 -0
  53. package/dist/modules/document.mjs +208 -0
  54. package/dist/modules/document.mjs.map +7 -0
  55. package/dist/modules/harness-configuration.d.mts +16 -0
  56. package/dist/modules/harness-configuration.mjs +83 -0
  57. package/dist/modules/harness-configuration.mjs.map +7 -0
  58. package/dist/modules/harness-definition.d.mts +280 -0
  59. package/dist/modules/harness-definition.mjs +430 -0
  60. package/dist/modules/harness-definition.mjs.map +7 -0
  61. package/dist/modules/harness-provider.d.mts +197 -0
  62. package/dist/modules/harness-provider.mjs +108 -0
  63. package/dist/modules/harness-provider.mjs.map +7 -0
  64. package/dist/modules/harness-requirements.d.mts +19 -0
  65. package/dist/modules/harness-requirements.mjs +40 -0
  66. package/dist/modules/harness-requirements.mjs.map +7 -0
  67. package/dist/modules/harness-start.d.mts +33 -0
  68. package/dist/modules/harness-start.mjs +107 -0
  69. package/dist/modules/harness-start.mjs.map +7 -0
  70. package/dist/modules/harness.d.mts +84 -109
  71. package/dist/modules/harness.mjs +56 -111
  72. package/dist/modules/harness.mjs.map +3 -3
  73. package/dist/modules/identity.d.mts +1 -0
  74. package/dist/modules/identity.mjs +2 -0
  75. package/dist/modules/identity.mjs.map +7 -0
  76. package/dist/modules/index.d.mts +12 -6
  77. package/dist/modules/index.mjs +12 -6
  78. package/dist/modules/index.mjs.map +2 -2
  79. package/dist/modules/inference.d.mts +35 -0
  80. package/dist/modules/inference.mjs +74 -0
  81. package/dist/modules/inference.mjs.map +7 -0
  82. package/dist/modules/local-channel-context.mjs +1 -1
  83. package/dist/modules/local-channel-context.mjs.map +2 -2
  84. package/dist/modules/requirements-check.d.mts +30 -0
  85. package/dist/modules/requirements-check.mjs +164 -0
  86. package/dist/modules/requirements-check.mjs.map +7 -0
  87. package/dist/modules/room-surface.d.mts +0 -5
  88. package/dist/modules/room-surface.mjs.map +2 -2
  89. package/dist/modules/sandbox/client.d.mts +3 -0
  90. package/dist/modules/sandbox/client.mjs +101 -18
  91. package/dist/modules/sandbox/client.mjs.map +2 -2
  92. package/dist/modules/sandbox/grant.d.mts +78 -0
  93. package/dist/modules/sandbox/grant.mjs +134 -0
  94. package/dist/modules/sandbox/grant.mjs.map +7 -0
  95. package/dist/modules/sandbox/index.d.mts +3 -3
  96. package/dist/modules/sandbox/index.mjs +4 -5
  97. package/dist/modules/sandbox/index.mjs.map +2 -2
  98. package/dist/modules/sandbox/mcp-hosted.d.mts +1 -1
  99. package/dist/modules/sandbox/mcp-hosted.mjs +4 -7
  100. package/dist/modules/sandbox/mcp-hosted.mjs.map +2 -2
  101. package/dist/modules/sandbox/mcp.d.mts +4 -2
  102. package/dist/modules/sandbox/mcp.mjs +14 -7
  103. package/dist/modules/sandbox/mcp.mjs.map +2 -2
  104. package/dist/modules/sandbox/memory-sandbox.d.mts +2 -1
  105. package/dist/modules/sandbox/memory-sandbox.mjs +71 -41
  106. package/dist/modules/sandbox/memory-sandbox.mjs.map +2 -2
  107. package/dist/modules/sandbox/networking.d.mts +7 -7
  108. package/dist/modules/sandbox/networking.mjs +16 -9
  109. package/dist/modules/sandbox/networking.mjs.map +2 -2
  110. package/dist/modules/sandbox/remote/adapter.d.mts +30 -0
  111. package/dist/modules/sandbox/remote/adapter.mjs +381 -0
  112. package/dist/modules/sandbox/remote/adapter.mjs.map +7 -0
  113. package/dist/modules/sandbox/remote/errors.d.mts +10 -0
  114. package/dist/modules/sandbox/remote/errors.mjs +62 -0
  115. package/dist/modules/sandbox/remote/errors.mjs.map +7 -0
  116. package/dist/modules/sandbox/remote/index.d.mts +5 -0
  117. package/dist/modules/sandbox/remote/index.mjs +6 -0
  118. package/dist/modules/sandbox/remote/index.mjs.map +7 -0
  119. package/dist/modules/sandbox/remote/ndjson.d.mts +6 -0
  120. package/dist/modules/sandbox/remote/ndjson.mjs +80 -0
  121. package/dist/modules/sandbox/remote/ndjson.mjs.map +7 -0
  122. package/dist/modules/sandbox/remote/platform-api.d.mts +8 -0
  123. package/dist/modules/sandbox/remote/platform-api.mjs +15 -0
  124. package/dist/modules/sandbox/remote/platform-api.mjs.map +7 -0
  125. package/dist/modules/sandbox/remote/preamble.d.mts +7 -0
  126. package/dist/modules/sandbox/remote/preamble.mjs +51 -0
  127. package/dist/modules/sandbox/remote/preamble.mjs.map +7 -0
  128. package/dist/modules/sandbox/remote/serve.d.mts +34 -0
  129. package/dist/modules/sandbox/remote/serve.mjs +519 -0
  130. package/dist/modules/sandbox/remote/serve.mjs.map +7 -0
  131. package/dist/modules/sandbox/remote/testing.d.mts +34 -0
  132. package/dist/modules/sandbox/remote/testing.mjs +275 -0
  133. package/dist/modules/sandbox/remote/testing.mjs.map +7 -0
  134. package/dist/modules/sandbox/seeds.d.mts +2 -2
  135. package/dist/modules/sandbox/seeds.mjs +2 -2
  136. package/dist/modules/sandbox/seeds.mjs.map +2 -2
  137. package/dist/modules/sandbox/server.d.mts +4 -6
  138. package/dist/modules/sandbox/server.mjs +93 -49
  139. package/dist/modules/sandbox/server.mjs.map +2 -2
  140. package/dist/modules/sandbox/setup/apply.d.mts +41 -0
  141. package/dist/modules/sandbox/setup/apply.mjs +204 -0
  142. package/dist/modules/sandbox/setup/apply.mjs.map +7 -0
  143. package/dist/modules/sandbox/setup/describe.d.mts +10 -0
  144. package/dist/modules/sandbox/setup/describe.mjs +62 -0
  145. package/dist/modules/sandbox/setup/describe.mjs.map +7 -0
  146. package/dist/modules/sandbox/setup/index.d.mts +6 -0
  147. package/dist/modules/sandbox/setup/index.mjs +17 -0
  148. package/dist/modules/sandbox/setup/index.mjs.map +7 -0
  149. package/dist/modules/sandbox/setup/paths.d.mts +8 -0
  150. package/dist/modules/sandbox/setup/paths.mjs +18 -0
  151. package/dist/modules/sandbox/setup/paths.mjs.map +7 -0
  152. package/dist/modules/sandbox/setup/schema.d.mts +42 -0
  153. package/dist/modules/sandbox/setup/schema.mjs +58 -0
  154. package/dist/modules/sandbox/setup/schema.mjs.map +7 -0
  155. package/dist/modules/sandbox/tool-policy.d.mts +1 -1
  156. package/dist/modules/sandbox/tool-policy.mjs +1 -1
  157. package/dist/modules/sandbox/tool-policy.mjs.map +2 -2
  158. package/dist/modules/sandbox/types.d.mts +117 -130
  159. package/dist/modules/sandbox/types.mjs +46 -50
  160. package/dist/modules/sandbox/types.mjs.map +3 -3
  161. package/dist/modules/sandbox/wire.d.mts +93 -6
  162. package/dist/modules/sandbox/wire.mjs +61 -38
  163. package/dist/modules/sandbox/wire.mjs.map +2 -2
  164. package/dist/modules/schemas.d.mts +5 -76
  165. package/dist/modules/schemas.mjs +18 -85
  166. package/dist/modules/schemas.mjs.map +2 -2
  167. package/dist/modules/tool-annotations.d.mts +15 -6
  168. package/dist/modules/tool-annotations.mjs +9 -3
  169. package/dist/modules/tool-annotations.mjs.map +2 -2
  170. package/dist/modules/tool-descriptor.d.mts +16 -0
  171. package/dist/modules/tool-descriptor.mjs +19 -0
  172. package/dist/modules/tool-descriptor.mjs.map +7 -0
  173. package/dist/modules/tool-patterns.d.mts +7 -7
  174. package/dist/modules/tool-patterns.mjs +10 -9
  175. package/dist/modules/tool-patterns.mjs.map +2 -2
  176. package/package.json +86 -36
  177. package/dist/modules/credentials.d.mts +0 -206
  178. package/dist/modules/credentials.mjs +0 -207
  179. package/dist/modules/credentials.mjs.map +0 -7
  180. package/dist/modules/dynamic.d.mts +0 -40
  181. package/dist/modules/dynamic.mjs +0 -79
  182. package/dist/modules/dynamic.mjs.map +0 -7
  183. package/dist/modules/hosted-bindings.d.mts +0 -15
  184. package/dist/modules/hosted-bindings.mjs +0 -21
  185. package/dist/modules/hosted-bindings.mjs.map +0 -7
  186. package/dist/modules/manifest.d.mts +0 -791
  187. package/dist/modules/manifest.mjs +0 -322
  188. package/dist/modules/manifest.mjs.map +0 -7
  189. package/dist/modules/provider-ref.d.mts +0 -29
  190. package/dist/modules/provider-ref.mjs +0 -55
  191. package/dist/modules/provider-ref.mjs.map +0 -7
  192. package/dist/modules/sandbox/open-scope-node.d.mts +0 -4
  193. package/dist/modules/sandbox/open-scope-node.mjs +0 -19
  194. package/dist/modules/sandbox/open-scope-node.mjs.map +0 -7
  195. package/dist/modules/sandbox/open-scope.d.mts +0 -16
  196. package/dist/modules/sandbox/open-scope.mjs +0 -66
  197. package/dist/modules/sandbox/open-scope.mjs.map +0 -7
  198. package/dist/modules/sandbox/workspace-identity.d.mts +0 -5
  199. package/dist/modules/sandbox/workspace-identity.mjs +0 -14
  200. package/dist/modules/sandbox/workspace-identity.mjs.map +0 -7
@@ -0,0 +1,204 @@
1
+ import * as z from "zod";
2
+ import { contentHash } from "../../canonical-json.mjs";
3
+ import { jsonValueSchema } from "../../json.mjs";
4
+ import { describeSandbox, SANDBOX_DESCRIPTION_PATH } from "./describe.mjs";
5
+ import { checkoutPath, commandPath, commandsDirectory, setupPath, setupRoot } from "./paths.mjs";
6
+ const SETUP_STEP_TIMEOUT_MS = 20 * 6e4;
7
+ var SandboxSetupPhase = /* @__PURE__ */ ((SandboxSetupPhase2) => {
8
+ SandboxSetupPhase2["Checkout"] = "checkout";
9
+ SandboxSetupPhase2["Commands"] = "commands";
10
+ SandboxSetupPhase2["Steps"] = "steps";
11
+ return SandboxSetupPhase2;
12
+ })(SandboxSetupPhase || {});
13
+ const sandboxSetupStateSchema = z.object({
14
+ // contentHash of the setup the recorded phases belong to.
15
+ setup: z.string(),
16
+ // Disk phases finished: they survive until the disk is replaced.
17
+ done: z.array(z.nativeEnum(SandboxSetupPhase)).default([]),
18
+ // Steps finished so far, in order; a retry resumes after them.
19
+ steps: z.number().int().nonnegative().default(0),
20
+ // Services started on the current boot.
21
+ services: z.array(z.string()).default([])
22
+ });
23
+ const shellQuote = (value) => `'${value.replaceAll("'", "'\\''")}'`;
24
+ const scrubber = (secrets) => (text) => secrets.reduce(
25
+ (scrubbed, secret) => secret.length < 4 ? scrubbed : scrubbed.replaceAll(secret, "****"),
26
+ text
27
+ );
28
+ const setupHash = (setup) => contentHash(jsonValueSchema.parse(JSON.parse(JSON.stringify(setup))));
29
+ const resolveEnvironment = async (setup, secrets) => {
30
+ const environment = {};
31
+ const secretValues = [];
32
+ for (const [name, variable] of Object.entries(setup.variables)) {
33
+ if ("value" in variable) {
34
+ environment[name] = variable.value;
35
+ continue;
36
+ }
37
+ const value = await secrets.get(variable.secret);
38
+ if (value == null)
39
+ throw new Error(
40
+ `variable ${name} needs the project secret ${variable.secret}, which is not set`
41
+ );
42
+ environment[name] = value;
43
+ secretValues.push(value);
44
+ }
45
+ return { environment, secretValues };
46
+ };
47
+ const isGitUrl = (value) => /^(https?:\/\/|ssh:\/\/|git@)/.test(value);
48
+ const commandScript = (args) => [
49
+ "#!/bin/bash",
50
+ "set -eu",
51
+ `cd -- ${shellQuote(args.cwd)}`,
52
+ `exec bash -c ${shellQuote(args.run)} ${shellQuote(args.name)} "$@"`,
53
+ ""
54
+ ].join("\n");
55
+ const applySandboxSetup = async (args) => {
56
+ const { handle, setup } = args;
57
+ const log = args.log ?? (() => void 0);
58
+ const hash = await setupHash(setup);
59
+ const { environment, secretValues } = await resolveEnvironment(setup, args.secrets);
60
+ const scrub = scrubber(secretValues);
61
+ const root = setupRoot(handle);
62
+ const recorded = args.state != null && args.state.setup === hash && !args.attachment.fresh ? args.state : null;
63
+ let state = {
64
+ setup: hash,
65
+ done: recorded?.done ?? [],
66
+ steps: recorded?.steps ?? 0,
67
+ // A boot (or a new disk) stops every process: services start again.
68
+ services: recorded == null || args.attachment.booted ? [] : recorded.services
69
+ };
70
+ const save = async (next) => {
71
+ state = next;
72
+ await args.saveState?.(next);
73
+ };
74
+ const finish = (phase) => save({ ...state, done: state.done.includes(phase) ? state.done : [...state.done, phase] });
75
+ const runOrThrow = async (label, options) => {
76
+ const result = await handle.run(options);
77
+ if (result.exitCode !== 0)
78
+ throw new Error(
79
+ `${label} failed (exit ${result.exitCode}): ${scrub(result.stderr.trim()).slice(-2e3)}`
80
+ );
81
+ return result;
82
+ };
83
+ const requireDirectory = async (label, cwd) => {
84
+ const path = setupPath(handle, cwd);
85
+ if (await handle.stat({ path }) == null)
86
+ throw new Error(`${label} runs in ${path}, which does not exist`);
87
+ return path;
88
+ };
89
+ if (!state.done.includes("checkout" /* Checkout */)) {
90
+ for (const repository of setup.repositories) {
91
+ const destination = checkoutPath(handle, repository.alias);
92
+ const ref = repository.ref ?? null;
93
+ const cloned = await handle.stat({ path: `${destination}/.git` }) != null;
94
+ 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
+ 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`
109
+ ].join("; ");
110
+ if (cloned && checkout == null) continue;
111
+ log("sandbox_setup.checkout", { alias: repository.alias });
112
+ const redact = scrubber(
113
+ source.authorization == null ? secretValues : [...secretValues, source.authorization]
114
+ );
115
+ const result = await handle.run({
116
+ command: [
117
+ "set -eu",
118
+ ...cloned ? [] : [
119
+ `mkdir -p ${shellQuote(root)}`,
120
+ `git clone --quiet -- ${shellQuote(source.url)} ${shellQuote(destination)}`
121
+ ],
122
+ ...checkout == null ? [] : [checkout]
123
+ ].join("; "),
124
+ shell: true,
125
+ // Paths are absolute; a sandbox may refuse `/` as outside it.
126
+ cwd: root,
127
+ env: { GIT_TERMINAL_PROMPT: "0", ...credential },
128
+ timeoutMs: SETUP_STEP_TIMEOUT_MS
129
+ });
130
+ if (result.exitCode !== 0)
131
+ throw new Error(
132
+ `checkout of ${repository.alias} failed (exit ${result.exitCode}): ${redact(result.stderr.trim()).slice(-2e3)}`
133
+ );
134
+ }
135
+ await finish("checkout" /* Checkout */);
136
+ }
137
+ if (!state.done.includes("commands" /* Commands */)) {
138
+ const names = Object.keys(setup.commands);
139
+ for (const [name, command] of Object.entries(setup.commands))
140
+ await handle.writeTextFile({
141
+ path: commandPath(handle, name),
142
+ content: commandScript({ name, cwd: setupPath(handle, command.cwd), run: command.run })
143
+ });
144
+ if (names.length > 0)
145
+ await runOrThrow("installing commands", {
146
+ command: `chmod 0755 ${names.map((name) => shellQuote(commandPath(handle, name))).join(" ")}`,
147
+ shell: true,
148
+ cwd: root,
149
+ timeoutMs: 6e4
150
+ });
151
+ await finish("commands" /* Commands */);
152
+ }
153
+ if (!state.done.includes("steps" /* Steps */)) {
154
+ for (const [index, step] of setup.steps.entries()) {
155
+ if (index < state.steps) continue;
156
+ const label = `setup step ${index + 1}${step.name == null ? "" : ` (${step.name})`}`;
157
+ log("sandbox_setup.step", { index });
158
+ const run = async () => runOrThrow(label, {
159
+ command: `set -eu
160
+ ${step.run}`,
161
+ shell: true,
162
+ cwd: await requireDirectory(label, step.cwd),
163
+ env: environment,
164
+ timeoutMs: step.timeoutSeconds == null ? SETUP_STEP_TIMEOUT_MS : step.timeoutSeconds * 1e3
165
+ });
166
+ if (step.optional === true)
167
+ await run().catch(() => log("sandbox_setup.optional_step_failed", { index }));
168
+ else await run();
169
+ await save({ ...state, steps: index + 1 });
170
+ }
171
+ await finish("steps" /* Steps */);
172
+ }
173
+ const startService = async (service) => {
174
+ const label = `service ${service.name}`;
175
+ const logFile = `${root}/.final/services/${service.name}.log`;
176
+ await runOrThrow(`starting ${label}`, {
177
+ command: `mkdir -p ${shellQuote(`${root}/.final/services`)} && nohup bash -lc ${shellQuote(service.run)} >${shellQuote(logFile)} 2>&1 </dev/null &`,
178
+ shell: true,
179
+ cwd: await requireDirectory(label, service.cwd),
180
+ env: environment,
181
+ timeoutMs: 6e4
182
+ });
183
+ log("sandbox_setup.service_started", { service: service.name });
184
+ };
185
+ for (const service of setup.services) {
186
+ if (state.services.includes(service.name)) continue;
187
+ await startService(service);
188
+ await save({ ...state, services: [...state.services, service.name] });
189
+ }
190
+ const description = await describeSandbox({ handle, setup, sandboxId: args.sandboxId });
191
+ await handle.writeTextFile({
192
+ path: setupPath(handle, SANDBOX_DESCRIPTION_PATH),
193
+ content: description.markdown
194
+ });
195
+ return { state, environment, commandsDirectory: commandsDirectory(handle) };
196
+ };
197
+ export {
198
+ SETUP_STEP_TIMEOUT_MS,
199
+ SandboxSetupPhase,
200
+ applySandboxSetup,
201
+ sandboxSetupStateSchema,
202
+ setupHash
203
+ };
204
+ //# sourceMappingURL=apply.mjs.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 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,MAAM,WAAW,KAAK,OAAO,CAAC;AAGhF,MAAM,WACJ,CAAC,YACD,CAAC,SACC,QAAQ;AAAA,EACN,CAAC,UAAU,WAAY,OAAO,SAAS,IAAI,WAAW,SAAS,WAAW,QAAQ,MAAM;AAAA,EACxF;AACF;AAGG,MAAM,YAAY,CAAC,UACxB,YAAY,gBAAgB,MAAM,KAAK,MAAM,KAAK,UAAU,KAAK,CAAC,CAAC,CAAC;AAEtE,MAAM,qBAAqB,OACzB,OACA,YAC6E;AAC7E,QAAM,cAAsC,CAAC;AAC7C,QAAM,eAAyB,CAAC;AAChC,aAAW,CAAC,MAAM,QAAQ,KAAK,OAAO,QAAQ,MAAM,SAAS,GAAG;AA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AE,CAAC;AAAA,IAC3C;AACA,UAAM,OAAO,mBAAuB;AAAA,EACtC;AAEA,QAAM,eAAe,OAAO,YAA8C;AACxE,UAAM,QAAQ,WAAW,QAAQ,IAAI;AACrC,UAAM,UAAU,GAAG,IAAI,oBAAoB,QAAQ,IAAI;AAEvD,UAAM,WAAW,YAAY,KAAK,IAAI;AAAA,MACpC,SAAS,YAAY,WAAW,GAAG,IAAI,kBAAkB,CAAC,sBAAsB,WAAW,QAAQ,GAAG,CAAC,KAAK,WAAW,OAAO,CAAC;AAAA,MAC/H,OAAO;AAAA,MACP,KAAK,MAAM,iBAAiB,OAAO,QAAQ,GAAG;AAAA,MAC9C,KAAK;AAAA,MACL,WAAW;AAAA,IACb,CAAC;AACD,QAAI,iCAAiC,EAAE,SAAS,QAAQ,KAAK,CAAC;AAAA,EAChE;AAGA,aAAW,WAAW,MAAM,UAAU;AACpC,QAAI,MAAM,SAAS,SAAS,QAAQ,IAAI,EAAG;AAC3C,UAAM,aAAa,OAAO;AAC1B,UAAM,KAAK,EAAE,GAAG,OAAO,UAAU,CAAC,GAAG,MAAM,UAAU,QAAQ,IAAI,EAAE,CAAC;AAAA,EACtE;AAEA,QAAM,cAAc,MAAM,gBAAgB,EAAE,QAAQ,OAAO,WAAW,KAAK,UAAU,CAAC;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;",
6
+ "names": ["SandboxSetupPhase"]
7
+ }
@@ -0,0 +1,10 @@
1
+ import type { SandboxDescriptionIface } from '@finalai/agent-protocol/agent-platform';
2
+ import type { NetworkSandboxSessionIface } from "../types.mjs";
3
+ import type { SandboxSetupIface } from "./schema.mjs";
4
+ export type { SandboxDescriptionIface } from '@finalai/agent-protocol/agent-platform';
5
+ export declare const SANDBOX_DESCRIPTION_PATH = ".final/sandbox.md";
6
+ export declare const describeSandbox: (args: {
7
+ handle: Pick<NetworkSandboxSessionIface, "defaultWorkingDirectory" | "getPortUrl">;
8
+ setup: SandboxSetupIface | null;
9
+ sandboxId: string;
10
+ }) => Promise<SandboxDescriptionIface>;
@@ -0,0 +1,62 @@
1
+ import { checkoutPath, setupRoot } from "./paths.mjs";
2
+ const SANDBOX_DESCRIPTION_PATH = ".final/sandbox.md";
3
+ const renderMarkdown = (description, commandDescriptions) => {
4
+ const lines = ["# This sandbox"];
5
+ if (description.workspace != null)
6
+ lines.push("", `Working directory: \`${description.workspace}\``);
7
+ if (description.checkouts.length > 0) {
8
+ lines.push("", "## Repositories", "");
9
+ for (const checkout of description.checkouts)
10
+ lines.push(
11
+ `- \`${checkout.path}\`: ${checkout.repository}${checkout.ref == null ? "" : ` at ${checkout.ref}`}`
12
+ );
13
+ }
14
+ if (description.services.length > 0) {
15
+ lines.push("", "## Services", "");
16
+ for (const service of description.services) {
17
+ const where = service.url ?? (service.port == null ? null : `port ${service.port}`);
18
+ lines.push(`- ${service.name}${where == null ? "" : `: ${where}`}`);
19
+ }
20
+ }
21
+ if (description.commands.length > 0) {
22
+ lines.push("", "## Commands", "");
23
+ for (const command of description.commands) {
24
+ const about = commandDescriptions[command];
25
+ lines.push(`- \`${command}\`${about == null ? "" : `: ${about}`}`);
26
+ }
27
+ }
28
+ if (description.notes != null) lines.push("", "## Notes", "", description.notes);
29
+ return `${lines.join("\n")}
30
+ `;
31
+ };
32
+ const describeSandbox = async (args) => {
33
+ const { handle } = args;
34
+ const setup = args.setup;
35
+ const services = [];
36
+ for (const service of setup?.services ?? []) {
37
+ const url = service.port == null ? null : await handle.getPortUrl({ port: service.port }).catch(() => null);
38
+ services.push({ name: service.name, port: service.port ?? null, url });
39
+ }
40
+ const description = {
41
+ sandboxId: args.sandboxId,
42
+ workspace: setupRoot(handle),
43
+ checkouts: (setup?.repositories ?? []).map((repository) => ({
44
+ alias: repository.alias,
45
+ repository: repository.repository,
46
+ ref: repository.ref ?? null,
47
+ path: checkoutPath(handle, repository.alias)
48
+ })),
49
+ services,
50
+ commands: Object.keys(setup?.commands ?? {}),
51
+ notes: setup?.notes ?? null
52
+ };
53
+ const commandDescriptions = {};
54
+ for (const [name, command] of Object.entries(setup?.commands ?? {}))
55
+ if (command.description != null) commandDescriptions[name] = command.description;
56
+ return { ...description, markdown: renderMarkdown(description, commandDescriptions) };
57
+ };
58
+ export {
59
+ SANDBOX_DESCRIPTION_PATH,
60
+ describeSandbox
61
+ };
62
+ //# sourceMappingURL=describe.mjs.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 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"],
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,I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7D,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
+ "names": []
7
+ }
@@ -0,0 +1,6 @@
1
+ import { type SandboxSetupIface, type SandboxSetupInputIface } from "./schema.mjs";
2
+ export declare const defineSandboxSetup: (value: SandboxSetupInputIface) => SandboxSetupIface;
3
+ export * from "./apply.mjs";
4
+ export * from "./describe.mjs";
5
+ export * from "./paths.mjs";
6
+ export * from "./schema.mjs";
@@ -0,0 +1,17 @@
1
+ import { sandboxSetupSchema } from "./schema.mjs";
2
+ const defineSandboxSetup = (value) => {
3
+ const parsed = sandboxSetupSchema.safeParse(value);
4
+ if (!parsed.success)
5
+ throw new Error(
6
+ `Invalid sandbox setup: ${parsed.error.issues.map((issue) => `${issue.path.join(".") || "(root)"}: ${issue.message}`).join("; ")}`
7
+ );
8
+ return parsed.data;
9
+ };
10
+ export * from "./apply.mjs";
11
+ export * from "./describe.mjs";
12
+ export * from "./paths.mjs";
13
+ export * from "./schema.mjs";
14
+ export {
15
+ defineSandboxSetup
16
+ };
17
+ //# sourceMappingURL=index.mjs.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../../../../../src/sandbox/setup/index.ts"],
4
+ "sourcesContent": ["import { sandboxSetupSchema, type SandboxSetupIface, type SandboxSetupInputIface } from \"./schema.mjs\";\n\n// Validates a sandbox setup and returns it with defaults applied: the value\n// `project.sandboxes.create(environment, { setup })` and\n// `project.sandboxSetups.publish` take. Throws with every problem found.\nexport const defineSandboxSetup = (value: SandboxSetupInputIface): SandboxSetupIface => {\n const parsed = sandboxSetupSchema.safeParse(value);\n if (!parsed.success)\n throw new Error(\n `Invalid sandbox setup: ${parsed.error.issues\n .map((issue) => `${issue.path.join('.') || '(root)'}: ${issue.message}`)\n .join('; ')}`,\n );\n return parsed.data;\n};\n\nexport * from \"./apply.mjs\";\nexport * from \"./describe.mjs\";\nexport * from \"./paths.mjs\";\nexport * from \"./schema.mjs\";\n"],
5
+ "mappings": "AAAA,SAAS,0BAA+E;AAKjF,MAAM,qBAAqB,CAAC,UAAqD;AACtF,QAAM,SAAS,mBAAmB,UAAU,KAAK;AACjD,MAAI,CAAC,OAAO;AACV,UAAM,IAAI;AAAA,MACR,0BAA0B,OAAO,MAAM,OACpC,IAAI,CAAC,UAAU,GAAG,MAAM,KAAK,KAAK,GAAG,KAAK,QAAQ,KAAK,MAAM,OAAO,EAAE,EACtE,KAAK,IAAI,CAAC;AAAA,IACf;AACF,SAAO,OAAO;AAChB;AAEA,cAAc;AACd,cAAc;AACd,cAAc;AACd,cAAc;",
6
+ "names": []
7
+ }
@@ -0,0 +1,8 @@
1
+ import type { NetworkSandboxSessionIface } from "../types.mjs";
2
+ type RootedIface = Pick<NetworkSandboxSessionIface, 'defaultWorkingDirectory'>;
3
+ export declare const setupRoot: (handle: RootedIface) => string;
4
+ export declare const setupPath: (handle: RootedIface, relative: string | undefined) => string;
5
+ export declare const checkoutPath: (handle: RootedIface, alias: string) => string;
6
+ export declare const commandsDirectory: (handle: RootedIface) => string;
7
+ export declare const commandPath: (handle: RootedIface, name: string) => string;
8
+ export {};
@@ -0,0 +1,18 @@
1
+ import { SETUP_ROOT_CWD } from "./schema.mjs";
2
+ const setupRoot = (handle) => handle.defaultWorkingDirectory.replace(/\/+$/, "") || "/";
3
+ const setupPath = (handle, relative) => {
4
+ const root = setupRoot(handle);
5
+ if (relative == null || relative === SETUP_ROOT_CWD) return root;
6
+ return `${root === "/" ? "" : root}/${relative.replace(/^\.\//, "").replace(/\/+$/, "")}`;
7
+ };
8
+ const checkoutPath = (handle, alias) => setupPath(handle, alias);
9
+ const commandsDirectory = (handle) => `${setupPath(handle, ".final/commands")}`;
10
+ const commandPath = (handle, name) => `${commandsDirectory(handle)}/${name}`;
11
+ export {
12
+ checkoutPath,
13
+ commandPath,
14
+ commandsDirectory,
15
+ setupPath,
16
+ setupRoot
17
+ };
18
+ //# sourceMappingURL=paths.mjs.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../../../../../src/sandbox/setup/paths.ts"],
4
+ "sourcesContent": ["import type { NetworkSandboxSessionIface } from \"../types.mjs\";\nimport { SETUP_ROOT_CWD } from \"./schema.mjs\";\n\n// Where a setup's pieces live: under the sandbox's own working directory,\n// never a fixed path.\n\ntype RootedIface = Pick<NetworkSandboxSessionIface, 'defaultWorkingDirectory'>;\n\nexport const setupRoot = (handle: RootedIface): string =>\n handle.defaultWorkingDirectory.replace(/\\/+$/, '') || '/';\n\n// A setup-relative path (`app`, `app/web`, `.`) on this sandbox.\nexport const setupPath = (handle: RootedIface, relative: string | undefined): string => {\n const root = setupRoot(handle);\n if (relative == null || relative === SETUP_ROOT_CWD) return root;\n return `${root === '/' ? '' : root}/${relative.replace(/^\\.\\//, '').replace(/\\/+$/, '')}`;\n};\n\nexport const checkoutPath = (handle: RootedIface, alias: string): string =>\n setupPath(handle, alias);\n\nexport const commandsDirectory = (handle: RootedIface): string =>\n `${setupPath(handle, '.final/commands')}`;\n\nexport const commandPath = (handle: RootedIface, name: string): string =>\n `${commandsDirectory(handle)}/${name}`;\n"],
5
+ "mappings": "AACA,SAAS,sBAAsB;AAOxB,MAAM,YAAY,CAAC,WACxB,OAAO,wBAAwB,QAAQ,QAAQ,EAAE,KAAK;AAGjD,MAAM,YAAY,CAAC,QAAqB,aAAyC;AACtF,QAAM,OAAO,UAAU,MAAM;AAC7B,MAAI,YAAY,QAAQ,aAAa,eAAgB,QAAO;AAC5D,SAAO,GAAG,SAAS,MAAM,KAAK,IAAI,IAAI,SAAS,QAAQ,SAAS,EAAE,EAAE,QAAQ,QAAQ,EAAE,CAAC;AACzF;AAEO,MAAM,eAAe,CAAC,QAAqB,UAChD,UAAU,QAAQ,KAAK;AAElB,MAAM,oBAAoB,CAAC,WAChC,GAAG,UAAU,QAAQ,iBAAiB,CAAC;AAElC,MAAM,cAAc,CAAC,QAAqB,SAC/C,GAAG,kBAAkB,MAAM,CAAC,IAAI,IAAI;",
6
+ "names": []
7
+ }
@@ -0,0 +1,42 @@
1
+ import { type SandboxSetupIface } from '@finalai/agent-protocol/agent-platform';
2
+ export { LATEST_SANDBOX_SETUP_VERSION, sandboxSetupRefInputSchema, type SandboxSetupIface, type SandboxSetupInputIface, type SandboxSetupRefInputIface, } from '@finalai/agent-protocol/agent-platform';
3
+ export type SetupRepositoryIface = SandboxSetupIface['repositories'][number];
4
+ export type SetupStepIface = SandboxSetupIface['steps'][number];
5
+ export type SetupServiceIface = SandboxSetupIface['services'][number];
6
+ export type SetupCommandIface = SandboxSetupIface['commands'][string];
7
+ export declare const SETUP_ROOT_CWD = ".";
8
+ export declare const sandboxSetupSchema: import("zod").ZodObject<{
9
+ repositories: import("zod").ZodDefault<import("zod").ZodArray<import("zod").ZodObject<{
10
+ alias: import("zod").ZodString;
11
+ repository: import("zod").ZodString;
12
+ ref: import("zod").ZodOptional<import("zod").ZodString>;
13
+ }, import("zod/v4/core").$strict>>>;
14
+ variables: import("zod").ZodDefault<import("zod").ZodRecord<import("zod").ZodString, import("zod").ZodUnion<readonly [import("zod").ZodObject<{
15
+ value: import("zod").ZodString;
16
+ }, import("zod/v4/core").$strict>, import("zod").ZodObject<{
17
+ secret: import("zod").ZodString;
18
+ }, import("zod/v4/core").$strict>]>>>;
19
+ steps: import("zod").ZodDefault<import("zod").ZodArray<import("zod").ZodObject<{
20
+ name: import("zod").ZodOptional<import("zod").ZodString>;
21
+ cwd: import("zod").ZodOptional<import("zod").ZodString>;
22
+ run: import("zod").ZodString;
23
+ optional: import("zod").ZodOptional<import("zod").ZodBoolean>;
24
+ timeoutSeconds: import("zod").ZodOptional<import("zod").ZodNumber>;
25
+ }, import("zod/v4/core").$strict>>>;
26
+ services: import("zod").ZodDefault<import("zod").ZodArray<import("zod").ZodObject<{
27
+ name: import("zod").ZodString;
28
+ run: import("zod").ZodString;
29
+ port: import("zod").ZodOptional<import("zod").ZodNumber>;
30
+ cwd: import("zod").ZodOptional<import("zod").ZodString>;
31
+ }, import("zod/v4/core").$strict>>>;
32
+ commands: import("zod").ZodDefault<import("zod").ZodRecord<import("zod").ZodString, import("zod").ZodObject<{
33
+ run: import("zod").ZodString;
34
+ cwd: import("zod").ZodOptional<import("zod").ZodString>;
35
+ description: import("zod").ZodOptional<import("zod").ZodString>;
36
+ }, import("zod/v4/core").$strict>>>;
37
+ network: import("zod").ZodOptional<import("zod").ZodObject<{
38
+ allow: import("zod").ZodOptional<import("zod").ZodArray<import("zod").ZodString>>;
39
+ deny: import("zod").ZodOptional<import("zod").ZodArray<import("zod").ZodString>>;
40
+ }, import("zod/v4/core").$strict>>;
41
+ notes: import("zod").ZodOptional<import("zod").ZodString>;
42
+ }, import("zod/v4/core").$strict>;
@@ -0,0 +1,58 @@
1
+ import {
2
+ sandboxSetupSchema as wireSandboxSetupSchema
3
+ } from "@finalai/agent-protocol/agent-platform";
4
+ import { PLATFORM_ENVIRONMENT_NAMES } from "../types.mjs";
5
+ import {
6
+ LATEST_SANDBOX_SETUP_VERSION,
7
+ sandboxSetupRefInputSchema
8
+ } from "@finalai/agent-protocol/agent-platform";
9
+ const SETUP_ROOT_CWD = ".";
10
+ const staysInside = (path) => !path.startsWith("/") && !path.split("/").some((segment) => segment === "..");
11
+ const sandboxSetupSchema = wireSandboxSetupSchema.superRefine((setup, ctx) => {
12
+ for (const name of Object.keys(setup.variables))
13
+ if (PLATFORM_ENVIRONMENT_NAMES.has(name))
14
+ ctx.addIssue({
15
+ code: "custom",
16
+ path: ["variables", name],
17
+ message: `${name} is set by the platform`
18
+ });
19
+ const aliases = /* @__PURE__ */ new Set();
20
+ for (const [index, repository] of setup.repositories.entries()) {
21
+ if (aliases.has(repository.alias))
22
+ ctx.addIssue({
23
+ code: "custom",
24
+ path: ["repositories", index, "alias"],
25
+ message: `alias ${repository.alias} is used twice`
26
+ });
27
+ aliases.add(repository.alias);
28
+ }
29
+ const checkCwd = (cwd, path) => {
30
+ if (cwd != null && !staysInside(cwd))
31
+ ctx.addIssue({
32
+ code: "custom",
33
+ path: [...path, "cwd"],
34
+ message: `${cwd} leaves the working directory`
35
+ });
36
+ };
37
+ setup.steps.forEach((step, index) => checkCwd(step.cwd, ["steps", index]));
38
+ setup.services.forEach((service, index) => checkCwd(service.cwd, ["services", index]));
39
+ for (const [name, command] of Object.entries(setup.commands))
40
+ checkCwd(command.cwd, ["commands", name]);
41
+ const services = /* @__PURE__ */ new Set();
42
+ for (const [index, service] of setup.services.entries()) {
43
+ if (services.has(service.name))
44
+ ctx.addIssue({
45
+ code: "custom",
46
+ path: ["services", index, "name"],
47
+ message: `service ${service.name} is declared twice`
48
+ });
49
+ services.add(service.name);
50
+ }
51
+ });
52
+ export {
53
+ LATEST_SANDBOX_SETUP_VERSION,
54
+ SETUP_ROOT_CWD,
55
+ sandboxSetupRefInputSchema,
56
+ sandboxSetupSchema
57
+ };
58
+ //# sourceMappingURL=schema.mjs.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../../../../../src/sandbox/setup/schema.ts"],
4
+ "sourcesContent": ["import {\n sandboxSetupSchema as wireSandboxSetupSchema,\n type SandboxSetupIface,\n} from '@finalai/agent-protocol/agent-platform';\nimport { PLATFORM_ENVIRONMENT_NAMES } from \"../types.mjs\";\n\n// A sandbox setup is the wire schema `@finalai/agent-protocol` defines (what\n// should be on a machine, provider-neutral), plus the checks only a whole\n// setup can fail: every `cwd` stays inside the working directory, aliases and\n// service names are unique, and no variable takes over one the platform sets.\n// Paths are relative to the sandbox's working directory: a repository with\n// alias `app` is checked out at `<working directory>/app`.\n\nexport {\n LATEST_SANDBOX_SETUP_VERSION,\n sandboxSetupRefInputSchema,\n type SandboxSetupIface,\n type SandboxSetupInputIface,\n type SandboxSetupRefInputIface,\n} from '@finalai/agent-protocol/agent-platform';\n\nexport type SetupRepositoryIface = SandboxSetupIface['repositories'][number];\nexport type SetupStepIface = SandboxSetupIface['steps'][number];\nexport type SetupServiceIface = SandboxSetupIface['services'][number];\nexport type SetupCommandIface = SandboxSetupIface['commands'][string];\n\nexport const SETUP_ROOT_CWD = '.';\n\n// Whether a relative path stays inside the directory it is relative to.\nconst staysInside = (path: string): boolean =>\n !path.startsWith('/') && !path.split('/').some((segment) => segment === '..');\n\nexport const sandboxSetupSchema = wireSandboxSetupSchema.superRefine((setup, ctx) => {\n for (const name of Object.keys(setup.variables))\n if (PLATFORM_ENVIRONMENT_NAMES.has(name))\n ctx.addIssue({\n code: 'custom',\n path: ['variables', name],\n message: `${name} is set by the platform`,\n });\n const aliases = new Set<string>();\n for (const [index, repository] of setup.repositories.entries()) {\n if (aliases.has(repository.alias))\n ctx.addIssue({\n code: 'custom',\n path: ['repositories', index, 'alias'],\n message: `alias ${repository.alias} is used twice`,\n });\n aliases.add(repository.alias);\n }\n const checkCwd = (cwd: string | undefined, path: (string | number)[]) => {\n if (cwd != null && !staysInside(cwd))\n ctx.addIssue({\n code: 'custom',\n path: [...path, 'cwd'],\n message: `${cwd} leaves the working directory`,\n });\n };\n setup.steps.forEach((step, index) => checkCwd(step.cwd, ['steps', index]));\n setup.services.forEach((service, index) => checkCwd(service.cwd, ['services', index]));\n for (const [name, command] of Object.entries(setup.commands))\n checkCwd(command.cwd, ['commands', name]);\n const services = new Set<string>();\n for (const [index, service] of setup.services.entries()) {\n if (services.has(service.name))\n ctx.addIssue({\n code: 'custom',\n path: ['services', index, 'name'],\n message: `service ${service.name} is declared twice`,\n });\n services.add(service.name);\n }\n});\n"],
5
+ "mappings": "AAAA;AAAA,EACE,sBAAsB;AAAA,OAEjB;AACP,SAAS,kCAAkC;AAS3C;AAAA,EACE;AAAA,EACA;AAAA,OAIK;AAOA,MAAM,iBAAiB;AAG9B,MAAM,cAAc,CAAC,SACnB,CAAC,KAAK,WAAW,GAAG,KAAK,CAAC,KAAK,MAAM,GAAG,EAAE,KAAK,CAAC,YAAY,YAAY,IAAI;AAEvE,MAAM,qBAAqB,uBAAuB,YAAY,CAAC,OAAO,QAAQ;AACnF,aAAW,QAAQ,OAAO,KAAK,MAAM,SAAS;AAC5C,QAAI,2BAA2B,IAAI,IAAI;AACrC,UAAI,SAAS;AAAA,QACX,MAAM;AAAA,QACN,MAAM,CAAC,aAAa,IAAI;AAAA,QACxB,SAAS,GAAG,IAAI;AAAA,MAClB,CAAC;AACL,QAAM,UAAU,oBAAI,IAAY;AAChC,aAAW,CAAC,OAAO,UAAU,KAAK,MAAM,aAAa,QAAQ,GAAG;AAC9D,QAAI,QAAQ,IAAI,WAAW,KAAK;AAC9B,UAAI,SAAS;AAAA,QACX,MAAM;AAAA,QACN,MAAM,CAAC,gBAAgB,OAAO,OAAO;AAAA,QACrC,SAAS,SAAS,WAAW,KAAK;AAAA,MACpC,CAAC;AACH,YAAQ,IAAI,WAAW,KAAK;AAAA,EAC9B;AACA,QAAM,WAAW,CAAC,KAAyB,SAA8B;AACvE,QAAI,OAAO,QAAQ,CAAC,YAAY,GAAG;AACjC,UAAI,SAAS;AAAA,QACX,MAAM;AAAA,QACN,MAAM,CAAC,GAAG,MAAM,KAAK;AAAA,QACrB,SAAS,GAAG,GAAG;AAAA,MACjB,CAAC;AAAA,EACL;AACA,QAAM,MAAM,QAAQ,CAAC,MAAM,UAAU,SAAS,KAAK,KAAK,CAAC,SAAS,KAAK,CAAC,CAAC;AACzE,QAAM,SAAS,QAAQ,CAAC,SAAS,UAAU,SAAS,QAAQ,KAAK,CAAC,YAAY,KAAK,CAAC,CAAC;AACrF,aAAW,CAAC,MAAM,OAAO,KAAK,OAAO,QAAQ,MAAM,QAAQ;AACzD,aAAS,QAAQ,KAAK,CAAC,YAAY,IAAI,CAAC;AAC1C,QAAM,WAAW,oBAAI,IAAY;AACjC,aAAW,CAAC,OAAO,OAAO,KAAK,MAAM,SAAS,QAAQ,GAAG;AACvD,QAAI,SAAS,IAAI,QAAQ,IAAI;AAC3B,UAAI,SAAS;AAAA,QACX,MAAM;AAAA,QACN,MAAM,CAAC,YAAY,OAAO,MAAM;AAAA,QAChC,SAAS,WAAW,QAAQ,IAAI;AAAA,MAClC,CAAC;AACH,aAAS,IAAI,QAAQ,IAAI;AAAA,EAC3B;AACF,CAAC;",
6
+ "names": []
7
+ }
@@ -1,4 +1,4 @@
1
- import { ToolApproval } from "../manifest.mjs";
1
+ import { ToolApprovalMode as ToolApproval } from "../document.mjs";
2
2
  export declare const resolveSandboxToolPolicy: (policy: Record<string, ToolApproval>, keys: readonly string[]) => {
3
3
  key: string;
4
4
  decision: ToolApproval;
@@ -1,4 +1,4 @@
1
- import { ToolApproval } from "../manifest.mjs";
1
+ import { ToolApprovalMode as ToolApproval } from "../document.mjs";
2
2
  const nativePolicyKeys = /* @__PURE__ */ new Set([
3
3
  "run",
4
4
  "spawn",
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../../../../../src/sandbox/tool-policy.ts"],
4
- "sourcesContent": ["import { ToolApproval } from \"../manifest.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;AAG7B,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;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,CAAC;AAGM,MAAM,2BAA2B,CACtC,QACA,SACmD;AACnD,QAAM,UAAU,CAAC,QAAiB,OAAO,OAAO,QAAQ,GAAG,IAAI,OAAO,GAAG,IAAI;AAC7E,QAAM,SAAS,KAAK,SAAS,QAAQ,KAAK,KAAK,SAAS,gBAAgB;AACxE,MAAI,QAAQ;AACV,UAAM,MAAM,KAAK,KAAK,CAAC,cAAc,QAAQ,SAAS,MAAM,aAAa,GAAG;AAC5E,QAAI,OAAO,KAAM,QAAO,EAAE,KAAK,UAAU,aAAa,IAAI;AAAA,EAC5D;AACA,MACE,WACC,KAAK,SAAS,0BAA0B,KAAK,KAAK,SAAS,wBAAwB,IACpF;AACA,UAAM,YAAY,KAAK,SAAS,0BAA0B,IACtD,6BACA;AACJ,UAAM,MAAM,QAAQ,SAAS,MAAM,aAAa,QAAQ,YAAY;AACpE,WAAO;AAAA,MACL,KAAK,OAAO;AAAA,MACZ,UAAU,OAAO,OAAO,aAAa,MAAM,aAAa;AAAA,IAC1D;AAAA,EACF;AACA,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;",
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,oBAAI,IAAI;AAAA,EAC/B;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;A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