@agent-native/core 0.51.15 → 0.52.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 +3 -3
  2. package/dist/cli/connect.d.ts +4 -3
  3. package/dist/cli/connect.d.ts.map +1 -1
  4. package/dist/cli/connect.js +67 -26
  5. package/dist/cli/connect.js.map +1 -1
  6. package/dist/cli/mcp-config-writers.d.ts +20 -13
  7. package/dist/cli/mcp-config-writers.d.ts.map +1 -1
  8. package/dist/cli/mcp-config-writers.js +152 -13
  9. package/dist/cli/mcp-config-writers.js.map +1 -1
  10. package/dist/cli/mcp.d.ts +2 -2
  11. package/dist/cli/mcp.d.ts.map +1 -1
  12. package/dist/cli/mcp.js +41 -193
  13. package/dist/cli/mcp.js.map +1 -1
  14. package/dist/cli/plan-local.d.ts +3 -1
  15. package/dist/cli/plan-local.d.ts.map +1 -1
  16. package/dist/cli/plan-local.js +24 -6
  17. package/dist/cli/plan-local.js.map +1 -1
  18. package/dist/cli/recap.d.ts.map +1 -1
  19. package/dist/cli/recap.js +1 -1
  20. package/dist/cli/recap.js.map +1 -1
  21. package/dist/cli/skills.d.ts +11 -4
  22. package/dist/cli/skills.d.ts.map +1 -1
  23. package/dist/cli/skills.js +218 -53
  24. package/dist/cli/skills.js.map +1 -1
  25. package/dist/client/agent-engine-key.d.ts +6 -4
  26. package/dist/client/agent-engine-key.d.ts.map +1 -1
  27. package/dist/client/agent-engine-key.js +9 -6
  28. package/dist/client/agent-engine-key.js.map +1 -1
  29. package/dist/client/chat/run-recovery.js +1 -1
  30. package/dist/client/chat/run-recovery.js.map +1 -1
  31. package/dist/client/settings/SettingsPanel.d.ts.map +1 -1
  32. package/dist/client/settings/SettingsPanel.js +7 -14
  33. package/dist/client/settings/SettingsPanel.js.map +1 -1
  34. package/dist/coding-tools/run-code.d.ts +7 -0
  35. package/dist/coding-tools/run-code.d.ts.map +1 -1
  36. package/dist/coding-tools/run-code.js +21 -106
  37. package/dist/coding-tools/run-code.js.map +1 -1
  38. package/dist/coding-tools/sandbox/adapter.d.ts +79 -0
  39. package/dist/coding-tools/sandbox/adapter.d.ts.map +1 -0
  40. package/dist/coding-tools/sandbox/adapter.js +24 -0
  41. package/dist/coding-tools/sandbox/adapter.js.map +1 -0
  42. package/dist/coding-tools/sandbox/index.d.ts +51 -0
  43. package/dist/coding-tools/sandbox/index.d.ts.map +1 -0
  44. package/dist/coding-tools/sandbox/index.js +79 -0
  45. package/dist/coding-tools/sandbox/index.js.map +1 -0
  46. package/dist/coding-tools/sandbox/local-child-process-adapter.d.ts +24 -0
  47. package/dist/coding-tools/sandbox/local-child-process-adapter.d.ts.map +1 -0
  48. package/dist/coding-tools/sandbox/local-child-process-adapter.js +141 -0
  49. package/dist/coding-tools/sandbox/local-child-process-adapter.js.map +1 -0
  50. package/dist/server/agent-engine-api-key-route.d.ts +37 -0
  51. package/dist/server/agent-engine-api-key-route.d.ts.map +1 -0
  52. package/dist/server/agent-engine-api-key-route.js +105 -0
  53. package/dist/server/agent-engine-api-key-route.js.map +1 -0
  54. package/dist/server/core-routes-plugin.d.ts.map +1 -1
  55. package/dist/server/core-routes-plugin.js +10 -6
  56. package/dist/server/core-routes-plugin.js.map +1 -1
  57. package/dist/server/create-server.js +1 -1
  58. package/dist/server/create-server.js.map +1 -1
  59. package/dist/templates/workspace-core/.agents/skills/external-agents/SKILL.md +7 -4
  60. package/package.json +1 -1
  61. package/src/templates/workspace-core/.agents/skills/external-agents/SKILL.md +7 -4
@@ -20,6 +20,13 @@
20
20
  * model; the env scrub means such requests carry no credentials, and all
21
21
  * authenticated calls must go through the bridge (which applies the
22
22
  * registered tools' host allowlists and SSRF guards).
23
+ *
24
+ * The actual execution is delegated to a pluggable `SandboxAdapter` (see
25
+ * `./sandbox`). The default `LocalChildProcessAdapter` preserves the spawned
26
+ * child-process behavior described above; a remote/durable adapter can be
27
+ * plugged in via `registerSandboxAdapter()` / `AGENT_NATIVE_SANDBOX` without
28
+ * changing this file. The bridge, env scrub, module building, and output
29
+ * formatting stay here in the parent regardless of adapter.
23
30
  */
24
31
  import type { ActionEntry } from "../agent/production-agent.js";
25
32
  export interface RunCodeOptions {
@@ -1 +1 @@
1
- {"version":3,"file":"run-code.d.ts","sourceRoot":"","sources":["../../src/coding-tools/run-code.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;GAsBG;AASH,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,8BAA8B,CAAC;AA8DhE,MAAM,WAAW,cAAc;IAC7B;;;OAGG;IACH,WAAW,CAAC,EAAE,MAAM,EAAE,CAAC;CACxB;AAED;;;;;;GAMG;AACH,wBAAgB,kBAAkB,CAChC,UAAU,EAAE,MAAM,MAAM,CAAC,MAAM,EAAE,WAAW,CAAC,EAC7C,IAAI,GAAE,cAAmB,GACxB,WAAW,CA4Mb"}
1
+ {"version":3,"file":"run-code.d.ts","sourceRoot":"","sources":["../../src/coding-tools/run-code.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA6BG;AAKH,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,8BAA8B,CAAC;AAoBhE,MAAM,WAAW,cAAc;IAC7B;;;OAGG;IACH,WAAW,CAAC,EAAE,MAAM,EAAE,CAAC;CACxB;AAED;;;;;;GAMG;AACH,wBAAgB,kBAAkB,CAChC,UAAU,EAAE,MAAM,MAAM,CAAC,MAAM,EAAE,WAAW,CAAC,EAC7C,IAAI,GAAE,cAAmB,GACxB,WAAW,CAiJb"}
@@ -20,59 +20,23 @@
20
20
  * model; the env scrub means such requests carry no credentials, and all
21
21
  * authenticated calls must go through the bridge (which applies the
22
22
  * registered tools' host allowlists and SSRF guards).
23
+ *
24
+ * The actual execution is delegated to a pluggable `SandboxAdapter` (see
25
+ * `./sandbox`). The default `LocalChildProcessAdapter` preserves the spawned
26
+ * child-process behavior described above; a remote/durable adapter can be
27
+ * plugged in via `registerSandboxAdapter()` / `AGENT_NATIVE_SANDBOX` without
28
+ * changing this file. The bridge, env scrub, module building, and output
29
+ * formatting stay here in the parent regardless of adapter.
23
30
  */
24
31
  import crypto from "node:crypto";
25
- import fs from "node:fs";
26
32
  import http from "node:http";
27
- import os from "node:os";
28
- import path from "node:path";
29
- import { spawn, spawnSync } from "node:child_process";
33
+ import { getSandboxAdapter } from "./sandbox/index.js";
30
34
  const DEFAULT_TIMEOUT_MS = 120_000;
31
35
  const MAX_TIMEOUT_MS = 600_000;
32
36
  const DEFAULT_MAX_OUTPUT_CHARS = 50_000;
33
37
  const MAX_OUTPUT_CHARS = 200_000;
34
38
  /** Hard cap on bridge request bodies so sandboxed code can't exhaust parent memory. */
35
39
  const BRIDGE_MAX_BODY_BYTES = 10 * 1024 * 1024;
36
- function sandboxReadAllowPaths(tmpDir) {
37
- const paths = new Set([tmpDir]);
38
- try {
39
- paths.add(fs.realpathSync(tmpDir));
40
- }
41
- catch { }
42
- return [...paths];
43
- }
44
- function sandboxWriteAllowPaths(tmpDir) {
45
- const paths = new Set([tmpDir]);
46
- try {
47
- paths.add(fs.realpathSync(tmpDir));
48
- }
49
- catch { }
50
- return [...paths];
51
- }
52
- /**
53
- * Resolve the Node permission-model flag supported by the current runtime,
54
- * probing once and caching. Returns null when the permission model is
55
- * unavailable (the sandbox then falls back to env-scrub isolation only).
56
- */
57
- let cachedPermissionFlag;
58
- function resolvePermissionFlag() {
59
- if (cachedPermissionFlag !== undefined)
60
- return cachedPermissionFlag;
61
- for (const flag of ["--permission", "--experimental-permission"]) {
62
- try {
63
- const probe = spawnSync(process.execPath, [flag, "-e", "process.exit(0)"], { timeout: 10_000, stdio: "ignore" });
64
- if (probe.status === 0) {
65
- cachedPermissionFlag = flag;
66
- return flag;
67
- }
68
- }
69
- catch {
70
- // Probe failure means the flag is unsupported; try the next one.
71
- }
72
- }
73
- cachedPermissionFlag = null;
74
- return null;
75
- }
76
40
  /** Tools callable via the sandbox bridge by default. */
77
41
  const DEFAULT_BRIDGE_TOOLS = new Set([
78
42
  "provider-api-request",
@@ -156,16 +120,10 @@ export function createRunCodeEntry(getActions, opts = {}) {
156
120
  const actions = getActions();
157
121
  const bridgeToken = crypto.randomBytes(32).toString("hex");
158
122
  // Start bridge server — resolves once the server is listening.
159
- const { server, bridgePort, getUsedTools, cleanup: cleanupBridge, } = await startBridgeServer(bridgeToken, actions, context, DEFAULT_BRIDGE_TOOLS, extraBridgeTools);
160
- let tmpDir;
161
- let tmpFile;
123
+ const { bridgePort, getUsedTools, cleanup: cleanupBridge, } = await startBridgeServer(bridgeToken, actions, context, DEFAULT_BRIDGE_TOOLS, extraBridgeTools);
162
124
  try {
163
- // Write code to a temp ESM file (top-level await needs a module).
164
- const tmpBaseDir = fs.realpathSync(os.tmpdir());
165
- tmpDir = fs.mkdtempSync(path.join(tmpBaseDir, "agent-run-code-"));
166
- tmpFile = path.join(tmpDir, "sandbox.mjs");
167
- fs.writeFileSync(tmpFile, buildSandboxModule(code, bridgePort, bridgeToken), "utf8");
168
- // Build scrubbed env — only safe POSIX vars, no secrets.
125
+ // Build scrubbed env only safe POSIX vars, no secrets. The adapter
126
+ // points TMPDIR/TEMP/TMP at the sandbox's own temp dir.
169
127
  const safeEnv = {};
170
128
  for (const key of [
171
129
  "PATH",
@@ -179,52 +137,16 @@ export function createRunCodeEntry(getActions, opts = {}) {
179
137
  if (process.env[key])
180
138
  safeEnv[key] = process.env[key];
181
139
  }
182
- // Point TMPDIR inside the sandbox dir so in-sandbox temp writes stay
183
- // within the permission-model allow list.
184
- safeEnv.TMPDIR = tmpDir;
185
- safeEnv.TEMP = tmpDir;
186
- safeEnv.TMP = tmpDir;
187
- // Lock the child down with the Node permission model when available:
188
- // filesystem restricted to the sandbox temp dir, and child processes,
189
- // workers, and native addons denied entirely.
190
- const permissionFlag = resolvePermissionFlag();
191
- const nodeArgs = permissionFlag
192
- ? [
193
- permissionFlag,
194
- ...sandboxReadAllowPaths(tmpDir).map((allowedPath) => `--allow-fs-read=${allowedPath}`),
195
- ...sandboxWriteAllowPaths(tmpDir).map((allowedPath) => `--allow-fs-write=${allowedPath}`),
196
- tmpFile,
197
- ]
198
- : [tmpFile];
199
- const child = spawn(process.execPath, nodeArgs, {
200
- cwd: tmpDir,
140
+ // Delegate execution to the active sandbox adapter (local child process
141
+ // by default; remote/durable adapters can be registered via
142
+ // ./sandbox). The bridge, env scrub, module, and output formatting stay
143
+ // in the parent regardless of adapter.
144
+ const { stdout, stderr, exitCode, timedOut } = await getSandboxAdapter().run({
145
+ moduleSource: buildSandboxModule(code, bridgePort, bridgeToken),
201
146
  env: safeEnv,
202
- stdio: ["ignore", "pipe", "pipe"],
147
+ timeoutMs,
148
+ bridgePort,
203
149
  });
204
- let stdout = "";
205
- let stderr = "";
206
- let timedOut = false;
207
- const timer = setTimeout(() => {
208
- timedOut = true;
209
- child.kill("SIGTERM");
210
- setTimeout(() => {
211
- try {
212
- child.kill("SIGKILL");
213
- }
214
- catch { }
215
- }, 2_000);
216
- }, timeoutMs);
217
- child.stdout?.on("data", (chunk) => {
218
- stdout += chunk.toString();
219
- });
220
- child.stderr?.on("data", (chunk) => {
221
- stderr += chunk.toString();
222
- });
223
- const exitCode = await new Promise((resolve, reject) => {
224
- child.once("error", reject);
225
- child.once("exit", resolve);
226
- });
227
- clearTimeout(timer);
228
150
  const combined = [
229
151
  stdout ? `stdout:\n${stdout}` : "",
230
152
  stderr ? `stderr:\n${stderr}` : "",
@@ -248,16 +170,9 @@ export function createRunCodeEntry(getActions, opts = {}) {
248
170
  return full;
249
171
  }
250
172
  finally {
173
+ // The active sandbox adapter owns its own temp-file cleanup; the parent
174
+ // only tears down the bridge server here.
251
175
  cleanupBridge();
252
- server.close();
253
- // Clean up temp files (best-effort).
254
- try {
255
- if (tmpFile)
256
- fs.rmSync(tmpFile, { force: true });
257
- if (tmpDir)
258
- fs.rmSync(tmpDir, { recursive: true, force: true });
259
- }
260
- catch { }
261
176
  }
262
177
  },
263
178
  };
@@ -1 +1 @@
1
-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B,UAAU;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EAuwBtB,QAAQ;;;;;CAKT,CAAC;AACF,CAAC","sourcesContent":["/**\n * Sandboxed JavaScript execution tool for the agent.\n *\n * Executes user-supplied JavaScript in an isolated child process with:\n * - A scrubbed environment (no app secrets or env vars; only PATH/HOME/TMPDIR).\n * - A fresh temporary working directory.\n * - An ephemeral bridge HTTP server on 127.0.0.1 so the child can call\n * allowlisted registered tools (provider-api-request, web-request, etc.)\n * with the same request context as the parent — without leaking secrets.\n *\n * Security notes:\n * - The bridge token is a 32-byte random hex string generated per invocation.\n * - The bridge binds to 127.0.0.1 only; no external exposure.\n * - The allowlist of callable bridge tools is enforced server-side.\n * - Secret values are NEVER included in the env passed to the child.\n * - When the Node permission model is available (`--permission`, or\n * `--experimental-permission` on Node 20), the child is denied filesystem\n * access outside its own temp dir, child processes, workers, and native\n * addons. Outbound network from the child is NOT blocked by the permission\n * model; the env scrub means such requests carry no credentials, and all\n * authenticated calls must go through the bridge (which applies the\n * registered tools' host allowlists and SSRF guards).\n */\n\nimport crypto from \"node:crypto\";\nimport fs from \"node:fs\";\nimport http from \"node:http\";\nimport os from \"node:os\";\nimport path from \"node:path\";\nimport { spawn, spawnSync } from \"node:child_process\";\n\nimport type { ActionEntry } from \"../agent/production-agent.js\";\nimport type { ActionRunContext } from \"../action.js\";\n\nconst DEFAULT_TIMEOUT_MS = 120_000;\nconst MAX_TIMEOUT_MS = 600_000;\nconst DEFAULT_MAX_OUTPUT_CHARS = 50_000;\nconst MAX_OUTPUT_CHARS = 200_000;\n/** Hard cap on bridge request bodies so sandboxed code can't exhaust parent memory. */\nconst BRIDGE_MAX_BODY_BYTES = 10 * 1024 * 1024;\n\nfunction sandboxReadAllowPaths(tmpDir: string): string[] {\n const paths = new Set<string>([tmpDir]);\n try {\n paths.add(fs.realpathSync(tmpDir));\n } catch {}\n return [...paths];\n}\n\nfunction sandboxWriteAllowPaths(tmpDir: string): string[] {\n const paths = new Set<string>([tmpDir]);\n try {\n paths.add(fs.realpathSync(tmpDir));\n } catch {}\n return [...paths];\n}\n\n/**\n * Resolve the Node permission-model flag supported by the current runtime,\n * probing once and caching. Returns null when the permission model is\n * unavailable (the sandbox then falls back to env-scrub isolation only).\n */\nlet cachedPermissionFlag: string | null | undefined;\nfunction resolvePermissionFlag(): string | null {\n if (cachedPermissionFlag !== undefined) return cachedPermissionFlag;\n for (const flag of [\"--permission\", \"--experimental-permission\"]) {\n try {\n const probe = spawnSync(\n process.execPath,\n [flag, \"-e\", \"process.exit(0)\"],\n { timeout: 10_000, stdio: \"ignore\" },\n );\n if (probe.status === 0) {\n cachedPermissionFlag = flag;\n return flag;\n }\n } catch {\n // Probe failure means the flag is unsupported; try the next one.\n }\n }\n cachedPermissionFlag = null;\n return null;\n}\n\n/** Tools callable via the sandbox bridge by default. */\nconst DEFAULT_BRIDGE_TOOLS = new Set([\n \"provider-api-request\",\n \"provider-api-docs\",\n \"provider-api-catalog\",\n \"web-request\",\n \"workspace-files\",\n]);\n\nexport interface RunCodeOptions {\n /**\n * Extra tool names (beyond the default set) that the sandbox bridge will\n * forward to the registered action registry.\n */\n bridgeTools?: string[];\n}\n\n/**\n * Create a `run-code` ActionEntry.\n *\n * @param getActions Supplier that returns the current action registry (called\n * at invocation time so updates are reflected).\n * @param opts Optional configuration.\n */\nexport function createRunCodeEntry(\n getActions: () => Record<string, ActionEntry>,\n opts: RunCodeOptions = {},\n): ActionEntry {\n const extraBridgeTools = new Set(opts.bridgeTools ?? []);\n\n return {\n readOnly: true,\n // Allow a generous per-call timeout so large data-processing jobs don't hit\n // the agent-loop's default 60 s cap.\n timeoutMs: MAX_TIMEOUT_MS,\n maxResultChars: MAX_OUTPUT_CHARS,\n tool: {\n description: [\n \"Execute JavaScript (Node.js, ESM, top-level await supported) in an isolated sandbox.\",\n \"Use this to fetch, join, aggregate, and reduce large datasets, returning only printed output to the conversation.\",\n \"The sandbox runs with a scrubbed environment (no secrets) and, where the Node permission model is available, no filesystem access outside its own temp dir, no child processes, and no workers. Authenticated calls must go through the provided globals; direct network requests carry no credentials. Note: isolation is process-level (env scrub + Node permission model), not an OS-level container — outbound network from sandbox code is not blocked.\",\n \"Available globals:\",\n \" - `appAction(name, args?)` — call any registered agent-exposed read-only app action/tool and get its parsed result.\",\n \" Use this to loop over app data readers and compose multi-source analyses without forcing every intermediate result into chat.\",\n \" - `providerFetch(provider, path, init?)` — authenticated call to a registered provider via the provider-api-request action.\",\n \" Returns the parsed JSON result (or throws on error).\",\n \" Supports stageAs/saveToFile/fetchAllPages; use cursorBodyPath for POST-body pagination.\",\n \" Example: `const data = await providerFetch('<provider-id>', '/records', { query: { limit: 100 } });`\",\n \" - `providerRequest(provider, path, init?)` — same authenticated call, but returns the full provider-api envelope with request, response status/headers, truncation, and body metadata.\",\n \" - `providerFetchAll(provider, path, init?)` — generic pagination helper for cursor, page, and offset APIs. Pass `pagination: { itemsPath, cursorPath or nextCursorPath, cursorParam or cursorBodyPath, pageParam, offsetParam, pageSize, maxPages }`. Returns `{ items, pages, pageCount, itemCount, hasMore, lastCursor, stoppedReason }`.\",\n \" - `providerSearchAll(provider, path, init?, options?)` — streaming search helper for broad provider corpora such as transcripts, messages, tickets, issues, notes, events, or documents. Use this before hand-written loops when searching many provider records for terms/phrases/regexes or proving absence. Pass the same `pagination` config as `providerFetchAll`, plus options like `{ query, queries, terms, regex, textPaths, idPaths, metadataPaths, maxHits }`. Returns structured hits with item ids, paths, snippets, page/item indexes, and coverage fields (`pageCount`, `itemCount`, `hasMore`, `stoppedReason`).\",\n \" - `webFetch(url, init?)` — outbound HTTP request via the web-request action.\",\n \" Returns `{ status, body }` where body is the response text.\",\n \" Example: `const { body } = await webFetch('https://api.example.com/data');`\",\n \" - `workspaceRead(path, opts?)` — read a Resources-backed workspace file by path. Returns content string or null. opts: { offset?, maxChars? }.\",\n \" - `workspaceReadMeta(path, opts?)` — read a workspace file with metadata such as sizeBytes, truncated, and nextOffset.\",\n \" - `workspaceWrite(path, content, contentType?)` — create or overwrite a workspace file. Use `scratch/...` for temporary staging; use durable folders only for files the user should keep.\",\n \" - `workspaceAppend(path, content)` — append text to a workspace file.\",\n \" - `workspaceList(prefix?)` — list workspace files, returns [{ path, sizeBytes, contentType, updatedAt }].\",\n \"Print results with `console.log()`; only stdout+stderr are returned.\",\n \"Timeout defaults to 120 s (max 600 s). Output is truncated to 50 000 chars by default (max 200 000).\",\n ].join(\" \"),\n parameters: {\n type: \"object\",\n properties: {\n code: {\n type: \"string\",\n description:\n \"JavaScript source to execute. ESM syntax, top-level await allowed.\",\n },\n timeoutMs: {\n type: \"number\",\n description: `Execution timeout in milliseconds. Default: ${DEFAULT_TIMEOUT_MS}. Max: ${MAX_TIMEOUT_MS}.`,\n },\n maxOutputChars: {\n type: \"number\",\n description: `Maximum combined stdout+stderr characters to return. Default: ${DEFAULT_MAX_OUTPUT_CHARS}. Max: ${MAX_OUTPUT_CHARS}.`,\n },\n },\n required: [\"code\"],\n },\n },\n run: async (args: Record<string, string>, context?: ActionRunContext) => {\n const code = typeof args.code === \"string\" ? args.code : \"\";\n if (!code.trim()) return \"Error: code is required.\";\n\n const requestedTimeout = Number(args.timeoutMs);\n const timeoutMs =\n Number.isFinite(requestedTimeout) && requestedTimeout > 0\n ? Math.min(requestedTimeout, MAX_TIMEOUT_MS)\n : DEFAULT_TIMEOUT_MS;\n\n const requestedMaxOutput = Number(args.maxOutputChars);\n const maxOutputChars =\n Number.isFinite(requestedMaxOutput) && requestedMaxOutput > 0\n ? Math.min(requestedMaxOutput, MAX_OUTPUT_CHARS)\n : DEFAULT_MAX_OUTPUT_CHARS;\n\n const actions = getActions();\n const bridgeToken = crypto.randomBytes(32).toString(\"hex\");\n\n // Start bridge server — resolves once the server is listening.\n const {\n server,\n bridgePort,\n getUsedTools,\n cleanup: cleanupBridge,\n } = await startBridgeServer(\n bridgeToken,\n actions,\n context,\n DEFAULT_BRIDGE_TOOLS,\n extraBridgeTools,\n );\n\n let tmpDir: string | undefined;\n let tmpFile: string | undefined;\n try {\n // Write code to a temp ESM file (top-level await needs a module).\n const tmpBaseDir = fs.realpathSync(os.tmpdir());\n tmpDir = fs.mkdtempSync(path.join(tmpBaseDir, \"agent-run-code-\"));\n tmpFile = path.join(tmpDir, \"sandbox.mjs\");\n fs.writeFileSync(\n tmpFile,\n buildSandboxModule(code, bridgePort, bridgeToken),\n \"utf8\",\n );\n\n // Build scrubbed env — only safe POSIX vars, no secrets.\n const safeEnv: Record<string, string> = {};\n for (const key of [\n \"PATH\",\n \"HOME\",\n \"TMPDIR\",\n \"TEMP\",\n \"TMP\",\n \"LANG\",\n \"LC_ALL\",\n ]) {\n if (process.env[key]) safeEnv[key] = process.env[key]!;\n }\n // Point TMPDIR inside the sandbox dir so in-sandbox temp writes stay\n // within the permission-model allow list.\n safeEnv.TMPDIR = tmpDir;\n safeEnv.TEMP = tmpDir;\n safeEnv.TMP = tmpDir;\n\n // Lock the child down with the Node permission model when available:\n // filesystem restricted to the sandbox temp dir, and child processes,\n // workers, and native addons denied entirely.\n const permissionFlag = resolvePermissionFlag();\n const nodeArgs = permissionFlag\n ? [\n permissionFlag,\n ...sandboxReadAllowPaths(tmpDir).map(\n (allowedPath) => `--allow-fs-read=${allowedPath}`,\n ),\n ...sandboxWriteAllowPaths(tmpDir).map(\n (allowedPath) => `--allow-fs-write=${allowedPath}`,\n ),\n tmpFile,\n ]\n : [tmpFile];\n\n const child = spawn(process.execPath, nodeArgs, {\n cwd: tmpDir,\n env: safeEnv,\n stdio: [\"ignore\", \"pipe\", \"pipe\"],\n });\n\n let stdout = \"\";\n let stderr = \"\";\n let timedOut = false;\n\n const timer = setTimeout(() => {\n timedOut = true;\n child.kill(\"SIGTERM\");\n setTimeout(() => {\n try {\n child.kill(\"SIGKILL\");\n } catch {}\n }, 2_000);\n }, timeoutMs);\n\n child.stdout?.on(\"data\", (chunk: Buffer) => {\n stdout += chunk.toString();\n });\n child.stderr?.on(\"data\", (chunk: Buffer) => {\n stderr += chunk.toString();\n });\n\n const exitCode = await new Promise<number | null>((resolve, reject) => {\n child.once(\"error\", reject);\n child.once(\"exit\", resolve);\n });\n clearTimeout(timer);\n\n const combined =\n [\n stdout ? `stdout:\\n${stdout}` : \"\",\n stderr ? `stderr:\\n${stderr}` : \"\",\n ]\n .filter(Boolean)\n .join(\"\\n\\n\") || \"(no output)\";\n\n const lines: string[] = [];\n if (timedOut) lines.push(`timedOut: true (${timeoutMs}ms)`);\n if (exitCode !== 0 && exitCode !== null)\n lines.push(`exitCode: ${exitCode}`);\n const usedTools = getUsedTools();\n if (usedTools.length)\n lines.push(`bridgeToolsUsed: ${usedTools.join(\", \")}`);\n lines.push(combined);\n\n const full = lines.join(\"\\n\\n\");\n if (full.length > maxOutputChars) {\n const truncated = full.slice(0, maxOutputChars);\n return `${truncated}\\n\\n...[truncated ${(full.length - maxOutputChars).toLocaleString()} chars]`;\n }\n return full;\n } finally {\n cleanupBridge();\n server.close();\n // Clean up temp files (best-effort).\n try {\n if (tmpFile) fs.rmSync(tmpFile, { force: true });\n if (tmpDir) fs.rmSync(tmpDir, { recursive: true, force: true });\n } catch {}\n }\n },\n };\n}\n\n// ---------------------------------------------------------------------------\n// Bridge server\n// ---------------------------------------------------------------------------\n\ninterface BridgeResult {\n server: http.Server;\n bridgePort: number;\n getUsedTools: () => string[];\n cleanup: () => void;\n}\n\nasync function startBridgeServer(\n token: string,\n actions: Record<string, ActionEntry>,\n context: ActionRunContext | undefined,\n defaultTools: Set<string>,\n extraTools: Set<string>,\n): Promise<BridgeResult> {\n const usedTools = new Set<string>();\n const server = http.createServer((req, res) => {\n if (req.method !== \"POST\" || req.url !== \"/tool\") {\n res.writeHead(404);\n res.end(\"Not found\");\n return;\n }\n\n // Validate bearer token — must match exactly.\n const authHeader = req.headers.authorization ?? \"\";\n if (authHeader !== `Bearer ${token}`) {\n res.writeHead(401);\n res.end(\"Unauthorized\");\n return;\n }\n\n let body = \"\";\n let receivedBytes = 0;\n let rejected = false;\n req.on(\"data\", (chunk: Buffer) => {\n receivedBytes += chunk.length;\n if (receivedBytes > BRIDGE_MAX_BODY_BYTES) {\n rejected = true;\n res.writeHead(413);\n res.end(\"Payload too large\");\n req.destroy();\n return;\n }\n body += chunk.toString();\n });\n req.on(\"end\", () => {\n if (rejected) return;\n handleBridgeRequest(\n body,\n actions,\n context,\n defaultTools,\n extraTools,\n usedTools,\n res,\n );\n });\n req.on(\"error\", () => {\n res.writeHead(500);\n res.end(\"Request error\");\n });\n });\n\n await new Promise<void>((resolve, reject) => {\n server.once(\"error\", reject);\n server.listen(0, \"127.0.0.1\", () => resolve());\n });\n\n const addr = server.address() as { port: number };\n const bridgePort = addr.port;\n\n const cleanup = () => {\n try {\n server.close();\n } catch {}\n };\n\n return {\n server,\n bridgePort,\n getUsedTools: () => Array.from(usedTools).sort(),\n cleanup,\n };\n}\n\nfunction handleBridgeRequest(\n rawBody: string,\n actions: Record<string, ActionEntry>,\n context: ActionRunContext | undefined,\n defaultTools: Set<string>,\n extraTools: Set<string>,\n usedTools: Set<string>,\n res: http.ServerResponse,\n): void {\n let parsed: { tool?: string; args?: Record<string, string> };\n try {\n parsed = JSON.parse(rawBody);\n } catch {\n res.writeHead(400, { \"Content-Type\": \"application/json\" });\n res.end(JSON.stringify({ error: \"Invalid JSON body\" }));\n return;\n }\n\n const toolName = typeof parsed.tool === \"string\" ? parsed.tool.trim() : \"\";\n if (!toolName) {\n res.writeHead(400, { \"Content-Type\": \"application/json\" });\n res.end(JSON.stringify({ error: \"Missing tool name\" }));\n return;\n }\n\n // Enforce allowlist.\n const entry = actions[toolName];\n const isReadOnlyAction =\n entry?.readOnly === true &&\n entry.agentTool !== false &&\n entry.toolCallable !== false;\n if (\n !defaultTools.has(toolName) &&\n !extraTools.has(toolName) &&\n !isReadOnlyAction\n ) {\n res.writeHead(403, { \"Content-Type\": \"application/json\" });\n res.end(\n JSON.stringify({\n error: `Tool \"${toolName}\" is not an agent-exposed read-only action or sandbox bridge allowlisted tool.`,\n }),\n );\n return;\n }\n\n if (!entry) {\n res.writeHead(404, { \"Content-Type\": \"application/json\" });\n res.end(JSON.stringify({ error: `Tool \"${toolName}\" is not registered.` }));\n return;\n }\n\n const toolArgs = parsed.args ?? {};\n usedTools.add(toolName);\n // Run the tool with the parent request context so auth/org/owner resolution\n // works exactly as it does in the normal agent loop.\n entry\n .run(toolArgs, context)\n .then((result: unknown) => {\n const body =\n typeof result === \"string\" ? result : JSON.stringify(result, null, 2);\n res.writeHead(200, { \"Content-Type\": \"application/json\" });\n res.end(JSON.stringify({ result: body }));\n })\n .catch((err: unknown) => {\n const message = err instanceof Error ? err.message : String(err);\n res.writeHead(500, { \"Content-Type\": \"application/json\" });\n res.end(JSON.stringify({ error: message }));\n });\n}\n\n// ---------------------------------------------------------------------------\n// Sandbox module template\n// ---------------------------------------------------------------------------\n\n/**\n * Wrap the user's code in an ESM module that:\n * 1. Defines `providerFetch`, `providerRequest`, `providerFetchAll`,\n * `providerSearchAll`, and `webFetch` helpers via the bridge.\n * 2. Runs the user's code as top-level await in an async IIFE.\n */\nfunction buildSandboxModule(\n userCode: string,\n bridgePort: number,\n bridgeToken: string,\n): string {\n return `\nimport { createRequire } from \"node:module\";\nconst require = createRequire(import.meta.url);\n\nconst _bridgeBase = \"http://127.0.0.1:${bridgePort}/tool\";\nconst _bridgeToken = \"${bridgeToken}\";\n\nasync function _bridgeCall(tool, args) {\n const http = await import(\"node:http\");\n return new Promise((resolve, reject) => {\n const body = JSON.stringify({ tool, args });\n const options = {\n hostname: \"127.0.0.1\",\n port: ${bridgePort},\n path: \"/tool\",\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n \"Content-Length\": Buffer.byteLength(body),\n \"Authorization\": \"Bearer \" + _bridgeToken,\n },\n };\n const req = http.request(options, (res) => {\n let data = \"\";\n res.on(\"data\", (chunk) => { data += chunk; });\n res.on(\"end\", () => {\n try {\n const parsed = JSON.parse(data);\n if (parsed.error) {\n reject(new Error(parsed.error));\n } else {\n resolve(parsed.result);\n }\n } catch (e) {\n reject(new Error(\"Bridge response parse error: \" + e.message));\n }\n });\n });\n req.on(\"error\", reject);\n req.end(body);\n });\n}\n\nfunction _parseBridgeResult(rawResult) {\n if (typeof rawResult !== \"string\") return rawResult;\n try { return JSON.parse(rawResult); } catch { return rawResult; }\n}\n\n/**\n * Call any registered agent-exposed read-only app action/tool via the sandbox bridge.\n * Mutating and explicitly hidden actions are blocked by the parent bridge.\n */\nasync function appAction(name, args = {}) {\n return _parseBridgeResult(await _bridgeCall(name, args));\n}\n\nasync function providerRequest(provider, apiPath, init = {}) {\n const method = (init.method || \"GET\").toUpperCase();\n const rawResult = await _bridgeCall(\"provider-api-request\", {\n provider,\n path: apiPath,\n method,\n ...(init.query ? { query: init.query } : {}),\n ...(init.body ? { body: init.body } : {}),\n ...(init.headers ? { headers: init.headers } : {}),\n ...(init.auth ? { auth: init.auth } : {}),\n ...(init.connectionId ? { connectionId: init.connectionId } : {}),\n ...(init.accountId ? { accountId: init.accountId } : {}),\n ...(init.timeoutMs ? { timeoutMs: init.timeoutMs } : {}),\n ...(init.maxBytes ? { maxBytes: init.maxBytes } : {}),\n ...(init.stageAs ? { stageAs: init.stageAs } : {}),\n ...(init.itemsPath ? { itemsPath: init.itemsPath } : {}),\n ...(init.pagination ? { pagination: init.pagination } : {}),\n ...(init.saveToFile ? { saveToFile: init.saveToFile } : {}),\n ...(init.fetchAllPages ? { fetchAllPages: init.fetchAllPages } : {}),\n });\n return _parseBridgeResult(rawResult);\n}\n\n/**\n * Call a provider API via the authenticated provider-api-request action.\n * Returns the parsed JSON response body (or throws on error).\n */\nasync function providerFetch(provider, apiPath, init = {}) {\n const parsed = await providerRequest(provider, apiPath, init);\n // Unwrap the provider-api-request envelope ({ provider, request, response, guidance })\n // so callers get the actual response body. fetchAllPages / saveToFile results\n // (which have no \\`response\\` field) are returned as-is.\n if (parsed && typeof parsed === \"object\" && parsed.response && typeof parsed.response === \"object\") {\n const r = parsed.response;\n if (typeof r.status === \"number\" && r.status >= 400) {\n const detail = typeof r.text === \"string\" ? r.text : JSON.stringify(r.json ?? \"\");\n throw new Error(\\`Provider request failed (\\${r.status}): \\${String(detail).slice(0, 500)}\\`);\n }\n return r.json !== undefined ? r.json : r.text;\n }\n return parsed;\n}\n\nfunction _cloneJson(value) {\n if (value === undefined || value === null) return value;\n return JSON.parse(JSON.stringify(value));\n}\n\nfunction _pathParts(path) {\n if (!path || typeof path !== \"string\") return [];\n return path\n .replace(/\\\\[(\\\\d+)\\\\]/g, \".$1\")\n .split(\".\")\n .map((part) => part.trim())\n .filter(Boolean);\n}\n\nfunction _getByPath(value, path) {\n let current = value;\n for (const part of _pathParts(path)) {\n if (current === undefined || current === null) return undefined;\n current = current[part];\n }\n return current;\n}\n\nfunction _setByPath(value, path, nextValue) {\n const parts = _pathParts(path);\n if (!parts.length) return value;\n const root = value && typeof value === \"object\" ? _cloneJson(value) : {};\n let current = root;\n for (let i = 0; i < parts.length - 1; i++) {\n const part = parts[i];\n if (!current[part] || typeof current[part] !== \"object\") current[part] = {};\n current = current[part];\n }\n current[parts[parts.length - 1]] = nextValue;\n return root;\n}\n\nfunction _extractItems(page, itemsPath) {\n if (itemsPath) {\n const value = _getByPath(page, itemsPath);\n return Array.isArray(value) ? value : [];\n }\n if (Array.isArray(page)) return page;\n if (!page || typeof page !== \"object\") return [];\n for (const key of [\"data\", \"results\", \"items\", \"records\", \"rows\", \"calls\", \"callTranscripts\", \"transcripts\", \"messages\", \"tickets\", \"issues\", \"deals\", \"events\", \"notes\", \"documents\", \"entries\", \"objects\"]) {\n if (Array.isArray(page[key])) return page[key];\n }\n return [];\n}\n\nfunction _withoutProviderFetchAllOptions(init) {\n const {\n pagination: _pagination,\n fetchAllPages: _fetchAllPages,\n stageAs: _stageAs,\n itemsPath: _itemsPath,\n saveToFile: _saveToFile,\n ...rest\n } = init || {};\n return rest;\n}\n\nfunction _asArray(value) {\n if (value === undefined || value === null) return [];\n return Array.isArray(value) ? value : [value];\n}\n\nfunction _stringifySearchValue(value) {\n if (typeof value === \"string\") return value;\n if (value === undefined || value === null) return \"\";\n if (typeof value === \"number\" || typeof value === \"boolean\" || typeof value === \"bigint\") {\n return String(value);\n }\n try {\n return JSON.stringify(value);\n } catch {\n return String(value);\n }\n}\n\nfunction _collectStrings(value, basePath = \"\", out = [], limit = 5000) {\n if (out.length >= limit || value === undefined || value === null) return out;\n if (typeof value === \"string\" || typeof value === \"number\" || typeof value === \"boolean\" || typeof value === \"bigint\") {\n out.push({ path: basePath || \"$\", text: String(value) });\n return out;\n }\n if (Array.isArray(value)) {\n for (let i = 0; i < value.length && out.length < limit; i++) {\n _collectStrings(value[i], basePath ? basePath + \"[\" + i + \"]\" : \"[\" + i + \"]\", out, limit);\n }\n return out;\n }\n if (typeof value === \"object\") {\n for (const key of Object.keys(value)) {\n if (out.length >= limit) break;\n _collectStrings(value[key], basePath ? basePath + \".\" + key : key, out, limit);\n }\n }\n return out;\n}\n\nfunction _collectSearchStrings(item, textPaths, maxFieldsPerItem) {\n const paths = _asArray(textPaths).filter((path) => typeof path === \"string\" && path.trim());\n if (!paths.length) return _collectStrings(item, \"\", [], maxFieldsPerItem);\n const out = [];\n for (const path of paths) {\n const value = _getByPath(item, path);\n if (value !== undefined) _collectStrings(value, path, out, maxFieldsPerItem);\n if (out.length >= maxFieldsPerItem) break;\n }\n return out;\n}\n\nfunction _firstValueByPath(value, paths) {\n for (const path of paths) {\n const found = _getByPath(value, path);\n if (found !== undefined && found !== null && String(found) !== \"\") {\n return { path, value: found };\n }\n }\n return null;\n}\n\nconst _DEFAULT_ID_PATHS = [\n \"id\",\n \"callId\",\n \"callID\",\n \"call_id\",\n \"call.id\",\n \"call.metaData.id\",\n \"metaData.id\",\n \"metadata.id\",\n \"recordId\",\n \"record_id\",\n \"objectId\",\n \"object_id\",\n \"ticketId\",\n \"ticket_id\",\n \"issueId\",\n \"issue_id\",\n \"messageId\",\n \"message_id\",\n \"conversationId\",\n \"conversation_id\",\n \"eventId\",\n \"event_id\",\n \"documentId\",\n \"document_id\",\n \"url\",\n \"webUrl\",\n \"permalink\",\n];\n\nfunction _extractItemIdentity(item, idPaths) {\n const paths = [\n ..._asArray(idPaths).filter((path) => typeof path === \"string\" && path.trim()),\n ..._DEFAULT_ID_PATHS,\n ];\n const found = _firstValueByPath(item, paths);\n if (!found) return { id: null, idPath: null };\n return { id: _stringifySearchValue(found.value), idPath: found.path };\n}\n\nfunction _extractMetadata(item, metadataPaths) {\n const metadata = {};\n for (const path of _asArray(metadataPaths)) {\n if (typeof path !== \"string\" || !path.trim()) continue;\n const value = _getByPath(item, path);\n if (value !== undefined) metadata[path] = value;\n }\n return metadata;\n}\n\nfunction _makeSnippet(text, index, contextChars) {\n const source = String(text);\n const context = Math.max(20, Math.min(Number(contextChars) || 180, 1000));\n const start = Math.max(0, index - context);\n const end = Math.min(source.length, Math.max(index, 0) + context);\n const prefix = start > 0 ? \"...\" : \"\";\n const suffix = end < source.length ? \"...\" : \"\";\n return (prefix + source.slice(start, end) + suffix).replace(/\\\\s+/g, \" \").trim();\n}\n\nfunction _normalizeFlags(flags, caseSensitive) {\n const raw = typeof flags === \"string\" ? flags : \"\";\n const allowed = raw.replace(/[^dgimsuvy]/g, \"\");\n const withoutGlobalOrSticky = allowed.replace(/[gy]/g, \"\");\n const withCase =\n caseSensitive || /i/.test(withoutGlobalOrSticky)\n ? withoutGlobalOrSticky\n : withoutGlobalOrSticky + \"i\";\n return withCase + \"g\";\n}\n\nfunction _normalizedSearchTerms(options) {\n const explicitTerms = _asArray(options.terms)\n .map((term) => String(term).trim())\n .filter(Boolean);\n if (explicitTerms.length) return explicitTerms;\n if (options.matchMode === \"allTerms\" && typeof options.query === \"string\") {\n return options.query\n .split(/\\\\s+/)\n .map((term) => term.trim())\n .filter(Boolean);\n }\n return [];\n}\n\nfunction _findItemWideTermMatch(fields, options) {\n const terms = _normalizedSearchTerms(options);\n if (!terms.length || options.matchMode === \"anyTerm\") return null;\n const caseSensitive = Boolean(options.caseSensitive);\n const normalizedFields = fields.map((field) => ({\n field,\n haystack: caseSensitive ? String(field.text) : String(field.text).toLowerCase(),\n }));\n const termHits = terms.map((term) => {\n const searchTerm = caseSensitive ? term : term.toLowerCase();\n for (const entry of normalizedFields) {\n const index = entry.haystack.indexOf(searchTerm);\n if (index >= 0) return { term, field: entry.field, index };\n }\n return { term, field: null, index: -1 };\n });\n if (termHits.some((hit) => hit.index < 0 || !hit.field)) return null;\n const first = termHits\n .filter((hit) => hit.field)\n .sort((a, b) => {\n const fieldOrder = fields.indexOf(a.field) - fields.indexOf(b.field);\n return fieldOrder || a.index - b.index;\n })[0];\n return {\n field: first.field,\n match: {\n kind: \"allTerms\",\n query: terms.join(\" \"),\n index: first.index,\n match: first.term,\n },\n };\n}\n\nfunction _findSearchMatches(text, options, includeTerms = true) {\n const source = String(text);\n const caseSensitive = Boolean(options.caseSensitive);\n const haystack = caseSensitive ? source : source.toLowerCase();\n const maxMatchesPerField = _boundedNumber(options.maxMatchesPerField, 1000, 1, 100000);\n const matches = [];\n\n const addSubstring = (needle, label, kind) => {\n if (needle === undefined || needle === null) return;\n const rawNeedle = String(needle);\n if (!rawNeedle) return;\n const searchNeedle = caseSensitive ? rawNeedle : rawNeedle.toLowerCase();\n let from = 0;\n while (from <= haystack.length) {\n const index = haystack.indexOf(searchNeedle, from);\n if (index < 0) break;\n matches.push({ kind, query: label ?? rawNeedle, index, match: source.slice(index, index + rawNeedle.length) });\n from = index + Math.max(1, searchNeedle.length);\n if (matches.length >= maxMatchesPerField) break;\n }\n };\n\n if (options.regex) {\n try {\n const regex = new RegExp(String(options.regex), _normalizeFlags(options.regexFlags, caseSensitive));\n let match;\n while ((match = regex.exec(source)) && typeof match.index === \"number\") {\n matches.push({ kind: \"regex\", query: String(options.regex), index: match.index, match: match[0] });\n if (matches.length >= maxMatchesPerField) break;\n if (match[0] === \"\") regex.lastIndex += 1;\n }\n } catch (err) {\n throw new Error(\"providerSearchAll invalid regex: \" + (err?.message || err));\n }\n }\n\n for (const query of _asArray(options.query).concat(_asArray(options.queries))) {\n addSubstring(query, String(query), \"query\");\n }\n\n const terms = includeTerms ? _normalizedSearchTerms(options) : [];\n if (terms.length) {\n const termHits = terms\n .map((term) => {\n const searchTerm = caseSensitive ? term : term.toLowerCase();\n const index = haystack.indexOf(searchTerm);\n return { term, index };\n })\n .filter((hit) => hit.index >= 0);\n const mode = options.matchMode === \"anyTerm\" ? \"anyTerm\" : \"allTerms\";\n if ((mode === \"allTerms\" && termHits.length === terms.length) || (mode === \"anyTerm\" && termHits.length > 0)) {\n const first = termHits.sort((a, b) => a.index - b.index)[0];\n matches.push({ kind: mode, query: terms.join(\" \"), index: first.index, match: first.term });\n }\n }\n\n return matches.sort((a, b) => a.index - b.index);\n}\n\nfunction _boundedNumber(value, defaultValue, min, max) {\n const parsed = Number(value);\n const finite = Number.isFinite(parsed) ? parsed : defaultValue;\n return Math.max(min, Math.min(finite, max));\n}\n\nfunction _hitKey(identity, path, query, index, pageIndex, pageItemIndex) {\n const itemKey =\n identity.id !== null && identity.id !== undefined\n ? \"id:\" + identity.id\n : \"page:\" + String(pageIndex) + \":\" + String(pageItemIndex);\n return [itemKey, path ?? \"\", query ?? \"\", String(index ?? \"\")].join(\"\\\\n\");\n}\n\n/**\n * Stream pages from a provider API and search item text structurally. This is\n * for broad mention searches and absence checks where keeping every raw page\n * in memory or hand-parsing JSON strings is brittle.\n */\nasync function providerSearchAll(provider, apiPath, init = {}, options = {}) {\n const pagination = init.pagination || init.fetchAllPages || {};\n const itemsPath = pagination.itemsPath || init.itemsPath || options.itemsPath;\n const cursorPath = pagination.nextCursorPath || pagination.cursorPath;\n const maxPagesRaw = Number(pagination.maxPages || init.maxPages || options.maxPages || 100);\n const maxPages = Math.max(1, Math.min(Number.isFinite(maxPagesRaw) ? maxPagesRaw : 100, 500));\n const maxHits = _boundedNumber(options.maxHits, 100, 1, 5000);\n const maxHitsPerItem = _boundedNumber(options.maxHitsPerItem, 3, 1, 100);\n const maxFieldsPerItem = _boundedNumber(options.maxFieldsPerItem, 5000, 1, 50000);\n const contextChars = options.contextChars ?? options.snippetChars ?? 180;\n const baseInit = _withoutProviderFetchAllOptions(init);\n let query = _cloneJson(init.query || {});\n let body = _cloneJson(init.body);\n let pageNumber = Number(pagination.startPage || 1);\n let offset = Number(pagination.startOffset || 0);\n let lastCursor = null;\n let stoppedReason = \"completed\";\n let itemCount = 0;\n let matchedItemCount = 0;\n let totalHitCount = 0;\n const hits = [];\n const seenHitKeys = new Set();\n let pageIndex = 0;\n\n for (; pageIndex < maxPages; pageIndex++) {\n if (pagination.pageParam) query = { ...(query || {}), [pagination.pageParam]: pageNumber };\n if (pagination.offsetParam) query = { ...(query || {}), [pagination.offsetParam]: offset };\n\n const page = await providerFetch(provider, apiPath, {\n ...baseInit,\n query,\n ...(body !== undefined ? { body } : {}),\n });\n const nextCursor = cursorPath ? _getByPath(page, cursorPath) : undefined;\n const hasNextCursor =\n nextCursor !== undefined && nextCursor !== null && String(nextCursor) !== \"\";\n if (hasNextCursor && lastCursor !== null && String(nextCursor) === String(lastCursor)) {\n stoppedReason = \"repeated-cursor\";\n break;\n }\n\n const pageItems = _extractItems(page, itemsPath);\n itemCount += pageItems.length;\n\n for (let pageItemIndex = 0; pageItemIndex < pageItems.length; pageItemIndex++) {\n const item = pageItems[pageItemIndex];\n const identity = _extractItemIdentity(item, options.idPaths);\n const metadata = _extractMetadata(item, options.metadataPaths);\n const fields = _collectSearchStrings(item, options.textPaths, maxFieldsPerItem);\n let storedItemHitCount = 0;\n let itemMatched = false;\n\n const addHit = (field, match) => {\n const key = _hitKey(identity, field.path, match.query, match.index, pageIndex, pageItemIndex);\n if (seenHitKeys.has(key)) return false;\n seenHitKeys.add(key);\n totalHitCount += 1;\n if (!itemMatched) {\n matchedItemCount += 1;\n itemMatched = true;\n }\n if (hits.length < maxHits && storedItemHitCount < maxHitsPerItem) {\n storedItemHitCount += 1;\n hits.push({\n id: identity.id,\n idPath: identity.idPath,\n pageIndex,\n pageItemIndex,\n itemIndex: itemCount - pageItems.length + pageItemIndex,\n path: field.path,\n kind: match.kind,\n query: match.query,\n match: match.match,\n snippet: _makeSnippet(field.text, match.index, contextChars),\n ...(Object.keys(metadata).length ? { metadata } : {}),\n });\n }\n return true;\n };\n\n const itemWideTermMatch = _findItemWideTermMatch(fields, options);\n if (itemWideTermMatch) {\n addHit(itemWideTermMatch.field, itemWideTermMatch.match);\n }\n\n for (const field of fields) {\n const fieldMatches = _findSearchMatches(field.text, options, !itemWideTermMatch);\n for (const match of fieldMatches) {\n addHit(field, match);\n }\n }\n }\n\n if (hasNextCursor) {\n lastCursor = nextCursor;\n if (pagination.cursorBodyPath) {\n body = _setByPath(body || {}, pagination.cursorBodyPath, nextCursor);\n } else if (pagination.cursorParam) {\n query = { ...(query || {}), [pagination.cursorParam]: nextCursor };\n } else {\n stoppedReason = \"cursor-found-without-destination\";\n break;\n }\n continue;\n }\n\n lastCursor = null;\n if (pagination.pageParam) {\n if (pageItems.length === 0) {\n stoppedReason = \"empty-page\";\n break;\n }\n pageNumber += 1;\n continue;\n }\n if (pagination.offsetParam) {\n if (pageItems.length === 0) {\n stoppedReason = \"empty-page\";\n break;\n }\n const step = Number(pagination.pageSize || pageItems.length);\n if (!Number.isFinite(step) || step <= 0) {\n stoppedReason = \"invalid-page-size\";\n break;\n }\n offset += step;\n if (pagination.pageSize && pageItems.length < Number(pagination.pageSize)) {\n stoppedReason = \"short-page\";\n break;\n }\n continue;\n }\n\n break;\n }\n\n const pageCount = pageIndex + (pageIndex < maxPages ? 1 : 0);\n const hitPageOrOffsetLimit =\n Boolean(pagination.pageParam || pagination.offsetParam) &&\n stoppedReason === \"completed\" &&\n pageCount >= maxPages;\n const hasMore =\n stoppedReason === \"cursor-found-without-destination\" ||\n (lastCursor !== null && pageCount >= maxPages) || hitPageOrOffsetLimit;\n if (hasMore && stoppedReason === \"completed\") stoppedReason = \"max-pages\";\n\n return {\n hits,\n hitCount: hits.length,\n totalHitCount,\n truncatedHits: totalHitCount > hits.length,\n matchedItemCount,\n itemCount,\n pageCount,\n hasMore,\n lastCursor,\n stoppedReason,\n searched: {\n provider,\n path: apiPath,\n itemsPath: itemsPath || null,\n textPaths: _asArray(options.textPaths),\n idPaths: _asArray(options.idPaths),\n query: options.query ?? null,\n queries: _asArray(options.queries),\n terms: _asArray(options.terms),\n regex: options.regex ?? null,\n matchMode: options.matchMode || (options.terms ? \"allTerms\" : \"query\"),\n caseSensitive: Boolean(options.caseSensitive),\n },\n };\n}\n\n/**\n * Fetch every page from a provider API using generic cursor, page-number, or\n * offset pagination. Prefer this inside run-code when the answer depends on a\n * broad provider corpus rather than a single bounded request.\n */\nasync function providerFetchAll(provider, apiPath, init = {}) {\n const pagination = init.pagination || init.fetchAllPages || {};\n const itemsPath = pagination.itemsPath || init.itemsPath;\n const cursorPath = pagination.nextCursorPath || pagination.cursorPath;\n const maxPagesRaw = Number(pagination.maxPages || init.maxPages || 50);\n const maxPages = Math.max(1, Math.min(Number.isFinite(maxPagesRaw) ? maxPagesRaw : 50, 200));\n const baseInit = _withoutProviderFetchAllOptions(init);\n let query = _cloneJson(init.query || {});\n let body = _cloneJson(init.body);\n let pageNumber = Number(pagination.startPage || 1);\n let offset = Number(pagination.startOffset || 0);\n const pages = [];\n const items = [];\n let lastCursor = null;\n let stoppedReason = \"completed\";\n\n for (let pageIndex = 0; pageIndex < maxPages; pageIndex++) {\n if (pagination.pageParam) {\n query = { ...(query || {}), [pagination.pageParam]: pageNumber };\n }\n if (pagination.offsetParam) {\n query = { ...(query || {}), [pagination.offsetParam]: offset };\n }\n\n const page = await providerFetch(provider, apiPath, {\n ...baseInit,\n query,\n ...(body !== undefined ? { body } : {}),\n });\n pages.push(page);\n const pageItems = _extractItems(page, itemsPath);\n items.push(...pageItems);\n\n const nextCursor = cursorPath ? _getByPath(page, cursorPath) : undefined;\n if (nextCursor !== undefined && nextCursor !== null && String(nextCursor) !== \"\") {\n if (lastCursor !== null && String(nextCursor) === String(lastCursor)) {\n stoppedReason = \"repeated-cursor\";\n break;\n }\n lastCursor = nextCursor;\n if (pagination.cursorBodyPath) {\n body = _setByPath(body || {}, pagination.cursorBodyPath, nextCursor);\n } else if (pagination.cursorParam) {\n query = { ...(query || {}), [pagination.cursorParam]: nextCursor };\n } else {\n stoppedReason = \"cursor-found-without-destination\";\n break;\n }\n continue;\n }\n\n lastCursor = null;\n if (pagination.pageParam) {\n if (pageItems.length === 0) {\n stoppedReason = \"empty-page\";\n break;\n }\n pageNumber += 1;\n continue;\n }\n if (pagination.offsetParam) {\n if (pageItems.length === 0) {\n stoppedReason = \"empty-page\";\n break;\n }\n const step = Number(pagination.pageSize || pageItems.length);\n if (!Number.isFinite(step) || step <= 0) {\n stoppedReason = \"invalid-page-size\";\n break;\n }\n offset += step;\n if (pagination.pageSize && pageItems.length < Number(pagination.pageSize)) {\n stoppedReason = \"short-page\";\n break;\n }\n continue;\n }\n\n break;\n }\n\n const hitPageOrOffsetLimit =\n Boolean(pagination.pageParam || pagination.offsetParam) &&\n stoppedReason === \"completed\" &&\n pages.length >= maxPages;\n const hasMore =\n (lastCursor !== null && pages.length >= maxPages) || hitPageOrOffsetLimit;\n if (hasMore) stoppedReason = \"max-pages\";\n return {\n items,\n pages,\n pageCount: pages.length,\n itemCount: items.length,\n hasMore,\n lastCursor,\n stoppedReason,\n };\n}\n\n/**\n * Make an outbound HTTP request via the web-request action.\n * Returns an object \\`{ status, body }\\` where \\`body\\` is the response text.\n */\nasync function webFetch(url, init = {}) {\n const method = (init.method || \"GET\").toUpperCase();\n const rawResult = await _bridgeCall(\"web-request\", {\n url,\n method,\n ...(init.headers ? { headers: typeof init.headers === \"string\" ? init.headers : JSON.stringify(init.headers) } : {}),\n ...(init.body ? { body: typeof init.body === \"string\" ? init.body : JSON.stringify(init.body) } : {}),\n });\n // rawResult is \"HTTP <status> <statusText>\\\\n\\\\n<body>\"\n const statusMatch = typeof rawResult === \"string\" ? rawResult.match(/^HTTP (\\\\d+) [^\\\\n]*\\\\n\\\\n/) : null;\n if (statusMatch) {\n return {\n status: Number(statusMatch[1]),\n body: rawResult.slice(statusMatch[0].length),\n };\n }\n return { status: 0, body: rawResult };\n}\n\n/**\n * Read a Resources-backed workspace file by path. Returns the file content as\n * a string, or null if not found.\n * Supports optional offset and maxChars for paging large files.\n */\nasync function workspaceRead(path, opts = {}) {\n const parsed = await workspaceReadMeta(path, opts);\n if (parsed && parsed.ok === false) return null;\n return parsed && typeof parsed.content === \"string\" ? parsed.content : null;\n}\n\n/**\n * Read a workspace file by path and return the full metadata envelope.\n * Use this when offset/maxChars paging or truncation status matters.\n */\nasync function workspaceReadMeta(path, opts = {}) {\n const rawResult = await _bridgeCall(\"workspace-files\", {\n action: \"read\",\n path,\n ...(opts.offset !== undefined ? { offset: opts.offset } : {}),\n ...(opts.maxChars !== undefined ? { maxChars: opts.maxChars } : {}),\n });\n return _parseBridgeResult(rawResult);\n}\n\n/**\n * Write (create or overwrite) a workspace file. Use \\`scratch/...\\` for\n * temporary staging files.\n * \\`content\\` must be a string. Returns metadata { path, sizeBytes, updatedAt }.\n */\nasync function workspaceWrite(path, content, contentType = \"text/plain\") {\n const rawResult = await _bridgeCall(\"workspace-files\", {\n action: \"write\",\n path,\n content: typeof content === \"string\" ? content : JSON.stringify(content),\n contentType,\n });\n try { return typeof rawResult === \"string\" ? JSON.parse(rawResult) : rawResult; } catch { return rawResult; }\n}\n\n/**\n * Append text to a workspace file (creates if absent).\n */\nasync function workspaceAppend(path, content) {\n const rawResult = await _bridgeCall(\"workspace-files\", {\n action: \"append\",\n path,\n content: typeof content === \"string\" ? content : JSON.stringify(content),\n });\n try { return typeof rawResult === \"string\" ? JSON.parse(rawResult) : rawResult; } catch { return rawResult; }\n}\n\n/**\n * List workspace files, optionally filtered by path prefix.\n * Returns an array of { path, sizeBytes, contentType, updatedAt }.\n */\nasync function workspaceList(prefix) {\n const rawResult = await _bridgeCall(\"workspace-files\", {\n action: \"list\",\n ...(prefix ? { path: prefix } : {}),\n });\n const parsed = typeof rawResult === \"string\" ? JSON.parse(rawResult) : rawResult;\n if (parsed && Array.isArray(parsed.files)) return parsed.files;\n if (Array.isArray(parsed)) return parsed;\n throw new Error(\"workspaceList: unexpected result shape: \" + JSON.stringify(parsed).slice(0, 200));\n}\n\n// Run user code\n(async () => {\n${userCode}\n})().catch((err) => {\n console.error(\"Unhandled error:\", err?.message ?? String(err));\n process.exit(1);\n});\n`;\n}\n"]}
1
+ {"version":3,"file":"run-code.js","sourceRoot":"","sources":["../../src/coding-tools/run-code.ts"],"names":[],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;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EAuwBtB,QAAQ;;;;;CAKT,CAAC;AACF,CAAC","sourcesContent":["/**\n * Sandboxed JavaScript execution tool for the agent.\n *\n * Executes user-supplied JavaScript in an isolated child process with:\n * - A scrubbed environment (no app secrets or env vars; only PATH/HOME/TMPDIR).\n * - A fresh temporary working directory.\n * - An ephemeral bridge HTTP server on 127.0.0.1 so the child can call\n * allowlisted registered tools (provider-api-request, web-request, etc.)\n * with the same request context as the parent — without leaking secrets.\n *\n * Security notes:\n * - The bridge token is a 32-byte random hex string generated per invocation.\n * - The bridge binds to 127.0.0.1 only; no external exposure.\n * - The allowlist of callable bridge tools is enforced server-side.\n * - Secret values are NEVER included in the env passed to the child.\n * - When the Node permission model is available (`--permission`, or\n * `--experimental-permission` on Node 20), the child is denied filesystem\n * access outside its own temp dir, child processes, workers, and native\n * addons. Outbound network from the child is NOT blocked by the permission\n * model; the env scrub means such requests carry no credentials, and all\n * authenticated calls must go through the bridge (which applies the\n * registered tools' host allowlists and SSRF guards).\n *\n * The actual execution is delegated to a pluggable `SandboxAdapter` (see\n * `./sandbox`). The default `LocalChildProcessAdapter` preserves the spawned\n * child-process behavior described above; a remote/durable adapter can be\n * plugged in via `registerSandboxAdapter()` / `AGENT_NATIVE_SANDBOX` without\n * changing this file. The bridge, env scrub, module building, and output\n * formatting stay here in the parent regardless of adapter.\n */\n\nimport crypto from \"node:crypto\";\nimport http from \"node:http\";\n\nimport type { ActionEntry } from \"../agent/production-agent.js\";\nimport type { ActionRunContext } from \"../action.js\";\nimport { getSandboxAdapter } from \"./sandbox/index.js\";\n\nconst DEFAULT_TIMEOUT_MS = 120_000;\nconst MAX_TIMEOUT_MS = 600_000;\nconst DEFAULT_MAX_OUTPUT_CHARS = 50_000;\nconst MAX_OUTPUT_CHARS = 200_000;\n/** Hard cap on bridge request bodies so sandboxed code can't exhaust parent memory. */\nconst BRIDGE_MAX_BODY_BYTES = 10 * 1024 * 1024;\n\n/** Tools callable via the sandbox bridge by default. */\nconst DEFAULT_BRIDGE_TOOLS = new Set([\n \"provider-api-request\",\n \"provider-api-docs\",\n \"provider-api-catalog\",\n \"web-request\",\n \"workspace-files\",\n]);\n\nexport interface RunCodeOptions {\n /**\n * Extra tool names (beyond the default set) that the sandbox bridge will\n * forward to the registered action registry.\n */\n bridgeTools?: string[];\n}\n\n/**\n * Create a `run-code` ActionEntry.\n *\n * @param getActions Supplier that returns the current action registry (called\n * at invocation time so updates are reflected).\n * @param opts Optional configuration.\n */\nexport function createRunCodeEntry(\n getActions: () => Record<string, ActionEntry>,\n opts: RunCodeOptions = {},\n): ActionEntry {\n const extraBridgeTools = new Set(opts.bridgeTools ?? []);\n\n return {\n readOnly: true,\n // Allow a generous per-call timeout so large data-processing jobs don't hit\n // the agent-loop's default 60 s cap.\n timeoutMs: MAX_TIMEOUT_MS,\n maxResultChars: MAX_OUTPUT_CHARS,\n tool: {\n description: [\n \"Execute JavaScript (Node.js, ESM, top-level await supported) in an isolated sandbox.\",\n \"Use this to fetch, join, aggregate, and reduce large datasets, returning only printed output to the conversation.\",\n \"The sandbox runs with a scrubbed environment (no secrets) and, where the Node permission model is available, no filesystem access outside its own temp dir, no child processes, and no workers. Authenticated calls must go through the provided globals; direct network requests carry no credentials. Note: isolation is process-level (env scrub + Node permission model), not an OS-level container — outbound network from sandbox code is not blocked.\",\n \"Available globals:\",\n \" - `appAction(name, args?)` — call any registered agent-exposed read-only app action/tool and get its parsed result.\",\n \" Use this to loop over app data readers and compose multi-source analyses without forcing every intermediate result into chat.\",\n \" - `providerFetch(provider, path, init?)` — authenticated call to a registered provider via the provider-api-request action.\",\n \" Returns the parsed JSON result (or throws on error).\",\n \" Supports stageAs/saveToFile/fetchAllPages; use cursorBodyPath for POST-body pagination.\",\n \" Example: `const data = await providerFetch('<provider-id>', '/records', { query: { limit: 100 } });`\",\n \" - `providerRequest(provider, path, init?)` — same authenticated call, but returns the full provider-api envelope with request, response status/headers, truncation, and body metadata.\",\n \" - `providerFetchAll(provider, path, init?)` — generic pagination helper for cursor, page, and offset APIs. Pass `pagination: { itemsPath, cursorPath or nextCursorPath, cursorParam or cursorBodyPath, pageParam, offsetParam, pageSize, maxPages }`. Returns `{ items, pages, pageCount, itemCount, hasMore, lastCursor, stoppedReason }`.\",\n \" - `providerSearchAll(provider, path, init?, options?)` — streaming search helper for broad provider corpora such as transcripts, messages, tickets, issues, notes, events, or documents. Use this before hand-written loops when searching many provider records for terms/phrases/regexes or proving absence. Pass the same `pagination` config as `providerFetchAll`, plus options like `{ query, queries, terms, regex, textPaths, idPaths, metadataPaths, maxHits }`. Returns structured hits with item ids, paths, snippets, page/item indexes, and coverage fields (`pageCount`, `itemCount`, `hasMore`, `stoppedReason`).\",\n \" - `webFetch(url, init?)` — outbound HTTP request via the web-request action.\",\n \" Returns `{ status, body }` where body is the response text.\",\n \" Example: `const { body } = await webFetch('https://api.example.com/data');`\",\n \" - `workspaceRead(path, opts?)` — read a Resources-backed workspace file by path. Returns content string or null. opts: { offset?, maxChars? }.\",\n \" - `workspaceReadMeta(path, opts?)` — read a workspace file with metadata such as sizeBytes, truncated, and nextOffset.\",\n \" - `workspaceWrite(path, content, contentType?)` — create or overwrite a workspace file. Use `scratch/...` for temporary staging; use durable folders only for files the user should keep.\",\n \" - `workspaceAppend(path, content)` — append text to a workspace file.\",\n \" - `workspaceList(prefix?)` — list workspace files, returns [{ path, sizeBytes, contentType, updatedAt }].\",\n \"Print results with `console.log()`; only stdout+stderr are returned.\",\n \"Timeout defaults to 120 s (max 600 s). Output is truncated to 50 000 chars by default (max 200 000).\",\n ].join(\" \"),\n parameters: {\n type: \"object\",\n properties: {\n code: {\n type: \"string\",\n description:\n \"JavaScript source to execute. ESM syntax, top-level await allowed.\",\n },\n timeoutMs: {\n type: \"number\",\n description: `Execution timeout in milliseconds. Default: ${DEFAULT_TIMEOUT_MS}. Max: ${MAX_TIMEOUT_MS}.`,\n },\n maxOutputChars: {\n type: \"number\",\n description: `Maximum combined stdout+stderr characters to return. Default: ${DEFAULT_MAX_OUTPUT_CHARS}. Max: ${MAX_OUTPUT_CHARS}.`,\n },\n },\n required: [\"code\"],\n },\n },\n run: async (args: Record<string, string>, context?: ActionRunContext) => {\n const code = typeof args.code === \"string\" ? args.code : \"\";\n if (!code.trim()) return \"Error: code is required.\";\n\n const requestedTimeout = Number(args.timeoutMs);\n const timeoutMs =\n Number.isFinite(requestedTimeout) && requestedTimeout > 0\n ? Math.min(requestedTimeout, MAX_TIMEOUT_MS)\n : DEFAULT_TIMEOUT_MS;\n\n const requestedMaxOutput = Number(args.maxOutputChars);\n const maxOutputChars =\n Number.isFinite(requestedMaxOutput) && requestedMaxOutput > 0\n ? Math.min(requestedMaxOutput, MAX_OUTPUT_CHARS)\n : DEFAULT_MAX_OUTPUT_CHARS;\n\n const actions = getActions();\n const bridgeToken = crypto.randomBytes(32).toString(\"hex\");\n\n // Start bridge server — resolves once the server is listening.\n const {\n bridgePort,\n getUsedTools,\n cleanup: cleanupBridge,\n } = await startBridgeServer(\n bridgeToken,\n actions,\n context,\n DEFAULT_BRIDGE_TOOLS,\n extraBridgeTools,\n );\n\n try {\n // Build scrubbed env — only safe POSIX vars, no secrets. The adapter\n // points TMPDIR/TEMP/TMP at the sandbox's own temp dir.\n const safeEnv: Record<string, string> = {};\n for (const key of [\n \"PATH\",\n \"HOME\",\n \"TMPDIR\",\n \"TEMP\",\n \"TMP\",\n \"LANG\",\n \"LC_ALL\",\n ]) {\n if (process.env[key]) safeEnv[key] = process.env[key]!;\n }\n\n // Delegate execution to the active sandbox adapter (local child process\n // by default; remote/durable adapters can be registered via\n // ./sandbox). The bridge, env scrub, module, and output formatting stay\n // in the parent regardless of adapter.\n const { stdout, stderr, exitCode, timedOut } =\n await getSandboxAdapter().run({\n moduleSource: buildSandboxModule(code, bridgePort, bridgeToken),\n env: safeEnv,\n timeoutMs,\n bridgePort,\n });\n\n const combined =\n [\n stdout ? `stdout:\\n${stdout}` : \"\",\n stderr ? `stderr:\\n${stderr}` : \"\",\n ]\n .filter(Boolean)\n .join(\"\\n\\n\") || \"(no output)\";\n\n const lines: string[] = [];\n if (timedOut) lines.push(`timedOut: true (${timeoutMs}ms)`);\n if (exitCode !== 0 && exitCode !== null)\n lines.push(`exitCode: ${exitCode}`);\n const usedTools = getUsedTools();\n if (usedTools.length)\n lines.push(`bridgeToolsUsed: ${usedTools.join(\", \")}`);\n lines.push(combined);\n\n const full = lines.join(\"\\n\\n\");\n if (full.length > maxOutputChars) {\n const truncated = full.slice(0, maxOutputChars);\n return `${truncated}\\n\\n...[truncated ${(full.length - maxOutputChars).toLocaleString()} chars]`;\n }\n return full;\n } finally {\n // The active sandbox adapter owns its own temp-file cleanup; the parent\n // only tears down the bridge server here.\n cleanupBridge();\n }\n },\n };\n}\n\n// ---------------------------------------------------------------------------\n// Bridge server\n// ---------------------------------------------------------------------------\n\ninterface BridgeResult {\n server: http.Server;\n bridgePort: number;\n getUsedTools: () => string[];\n cleanup: () => void;\n}\n\nasync function startBridgeServer(\n token: string,\n actions: Record<string, ActionEntry>,\n context: ActionRunContext | undefined,\n defaultTools: Set<string>,\n extraTools: Set<string>,\n): Promise<BridgeResult> {\n const usedTools = new Set<string>();\n const server = http.createServer((req, res) => {\n if (req.method !== \"POST\" || req.url !== \"/tool\") {\n res.writeHead(404);\n res.end(\"Not found\");\n return;\n }\n\n // Validate bearer token — must match exactly.\n const authHeader = req.headers.authorization ?? \"\";\n if (authHeader !== `Bearer ${token}`) {\n res.writeHead(401);\n res.end(\"Unauthorized\");\n return;\n }\n\n let body = \"\";\n let receivedBytes = 0;\n let rejected = false;\n req.on(\"data\", (chunk: Buffer) => {\n receivedBytes += chunk.length;\n if (receivedBytes > BRIDGE_MAX_BODY_BYTES) {\n rejected = true;\n res.writeHead(413);\n res.end(\"Payload too large\");\n req.destroy();\n return;\n }\n body += chunk.toString();\n });\n req.on(\"end\", () => {\n if (rejected) return;\n handleBridgeRequest(\n body,\n actions,\n context,\n defaultTools,\n extraTools,\n usedTools,\n res,\n );\n });\n req.on(\"error\", () => {\n res.writeHead(500);\n res.end(\"Request error\");\n });\n });\n\n await new Promise<void>((resolve, reject) => {\n server.once(\"error\", reject);\n server.listen(0, \"127.0.0.1\", () => resolve());\n });\n\n const addr = server.address() as { port: number };\n const bridgePort = addr.port;\n\n const cleanup = () => {\n try {\n server.close();\n } catch {}\n };\n\n return {\n server,\n bridgePort,\n getUsedTools: () => Array.from(usedTools).sort(),\n cleanup,\n };\n}\n\nfunction handleBridgeRequest(\n rawBody: string,\n actions: Record<string, ActionEntry>,\n context: ActionRunContext | undefined,\n defaultTools: Set<string>,\n extraTools: Set<string>,\n usedTools: Set<string>,\n res: http.ServerResponse,\n): void {\n let parsed: { tool?: string; args?: Record<string, string> };\n try {\n parsed = JSON.parse(rawBody);\n } catch {\n res.writeHead(400, { \"Content-Type\": \"application/json\" });\n res.end(JSON.stringify({ error: \"Invalid JSON body\" }));\n return;\n }\n\n const toolName = typeof parsed.tool === \"string\" ? parsed.tool.trim() : \"\";\n if (!toolName) {\n res.writeHead(400, { \"Content-Type\": \"application/json\" });\n res.end(JSON.stringify({ error: \"Missing tool name\" }));\n return;\n }\n\n // Enforce allowlist.\n const entry = actions[toolName];\n const isReadOnlyAction =\n entry?.readOnly === true &&\n entry.agentTool !== false &&\n entry.toolCallable !== false;\n if (\n !defaultTools.has(toolName) &&\n !extraTools.has(toolName) &&\n !isReadOnlyAction\n ) {\n res.writeHead(403, { \"Content-Type\": \"application/json\" });\n res.end(\n JSON.stringify({\n error: `Tool \"${toolName}\" is not an agent-exposed read-only action or sandbox bridge allowlisted tool.`,\n }),\n );\n return;\n }\n\n if (!entry) {\n res.writeHead(404, { \"Content-Type\": \"application/json\" });\n res.end(JSON.stringify({ error: `Tool \"${toolName}\" is not registered.` }));\n return;\n }\n\n const toolArgs = parsed.args ?? {};\n usedTools.add(toolName);\n // Run the tool with the parent request context so auth/org/owner resolution\n // works exactly as it does in the normal agent loop.\n entry\n .run(toolArgs, context)\n .then((result: unknown) => {\n const body =\n typeof result === \"string\" ? result : JSON.stringify(result, null, 2);\n res.writeHead(200, { \"Content-Type\": \"application/json\" });\n res.end(JSON.stringify({ result: body }));\n })\n .catch((err: unknown) => {\n const message = err instanceof Error ? err.message : String(err);\n res.writeHead(500, { \"Content-Type\": \"application/json\" });\n res.end(JSON.stringify({ error: message }));\n });\n}\n\n// ---------------------------------------------------------------------------\n// Sandbox module template\n// ---------------------------------------------------------------------------\n\n/**\n * Wrap the user's code in an ESM module that:\n * 1. Defines `providerFetch`, `providerRequest`, `providerFetchAll`,\n * `providerSearchAll`, and `webFetch` helpers via the bridge.\n * 2. Runs the user's code as top-level await in an async IIFE.\n */\nfunction buildSandboxModule(\n userCode: string,\n bridgePort: number,\n bridgeToken: string,\n): string {\n return `\nimport { createRequire } from \"node:module\";\nconst require = createRequire(import.meta.url);\n\nconst _bridgeBase = \"http://127.0.0.1:${bridgePort}/tool\";\nconst _bridgeToken = \"${bridgeToken}\";\n\nasync function _bridgeCall(tool, args) {\n const http = await import(\"node:http\");\n return new Promise((resolve, reject) => {\n const body = JSON.stringify({ tool, args });\n const options = {\n hostname: \"127.0.0.1\",\n port: ${bridgePort},\n path: \"/tool\",\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n \"Content-Length\": Buffer.byteLength(body),\n \"Authorization\": \"Bearer \" + _bridgeToken,\n },\n };\n const req = http.request(options, (res) => {\n let data = \"\";\n res.on(\"data\", (chunk) => { data += chunk; });\n res.on(\"end\", () => {\n try {\n const parsed = JSON.parse(data);\n if (parsed.error) {\n reject(new Error(parsed.error));\n } else {\n resolve(parsed.result);\n }\n } catch (e) {\n reject(new Error(\"Bridge response parse error: \" + e.message));\n }\n });\n });\n req.on(\"error\", reject);\n req.end(body);\n });\n}\n\nfunction _parseBridgeResult(rawResult) {\n if (typeof rawResult !== \"string\") return rawResult;\n try { return JSON.parse(rawResult); } catch { return rawResult; }\n}\n\n/**\n * Call any registered agent-exposed read-only app action/tool via the sandbox bridge.\n * Mutating and explicitly hidden actions are blocked by the parent bridge.\n */\nasync function appAction(name, args = {}) {\n return _parseBridgeResult(await _bridgeCall(name, args));\n}\n\nasync function providerRequest(provider, apiPath, init = {}) {\n const method = (init.method || \"GET\").toUpperCase();\n const rawResult = await _bridgeCall(\"provider-api-request\", {\n provider,\n path: apiPath,\n method,\n ...(init.query ? { query: init.query } : {}),\n ...(init.body ? { body: init.body } : {}),\n ...(init.headers ? { headers: init.headers } : {}),\n ...(init.auth ? { auth: init.auth } : {}),\n ...(init.connectionId ? { connectionId: init.connectionId } : {}),\n ...(init.accountId ? { accountId: init.accountId } : {}),\n ...(init.timeoutMs ? { timeoutMs: init.timeoutMs } : {}),\n ...(init.maxBytes ? { maxBytes: init.maxBytes } : {}),\n ...(init.stageAs ? { stageAs: init.stageAs } : {}),\n ...(init.itemsPath ? { itemsPath: init.itemsPath } : {}),\n ...(init.pagination ? { pagination: init.pagination } : {}),\n ...(init.saveToFile ? { saveToFile: init.saveToFile } : {}),\n ...(init.fetchAllPages ? { fetchAllPages: init.fetchAllPages } : {}),\n });\n return _parseBridgeResult(rawResult);\n}\n\n/**\n * Call a provider API via the authenticated provider-api-request action.\n * Returns the parsed JSON response body (or throws on error).\n */\nasync function providerFetch(provider, apiPath, init = {}) {\n const parsed = await providerRequest(provider, apiPath, init);\n // Unwrap the provider-api-request envelope ({ provider, request, response, guidance })\n // so callers get the actual response body. fetchAllPages / saveToFile results\n // (which have no \\`response\\` field) are returned as-is.\n if (parsed && typeof parsed === \"object\" && parsed.response && typeof parsed.response === \"object\") {\n const r = parsed.response;\n if (typeof r.status === \"number\" && r.status >= 400) {\n const detail = typeof r.text === \"string\" ? r.text : JSON.stringify(r.json ?? \"\");\n throw new Error(\\`Provider request failed (\\${r.status}): \\${String(detail).slice(0, 500)}\\`);\n }\n return r.json !== undefined ? r.json : r.text;\n }\n return parsed;\n}\n\nfunction _cloneJson(value) {\n if (value === undefined || value === null) return value;\n return JSON.parse(JSON.stringify(value));\n}\n\nfunction _pathParts(path) {\n if (!path || typeof path !== \"string\") return [];\n return path\n .replace(/\\\\[(\\\\d+)\\\\]/g, \".$1\")\n .split(\".\")\n .map((part) => part.trim())\n .filter(Boolean);\n}\n\nfunction _getByPath(value, path) {\n let current = value;\n for (const part of _pathParts(path)) {\n if (current === undefined || current === null) return undefined;\n current = current[part];\n }\n return current;\n}\n\nfunction _setByPath(value, path, nextValue) {\n const parts = _pathParts(path);\n if (!parts.length) return value;\n const root = value && typeof value === \"object\" ? _cloneJson(value) : {};\n let current = root;\n for (let i = 0; i < parts.length - 1; i++) {\n const part = parts[i];\n if (!current[part] || typeof current[part] !== \"object\") current[part] = {};\n current = current[part];\n }\n current[parts[parts.length - 1]] = nextValue;\n return root;\n}\n\nfunction _extractItems(page, itemsPath) {\n if (itemsPath) {\n const value = _getByPath(page, itemsPath);\n return Array.isArray(value) ? value : [];\n }\n if (Array.isArray(page)) return page;\n if (!page || typeof page !== \"object\") return [];\n for (const key of [\"data\", \"results\", \"items\", \"records\", \"rows\", \"calls\", \"callTranscripts\", \"transcripts\", \"messages\", \"tickets\", \"issues\", \"deals\", \"events\", \"notes\", \"documents\", \"entries\", \"objects\"]) {\n if (Array.isArray(page[key])) return page[key];\n }\n return [];\n}\n\nfunction _withoutProviderFetchAllOptions(init) {\n const {\n pagination: _pagination,\n fetchAllPages: _fetchAllPages,\n stageAs: _stageAs,\n itemsPath: _itemsPath,\n saveToFile: _saveToFile,\n ...rest\n } = init || {};\n return rest;\n}\n\nfunction _asArray(value) {\n if (value === undefined || value === null) return [];\n return Array.isArray(value) ? value : [value];\n}\n\nfunction _stringifySearchValue(value) {\n if (typeof value === \"string\") return value;\n if (value === undefined || value === null) return \"\";\n if (typeof value === \"number\" || typeof value === \"boolean\" || typeof value === \"bigint\") {\n return String(value);\n }\n try {\n return JSON.stringify(value);\n } catch {\n return String(value);\n }\n}\n\nfunction _collectStrings(value, basePath = \"\", out = [], limit = 5000) {\n if (out.length >= limit || value === undefined || value === null) return out;\n if (typeof value === \"string\" || typeof value === \"number\" || typeof value === \"boolean\" || typeof value === \"bigint\") {\n out.push({ path: basePath || \"$\", text: String(value) });\n return out;\n }\n if (Array.isArray(value)) {\n for (let i = 0; i < value.length && out.length < limit; i++) {\n _collectStrings(value[i], basePath ? basePath + \"[\" + i + \"]\" : \"[\" + i + \"]\", out, limit);\n }\n return out;\n }\n if (typeof value === \"object\") {\n for (const key of Object.keys(value)) {\n if (out.length >= limit) break;\n _collectStrings(value[key], basePath ? basePath + \".\" + key : key, out, limit);\n }\n }\n return out;\n}\n\nfunction _collectSearchStrings(item, textPaths, maxFieldsPerItem) {\n const paths = _asArray(textPaths).filter((path) => typeof path === \"string\" && path.trim());\n if (!paths.length) return _collectStrings(item, \"\", [], maxFieldsPerItem);\n const out = [];\n for (const path of paths) {\n const value = _getByPath(item, path);\n if (value !== undefined) _collectStrings(value, path, out, maxFieldsPerItem);\n if (out.length >= maxFieldsPerItem) break;\n }\n return out;\n}\n\nfunction _firstValueByPath(value, paths) {\n for (const path of paths) {\n const found = _getByPath(value, path);\n if (found !== undefined && found !== null && String(found) !== \"\") {\n return { path, value: found };\n }\n }\n return null;\n}\n\nconst _DEFAULT_ID_PATHS = [\n \"id\",\n \"callId\",\n \"callID\",\n \"call_id\",\n \"call.id\",\n \"call.metaData.id\",\n \"metaData.id\",\n \"metadata.id\",\n \"recordId\",\n \"record_id\",\n \"objectId\",\n \"object_id\",\n \"ticketId\",\n \"ticket_id\",\n \"issueId\",\n \"issue_id\",\n \"messageId\",\n \"message_id\",\n \"conversationId\",\n \"conversation_id\",\n \"eventId\",\n \"event_id\",\n \"documentId\",\n \"document_id\",\n \"url\",\n \"webUrl\",\n \"permalink\",\n];\n\nfunction _extractItemIdentity(item, idPaths) {\n const paths = [\n ..._asArray(idPaths).filter((path) => typeof path === \"string\" && path.trim()),\n ..._DEFAULT_ID_PATHS,\n ];\n const found = _firstValueByPath(item, paths);\n if (!found) return { id: null, idPath: null };\n return { id: _stringifySearchValue(found.value), idPath: found.path };\n}\n\nfunction _extractMetadata(item, metadataPaths) {\n const metadata = {};\n for (const path of _asArray(metadataPaths)) {\n if (typeof path !== \"string\" || !path.trim()) continue;\n const value = _getByPath(item, path);\n if (value !== undefined) metadata[path] = value;\n }\n return metadata;\n}\n\nfunction _makeSnippet(text, index, contextChars) {\n const source = String(text);\n const context = Math.max(20, Math.min(Number(contextChars) || 180, 1000));\n const start = Math.max(0, index - context);\n const end = Math.min(source.length, Math.max(index, 0) + context);\n const prefix = start > 0 ? \"...\" : \"\";\n const suffix = end < source.length ? \"...\" : \"\";\n return (prefix + source.slice(start, end) + suffix).replace(/\\\\s+/g, \" \").trim();\n}\n\nfunction _normalizeFlags(flags, caseSensitive) {\n const raw = typeof flags === \"string\" ? flags : \"\";\n const allowed = raw.replace(/[^dgimsuvy]/g, \"\");\n const withoutGlobalOrSticky = allowed.replace(/[gy]/g, \"\");\n const withCase =\n caseSensitive || /i/.test(withoutGlobalOrSticky)\n ? withoutGlobalOrSticky\n : withoutGlobalOrSticky + \"i\";\n return withCase + \"g\";\n}\n\nfunction _normalizedSearchTerms(options) {\n const explicitTerms = _asArray(options.terms)\n .map((term) => String(term).trim())\n .filter(Boolean);\n if (explicitTerms.length) return explicitTerms;\n if (options.matchMode === \"allTerms\" && typeof options.query === \"string\") {\n return options.query\n .split(/\\\\s+/)\n .map((term) => term.trim())\n .filter(Boolean);\n }\n return [];\n}\n\nfunction _findItemWideTermMatch(fields, options) {\n const terms = _normalizedSearchTerms(options);\n if (!terms.length || options.matchMode === \"anyTerm\") return null;\n const caseSensitive = Boolean(options.caseSensitive);\n const normalizedFields = fields.map((field) => ({\n field,\n haystack: caseSensitive ? String(field.text) : String(field.text).toLowerCase(),\n }));\n const termHits = terms.map((term) => {\n const searchTerm = caseSensitive ? term : term.toLowerCase();\n for (const entry of normalizedFields) {\n const index = entry.haystack.indexOf(searchTerm);\n if (index >= 0) return { term, field: entry.field, index };\n }\n return { term, field: null, index: -1 };\n });\n if (termHits.some((hit) => hit.index < 0 || !hit.field)) return null;\n const first = termHits\n .filter((hit) => hit.field)\n .sort((a, b) => {\n const fieldOrder = fields.indexOf(a.field) - fields.indexOf(b.field);\n return fieldOrder || a.index - b.index;\n })[0];\n return {\n field: first.field,\n match: {\n kind: \"allTerms\",\n query: terms.join(\" \"),\n index: first.index,\n match: first.term,\n },\n };\n}\n\nfunction _findSearchMatches(text, options, includeTerms = true) {\n const source = String(text);\n const caseSensitive = Boolean(options.caseSensitive);\n const haystack = caseSensitive ? source : source.toLowerCase();\n const maxMatchesPerField = _boundedNumber(options.maxMatchesPerField, 1000, 1, 100000);\n const matches = [];\n\n const addSubstring = (needle, label, kind) => {\n if (needle === undefined || needle === null) return;\n const rawNeedle = String(needle);\n if (!rawNeedle) return;\n const searchNeedle = caseSensitive ? rawNeedle : rawNeedle.toLowerCase();\n let from = 0;\n while (from <= haystack.length) {\n const index = haystack.indexOf(searchNeedle, from);\n if (index < 0) break;\n matches.push({ kind, query: label ?? rawNeedle, index, match: source.slice(index, index + rawNeedle.length) });\n from = index + Math.max(1, searchNeedle.length);\n if (matches.length >= maxMatchesPerField) break;\n }\n };\n\n if (options.regex) {\n try {\n const regex = new RegExp(String(options.regex), _normalizeFlags(options.regexFlags, caseSensitive));\n let match;\n while ((match = regex.exec(source)) && typeof match.index === \"number\") {\n matches.push({ kind: \"regex\", query: String(options.regex), index: match.index, match: match[0] });\n if (matches.length >= maxMatchesPerField) break;\n if (match[0] === \"\") regex.lastIndex += 1;\n }\n } catch (err) {\n throw new Error(\"providerSearchAll invalid regex: \" + (err?.message || err));\n }\n }\n\n for (const query of _asArray(options.query).concat(_asArray(options.queries))) {\n addSubstring(query, String(query), \"query\");\n }\n\n const terms = includeTerms ? _normalizedSearchTerms(options) : [];\n if (terms.length) {\n const termHits = terms\n .map((term) => {\n const searchTerm = caseSensitive ? term : term.toLowerCase();\n const index = haystack.indexOf(searchTerm);\n return { term, index };\n })\n .filter((hit) => hit.index >= 0);\n const mode = options.matchMode === \"anyTerm\" ? \"anyTerm\" : \"allTerms\";\n if ((mode === \"allTerms\" && termHits.length === terms.length) || (mode === \"anyTerm\" && termHits.length > 0)) {\n const first = termHits.sort((a, b) => a.index - b.index)[0];\n matches.push({ kind: mode, query: terms.join(\" \"), index: first.index, match: first.term });\n }\n }\n\n return matches.sort((a, b) => a.index - b.index);\n}\n\nfunction _boundedNumber(value, defaultValue, min, max) {\n const parsed = Number(value);\n const finite = Number.isFinite(parsed) ? parsed : defaultValue;\n return Math.max(min, Math.min(finite, max));\n}\n\nfunction _hitKey(identity, path, query, index, pageIndex, pageItemIndex) {\n const itemKey =\n identity.id !== null && identity.id !== undefined\n ? \"id:\" + identity.id\n : \"page:\" + String(pageIndex) + \":\" + String(pageItemIndex);\n return [itemKey, path ?? \"\", query ?? \"\", String(index ?? \"\")].join(\"\\\\n\");\n}\n\n/**\n * Stream pages from a provider API and search item text structurally. This is\n * for broad mention searches and absence checks where keeping every raw page\n * in memory or hand-parsing JSON strings is brittle.\n */\nasync function providerSearchAll(provider, apiPath, init = {}, options = {}) {\n const pagination = init.pagination || init.fetchAllPages || {};\n const itemsPath = pagination.itemsPath || init.itemsPath || options.itemsPath;\n const cursorPath = pagination.nextCursorPath || pagination.cursorPath;\n const maxPagesRaw = Number(pagination.maxPages || init.maxPages || options.maxPages || 100);\n const maxPages = Math.max(1, Math.min(Number.isFinite(maxPagesRaw) ? maxPagesRaw : 100, 500));\n const maxHits = _boundedNumber(options.maxHits, 100, 1, 5000);\n const maxHitsPerItem = _boundedNumber(options.maxHitsPerItem, 3, 1, 100);\n const maxFieldsPerItem = _boundedNumber(options.maxFieldsPerItem, 5000, 1, 50000);\n const contextChars = options.contextChars ?? options.snippetChars ?? 180;\n const baseInit = _withoutProviderFetchAllOptions(init);\n let query = _cloneJson(init.query || {});\n let body = _cloneJson(init.body);\n let pageNumber = Number(pagination.startPage || 1);\n let offset = Number(pagination.startOffset || 0);\n let lastCursor = null;\n let stoppedReason = \"completed\";\n let itemCount = 0;\n let matchedItemCount = 0;\n let totalHitCount = 0;\n const hits = [];\n const seenHitKeys = new Set();\n let pageIndex = 0;\n\n for (; pageIndex < maxPages; pageIndex++) {\n if (pagination.pageParam) query = { ...(query || {}), [pagination.pageParam]: pageNumber };\n if (pagination.offsetParam) query = { ...(query || {}), [pagination.offsetParam]: offset };\n\n const page = await providerFetch(provider, apiPath, {\n ...baseInit,\n query,\n ...(body !== undefined ? { body } : {}),\n });\n const nextCursor = cursorPath ? _getByPath(page, cursorPath) : undefined;\n const hasNextCursor =\n nextCursor !== undefined && nextCursor !== null && String(nextCursor) !== \"\";\n if (hasNextCursor && lastCursor !== null && String(nextCursor) === String(lastCursor)) {\n stoppedReason = \"repeated-cursor\";\n break;\n }\n\n const pageItems = _extractItems(page, itemsPath);\n itemCount += pageItems.length;\n\n for (let pageItemIndex = 0; pageItemIndex < pageItems.length; pageItemIndex++) {\n const item = pageItems[pageItemIndex];\n const identity = _extractItemIdentity(item, options.idPaths);\n const metadata = _extractMetadata(item, options.metadataPaths);\n const fields = _collectSearchStrings(item, options.textPaths, maxFieldsPerItem);\n let storedItemHitCount = 0;\n let itemMatched = false;\n\n const addHit = (field, match) => {\n const key = _hitKey(identity, field.path, match.query, match.index, pageIndex, pageItemIndex);\n if (seenHitKeys.has(key)) return false;\n seenHitKeys.add(key);\n totalHitCount += 1;\n if (!itemMatched) {\n matchedItemCount += 1;\n itemMatched = true;\n }\n if (hits.length < maxHits && storedItemHitCount < maxHitsPerItem) {\n storedItemHitCount += 1;\n hits.push({\n id: identity.id,\n idPath: identity.idPath,\n pageIndex,\n pageItemIndex,\n itemIndex: itemCount - pageItems.length + pageItemIndex,\n path: field.path,\n kind: match.kind,\n query: match.query,\n match: match.match,\n snippet: _makeSnippet(field.text, match.index, contextChars),\n ...(Object.keys(metadata).length ? { metadata } : {}),\n });\n }\n return true;\n };\n\n const itemWideTermMatch = _findItemWideTermMatch(fields, options);\n if (itemWideTermMatch) {\n addHit(itemWideTermMatch.field, itemWideTermMatch.match);\n }\n\n for (const field of fields) {\n const fieldMatches = _findSearchMatches(field.text, options, !itemWideTermMatch);\n for (const match of fieldMatches) {\n addHit(field, match);\n }\n }\n }\n\n if (hasNextCursor) {\n lastCursor = nextCursor;\n if (pagination.cursorBodyPath) {\n body = _setByPath(body || {}, pagination.cursorBodyPath, nextCursor);\n } else if (pagination.cursorParam) {\n query = { ...(query || {}), [pagination.cursorParam]: nextCursor };\n } else {\n stoppedReason = \"cursor-found-without-destination\";\n break;\n }\n continue;\n }\n\n lastCursor = null;\n if (pagination.pageParam) {\n if (pageItems.length === 0) {\n stoppedReason = \"empty-page\";\n break;\n }\n pageNumber += 1;\n continue;\n }\n if (pagination.offsetParam) {\n if (pageItems.length === 0) {\n stoppedReason = \"empty-page\";\n break;\n }\n const step = Number(pagination.pageSize || pageItems.length);\n if (!Number.isFinite(step) || step <= 0) {\n stoppedReason = \"invalid-page-size\";\n break;\n }\n offset += step;\n if (pagination.pageSize && pageItems.length < Number(pagination.pageSize)) {\n stoppedReason = \"short-page\";\n break;\n }\n continue;\n }\n\n break;\n }\n\n const pageCount = pageIndex + (pageIndex < maxPages ? 1 : 0);\n const hitPageOrOffsetLimit =\n Boolean(pagination.pageParam || pagination.offsetParam) &&\n stoppedReason === \"completed\" &&\n pageCount >= maxPages;\n const hasMore =\n stoppedReason === \"cursor-found-without-destination\" ||\n (lastCursor !== null && pageCount >= maxPages) || hitPageOrOffsetLimit;\n if (hasMore && stoppedReason === \"completed\") stoppedReason = \"max-pages\";\n\n return {\n hits,\n hitCount: hits.length,\n totalHitCount,\n truncatedHits: totalHitCount > hits.length,\n matchedItemCount,\n itemCount,\n pageCount,\n hasMore,\n lastCursor,\n stoppedReason,\n searched: {\n provider,\n path: apiPath,\n itemsPath: itemsPath || null,\n textPaths: _asArray(options.textPaths),\n idPaths: _asArray(options.idPaths),\n query: options.query ?? null,\n queries: _asArray(options.queries),\n terms: _asArray(options.terms),\n regex: options.regex ?? null,\n matchMode: options.matchMode || (options.terms ? \"allTerms\" : \"query\"),\n caseSensitive: Boolean(options.caseSensitive),\n },\n };\n}\n\n/**\n * Fetch every page from a provider API using generic cursor, page-number, or\n * offset pagination. Prefer this inside run-code when the answer depends on a\n * broad provider corpus rather than a single bounded request.\n */\nasync function providerFetchAll(provider, apiPath, init = {}) {\n const pagination = init.pagination || init.fetchAllPages || {};\n const itemsPath = pagination.itemsPath || init.itemsPath;\n const cursorPath = pagination.nextCursorPath || pagination.cursorPath;\n const maxPagesRaw = Number(pagination.maxPages || init.maxPages || 50);\n const maxPages = Math.max(1, Math.min(Number.isFinite(maxPagesRaw) ? maxPagesRaw : 50, 200));\n const baseInit = _withoutProviderFetchAllOptions(init);\n let query = _cloneJson(init.query || {});\n let body = _cloneJson(init.body);\n let pageNumber = Number(pagination.startPage || 1);\n let offset = Number(pagination.startOffset || 0);\n const pages = [];\n const items = [];\n let lastCursor = null;\n let stoppedReason = \"completed\";\n\n for (let pageIndex = 0; pageIndex < maxPages; pageIndex++) {\n if (pagination.pageParam) {\n query = { ...(query || {}), [pagination.pageParam]: pageNumber };\n }\n if (pagination.offsetParam) {\n query = { ...(query || {}), [pagination.offsetParam]: offset };\n }\n\n const page = await providerFetch(provider, apiPath, {\n ...baseInit,\n query,\n ...(body !== undefined ? { body } : {}),\n });\n pages.push(page);\n const pageItems = _extractItems(page, itemsPath);\n items.push(...pageItems);\n\n const nextCursor = cursorPath ? _getByPath(page, cursorPath) : undefined;\n if (nextCursor !== undefined && nextCursor !== null && String(nextCursor) !== \"\") {\n if (lastCursor !== null && String(nextCursor) === String(lastCursor)) {\n stoppedReason = \"repeated-cursor\";\n break;\n }\n lastCursor = nextCursor;\n if (pagination.cursorBodyPath) {\n body = _setByPath(body || {}, pagination.cursorBodyPath, nextCursor);\n } else if (pagination.cursorParam) {\n query = { ...(query || {}), [pagination.cursorParam]: nextCursor };\n } else {\n stoppedReason = \"cursor-found-without-destination\";\n break;\n }\n continue;\n }\n\n lastCursor = null;\n if (pagination.pageParam) {\n if (pageItems.length === 0) {\n stoppedReason = \"empty-page\";\n break;\n }\n pageNumber += 1;\n continue;\n }\n if (pagination.offsetParam) {\n if (pageItems.length === 0) {\n stoppedReason = \"empty-page\";\n break;\n }\n const step = Number(pagination.pageSize || pageItems.length);\n if (!Number.isFinite(step) || step <= 0) {\n stoppedReason = \"invalid-page-size\";\n break;\n }\n offset += step;\n if (pagination.pageSize && pageItems.length < Number(pagination.pageSize)) {\n stoppedReason = \"short-page\";\n break;\n }\n continue;\n }\n\n break;\n }\n\n const hitPageOrOffsetLimit =\n Boolean(pagination.pageParam || pagination.offsetParam) &&\n stoppedReason === \"completed\" &&\n pages.length >= maxPages;\n const hasMore =\n (lastCursor !== null && pages.length >= maxPages) || hitPageOrOffsetLimit;\n if (hasMore) stoppedReason = \"max-pages\";\n return {\n items,\n pages,\n pageCount: pages.length,\n itemCount: items.length,\n hasMore,\n lastCursor,\n stoppedReason,\n };\n}\n\n/**\n * Make an outbound HTTP request via the web-request action.\n * Returns an object \\`{ status, body }\\` where \\`body\\` is the response text.\n */\nasync function webFetch(url, init = {}) {\n const method = (init.method || \"GET\").toUpperCase();\n const rawResult = await _bridgeCall(\"web-request\", {\n url,\n method,\n ...(init.headers ? { headers: typeof init.headers === \"string\" ? init.headers : JSON.stringify(init.headers) } : {}),\n ...(init.body ? { body: typeof init.body === \"string\" ? init.body : JSON.stringify(init.body) } : {}),\n });\n // rawResult is \"HTTP <status> <statusText>\\\\n\\\\n<body>\"\n const statusMatch = typeof rawResult === \"string\" ? rawResult.match(/^HTTP (\\\\d+) [^\\\\n]*\\\\n\\\\n/) : null;\n if (statusMatch) {\n return {\n status: Number(statusMatch[1]),\n body: rawResult.slice(statusMatch[0].length),\n };\n }\n return { status: 0, body: rawResult };\n}\n\n/**\n * Read a Resources-backed workspace file by path. Returns the file content as\n * a string, or null if not found.\n * Supports optional offset and maxChars for paging large files.\n */\nasync function workspaceRead(path, opts = {}) {\n const parsed = await workspaceReadMeta(path, opts);\n if (parsed && parsed.ok === false) return null;\n return parsed && typeof parsed.content === \"string\" ? parsed.content : null;\n}\n\n/**\n * Read a workspace file by path and return the full metadata envelope.\n * Use this when offset/maxChars paging or truncation status matters.\n */\nasync function workspaceReadMeta(path, opts = {}) {\n const rawResult = await _bridgeCall(\"workspace-files\", {\n action: \"read\",\n path,\n ...(opts.offset !== undefined ? { offset: opts.offset } : {}),\n ...(opts.maxChars !== undefined ? { maxChars: opts.maxChars } : {}),\n });\n return _parseBridgeResult(rawResult);\n}\n\n/**\n * Write (create or overwrite) a workspace file. Use \\`scratch/...\\` for\n * temporary staging files.\n * \\`content\\` must be a string. Returns metadata { path, sizeBytes, updatedAt }.\n */\nasync function workspaceWrite(path, content, contentType = \"text/plain\") {\n const rawResult = await _bridgeCall(\"workspace-files\", {\n action: \"write\",\n path,\n content: typeof content === \"string\" ? content : JSON.stringify(content),\n contentType,\n });\n try { return typeof rawResult === \"string\" ? JSON.parse(rawResult) : rawResult; } catch { return rawResult; }\n}\n\n/**\n * Append text to a workspace file (creates if absent).\n */\nasync function workspaceAppend(path, content) {\n const rawResult = await _bridgeCall(\"workspace-files\", {\n action: \"append\",\n path,\n content: typeof content === \"string\" ? content : JSON.stringify(content),\n });\n try { return typeof rawResult === \"string\" ? JSON.parse(rawResult) : rawResult; } catch { return rawResult; }\n}\n\n/**\n * List workspace files, optionally filtered by path prefix.\n * Returns an array of { path, sizeBytes, contentType, updatedAt }.\n */\nasync function workspaceList(prefix) {\n const rawResult = await _bridgeCall(\"workspace-files\", {\n action: \"list\",\n ...(prefix ? { path: prefix } : {}),\n });\n const parsed = typeof rawResult === \"string\" ? JSON.parse(rawResult) : rawResult;\n if (parsed && Array.isArray(parsed.files)) return parsed.files;\n if (Array.isArray(parsed)) return parsed;\n throw new Error(\"workspaceList: unexpected result shape: \" + JSON.stringify(parsed).slice(0, 200));\n}\n\n// Run user code\n(async () => {\n${userCode}\n})().catch((err) => {\n console.error(\"Unhandled error:\", err?.message ?? String(err));\n process.exit(1);\n});\n`;\n}\n"]}
@@ -0,0 +1,79 @@
1
+ /**
2
+ * Pluggable sandbox-adapter seam for the `run-code` tool.
3
+ *
4
+ * The `run-code` tool runs agent-supplied JavaScript in an isolated environment.
5
+ * Historically that environment was always a local spawned child process with a
6
+ * scrubbed env and the Node permission model. This interface factors the
7
+ * *execution* concern out of `run-code.ts` so the sandbox can be swapped for a
8
+ * different backend (e.g. a Docker container or a remote/durable
9
+ * Vercel-Sandbox-style runner) WITHOUT changing the calling agent code, the
10
+ * localhost bridge, the env scrub, or the output formatting.
11
+ *
12
+ * The parent process keeps ownership of everything secret-bearing: it builds the
13
+ * sandbox module, runs the localhost bridge (which holds the request context and
14
+ * applies the registered tools' host allowlists and SSRF guards), scrubs the env,
15
+ * and formats output. An adapter only receives an already-prepared, non-secret
16
+ * module source plus resource limits, and is responsible solely for *running* it
17
+ * and capturing stdout/stderr/exit status.
18
+ *
19
+ * Keeping the contract this narrow means a remote adapter inherits the same
20
+ * security posture: it never sees app secrets, only the (already env-scrubbed)
21
+ * code and the loopback bridge URL embedded in that code by the parent.
22
+ */
23
+ /** Environment variables an adapter may expose to the sandbox process. */
24
+ export type SandboxEnv = Record<string, string>;
25
+ /**
26
+ * A single sandbox execution request. The module source is fully prepared by the
27
+ * parent (`run-code.ts`): it already embeds the loopback bridge port/token and
28
+ * wraps the user's code, so an adapter treats it as an opaque program to run.
29
+ */
30
+ export interface SandboxRunRequest {
31
+ /**
32
+ * The complete ESM module source to execute. Already wraps the user's code and
33
+ * embeds the loopback bridge URL/token; the adapter does not parse or rewrite
34
+ * it.
35
+ */
36
+ moduleSource: string;
37
+ /**
38
+ * Scrubbed environment for the sandbox process. Contains only safe POSIX vars
39
+ * (PATH/HOME/TMPDIR/etc.) — never app secrets. Adapters must not augment this
40
+ * with the parent's own environment.
41
+ */
42
+ env: SandboxEnv;
43
+ /** Hard wall-clock timeout in milliseconds. The adapter must enforce it. */
44
+ timeoutMs: number;
45
+ /**
46
+ * Loopback port of the parent's bridge server. The bridge runs in the parent
47
+ * process and is reachable from the sandbox over 127.0.0.1. A remote adapter
48
+ * that cannot reach the parent's loopback interface must tunnel or proxy this
49
+ * before it can support bridge-backed globals (`appAction`, `providerFetch`,
50
+ * etc.).
51
+ */
52
+ bridgePort: number;
53
+ }
54
+ /** The result of a single sandbox execution. */
55
+ export interface SandboxRunResult {
56
+ /** Captured standard output. */
57
+ stdout: string;
58
+ /** Captured standard error. */
59
+ stderr: string;
60
+ /**
61
+ * Process exit code. `0` for clean exit, non-zero for failures, `null` when
62
+ * the process was terminated by a signal (e.g. timeout SIGKILL).
63
+ */
64
+ exitCode: number | null;
65
+ /** True when the run was killed because it exceeded `timeoutMs`. */
66
+ timedOut: boolean;
67
+ }
68
+ /**
69
+ * Contract every sandbox backend implements. The default
70
+ * `LocalChildProcessAdapter` spawns a local Node child process; a future
71
+ * Docker/remote/durable adapter implements the same method.
72
+ */
73
+ export interface SandboxAdapter {
74
+ /** Stable identifier, surfaced for diagnostics and adapter selection. */
75
+ readonly id: string;
76
+ /** Execute one prepared sandbox module and capture its output. */
77
+ run(request: SandboxRunRequest): Promise<SandboxRunResult>;
78
+ }
79
+ //# sourceMappingURL=adapter.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"adapter.d.ts","sourceRoot":"","sources":["../../../src/coding-tools/sandbox/adapter.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;GAqBG;AAEH,0EAA0E;AAC1E,MAAM,MAAM,UAAU,GAAG,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;AAEhD;;;;GAIG;AACH,MAAM,WAAW,iBAAiB;IAChC;;;;OAIG;IACH,YAAY,EAAE,MAAM,CAAC;IACrB;;;;OAIG;IACH,GAAG,EAAE,UAAU,CAAC;IAChB,4EAA4E;IAC5E,SAAS,EAAE,MAAM,CAAC;IAClB;;;;;;OAMG;IACH,UAAU,EAAE,MAAM,CAAC;CACpB;AAED,gDAAgD;AAChD,MAAM,WAAW,gBAAgB;IAC/B,gCAAgC;IAChC,MAAM,EAAE,MAAM,CAAC;IACf,+BAA+B;IAC/B,MAAM,EAAE,MAAM,CAAC;IACf;;;OAGG;IACH,QAAQ,EAAE,MAAM,GAAG,IAAI,CAAC;IACxB,oEAAoE;IACpE,QAAQ,EAAE,OAAO,CAAC;CACnB;AAED;;;;GAIG;AACH,MAAM,WAAW,cAAc;IAC7B,yEAAyE;IACzE,QAAQ,CAAC,EAAE,EAAE,MAAM,CAAC;IACpB,kEAAkE;IAClE,GAAG,CAAC,OAAO,EAAE,iBAAiB,GAAG,OAAO,CAAC,gBAAgB,CAAC,CAAC;CAC5D"}
@@ -0,0 +1,24 @@
1
+ /**
2
+ * Pluggable sandbox-adapter seam for the `run-code` tool.
3
+ *
4
+ * The `run-code` tool runs agent-supplied JavaScript in an isolated environment.
5
+ * Historically that environment was always a local spawned child process with a
6
+ * scrubbed env and the Node permission model. This interface factors the
7
+ * *execution* concern out of `run-code.ts` so the sandbox can be swapped for a
8
+ * different backend (e.g. a Docker container or a remote/durable
9
+ * Vercel-Sandbox-style runner) WITHOUT changing the calling agent code, the
10
+ * localhost bridge, the env scrub, or the output formatting.
11
+ *
12
+ * The parent process keeps ownership of everything secret-bearing: it builds the
13
+ * sandbox module, runs the localhost bridge (which holds the request context and
14
+ * applies the registered tools' host allowlists and SSRF guards), scrubs the env,
15
+ * and formats output. An adapter only receives an already-prepared, non-secret
16
+ * module source plus resource limits, and is responsible solely for *running* it
17
+ * and capturing stdout/stderr/exit status.
18
+ *
19
+ * Keeping the contract this narrow means a remote adapter inherits the same
20
+ * security posture: it never sees app secrets, only the (already env-scrubbed)
21
+ * code and the loopback bridge URL embedded in that code by the parent.
22
+ */
23
+ export {};
24
+ //# sourceMappingURL=adapter.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"adapter.js","sourceRoot":"","sources":["../../../src/coding-tools/sandbox/adapter.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;GAqBG","sourcesContent":["/**\n * Pluggable sandbox-adapter seam for the `run-code` tool.\n *\n * The `run-code` tool runs agent-supplied JavaScript in an isolated environment.\n * Historically that environment was always a local spawned child process with a\n * scrubbed env and the Node permission model. This interface factors the\n * *execution* concern out of `run-code.ts` so the sandbox can be swapped for a\n * different backend (e.g. a Docker container or a remote/durable\n * Vercel-Sandbox-style runner) WITHOUT changing the calling agent code, the\n * localhost bridge, the env scrub, or the output formatting.\n *\n * The parent process keeps ownership of everything secret-bearing: it builds the\n * sandbox module, runs the localhost bridge (which holds the request context and\n * applies the registered tools' host allowlists and SSRF guards), scrubs the env,\n * and formats output. An adapter only receives an already-prepared, non-secret\n * module source plus resource limits, and is responsible solely for *running* it\n * and capturing stdout/stderr/exit status.\n *\n * Keeping the contract this narrow means a remote adapter inherits the same\n * security posture: it never sees app secrets, only the (already env-scrubbed)\n * code and the loopback bridge URL embedded in that code by the parent.\n */\n\n/** Environment variables an adapter may expose to the sandbox process. */\nexport type SandboxEnv = Record<string, string>;\n\n/**\n * A single sandbox execution request. The module source is fully prepared by the\n * parent (`run-code.ts`): it already embeds the loopback bridge port/token and\n * wraps the user's code, so an adapter treats it as an opaque program to run.\n */\nexport interface SandboxRunRequest {\n /**\n * The complete ESM module source to execute. Already wraps the user's code and\n * embeds the loopback bridge URL/token; the adapter does not parse or rewrite\n * it.\n */\n moduleSource: string;\n /**\n * Scrubbed environment for the sandbox process. Contains only safe POSIX vars\n * (PATH/HOME/TMPDIR/etc.) — never app secrets. Adapters must not augment this\n * with the parent's own environment.\n */\n env: SandboxEnv;\n /** Hard wall-clock timeout in milliseconds. The adapter must enforce it. */\n timeoutMs: number;\n /**\n * Loopback port of the parent's bridge server. The bridge runs in the parent\n * process and is reachable from the sandbox over 127.0.0.1. A remote adapter\n * that cannot reach the parent's loopback interface must tunnel or proxy this\n * before it can support bridge-backed globals (`appAction`, `providerFetch`,\n * etc.).\n */\n bridgePort: number;\n}\n\n/** The result of a single sandbox execution. */\nexport interface SandboxRunResult {\n /** Captured standard output. */\n stdout: string;\n /** Captured standard error. */\n stderr: string;\n /**\n * Process exit code. `0` for clean exit, non-zero for failures, `null` when\n * the process was terminated by a signal (e.g. timeout SIGKILL).\n */\n exitCode: number | null;\n /** True when the run was killed because it exceeded `timeoutMs`. */\n timedOut: boolean;\n}\n\n/**\n * Contract every sandbox backend implements. The default\n * `LocalChildProcessAdapter` spawns a local Node child process; a future\n * Docker/remote/durable adapter implements the same method.\n */\nexport interface SandboxAdapter {\n /** Stable identifier, surfaced for diagnostics and adapter selection. */\n readonly id: string;\n /** Execute one prepared sandbox module and capture its output. */\n run(request: SandboxRunRequest): Promise<SandboxRunResult>;\n}\n"]}