@tangle-network/sandbox 0.55.2 → 0.57.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 (44) hide show
  1. package/README.md +25 -2
  2. package/dist/agent/index.d.ts +59 -19
  3. package/dist/agent/index.js +26 -306
  4. package/dist/agent/preview.d.ts +2 -0
  5. package/dist/agent/preview.js +74 -0
  6. package/dist/{agent-run-outcome-CWo6e5lW.d.ts → agent-run-outcome-B8PjRMLE.d.ts} +1 -1
  7. package/dist/auth/index.d.ts +1 -1
  8. package/dist/auth/index.js +1 -1
  9. package/dist/{browser-interactive-control-controller-Dv0gbFMu.js → browser-interactive-control-controller-CVGqjPgs.js} +1 -1
  10. package/dist/{browser-interactive-control-controller-BELrFH4f.d.ts → browser-interactive-control-controller-knjCl8Zp.d.ts} +1 -1
  11. package/dist/{client-B-LZQQ51.d.ts → client-BHGieo06.d.ts} +10 -4
  12. package/dist/{client-Bd8nskJA.js → client-CdbHGWiu.js} +23 -10
  13. package/dist/collaboration/index.d.ts +1 -1
  14. package/dist/collaboration/index.js +1 -1
  15. package/dist/{collaboration-DLPFc9-W.js → collaboration-CSHswAOI.js} +1 -1
  16. package/dist/core.d.ts +5 -5
  17. package/dist/core.js +3 -3
  18. package/dist/{index-ATSSTK2A.d.ts → index-C1sVorE5.d.ts} +2 -2
  19. package/dist/index.d.ts +11 -11
  20. package/dist/index.js +7 -7
  21. package/dist/intelligence/index.js +1 -1
  22. package/dist/interactive-control.d.ts +1 -1
  23. package/dist/interactive-control.js +1 -1
  24. package/dist/{local-cli-auth-BAJuMBZU.js → local-cli-auth-DfuFJCcs.js} +1 -1
  25. package/dist/mcp-local-DUT2U_y8.js +429 -0
  26. package/dist/preview-operations-Dgbi46FH.js +212 -0
  27. package/dist/preview-wJJxG42-.d.ts +72 -0
  28. package/dist/{runtime-api-DoZsOiOR.js → runtime-api-BZg34WGd.js} +10 -5
  29. package/dist/runtime.d.ts +6 -4
  30. package/dist/runtime.js +3 -3
  31. package/dist/{sandbox-DzSE1u7d.js → sandbox-C9VLoJAb.js} +107 -8
  32. package/dist/{sandbox-C7KqjY6Y.d.ts → sandbox-DWDqWnsJ.d.ts} +139 -10
  33. package/dist/tangle/index.d.ts +1 -1
  34. package/dist/tangle/index.js +1 -1
  35. package/dist/{tangle-CmpR_07-.js → tangle-Bm6H-xIM.js} +2 -2
  36. package/dist/{types-UOIM3RS6.d.ts → types-CFmeauzy.d.ts} +12 -2
  37. package/package.json +9 -4
  38. /package/dist/{abort-signal-si1WMfJb.js → abort-signal-CgFhjY_v.js} +0 -0
  39. /package/dist/{cli-auth-bundle-DUsK57rK.js → cli-auth-bundle-bRJOyaJO.js} +0 -0
  40. /package/dist/{errors-CmYPVl-k.js → errors-BkhlSDW-.js} +0 -0
  41. /package/dist/{errors-Cz23YNu2.d.ts → errors-CNsmhCen.d.ts} +0 -0
  42. /package/dist/{index-BWiG3Vcw.d.ts → index-BN7zNEUB.d.ts} +0 -0
  43. /package/dist/{index-BfVsF6yU.d.ts → index-X4EEZlMi.d.ts} +0 -0
  44. /package/dist/{terminal-stream-CcaBTVg3.d.ts → terminal-stream-BW4veIsI.d.ts} +0 -0
package/README.md CHANGED
@@ -308,6 +308,10 @@ Renew application credentials before dispatch when reusing a sandbox:
308
308
  await box.setRuntimeEnv({ APP_CAPABILITY_TOKEN: freshWorkspaceToken });
309
309
  ```
310
310
 
311
+ Pass `{ ttlMs }` for short-lived credentials. The runtime removes each injected
312
+ key after that duration; refreshing the key starts a new lifetime. Older
313
+ runtimes reject expiring credentials before injection.
314
+
311
315
  New child processes and profile secret references use the updated values.
312
316
  Existing processes retain their environment.
313
317
  Updates do not change durable creation configuration, so repeat renewal after resume.
@@ -427,6 +431,8 @@ Use `fs.upload()` for local files or `fs.uploadData()` for in-memory content lar
427
431
 
428
432
  The instance also exposes `git`, `tools`, `process`, `terminals`, `network`, `egress`, `previewLinks`, `images`, and `backend` capability clients.
429
433
  Unsupported capabilities fail with a typed SDK error.
434
+ `box.images.publish()` returns `IN_BOX_DOCKER_UNAVAILABLE` with HTTP 409 when the sandbox has no in-box Docker.
435
+ Build and push the image outside the sandbox, then create a sandbox from its registry reference.
430
436
 
431
437
  ## Prompts
432
438
 
@@ -566,6 +572,11 @@ try {
566
572
 
567
573
  Fleet policies are checked before provisioning and do not replace account quotas.
568
574
 
575
+ Agent fleets retain the default harness, model, and profile in each agent's specification.
576
+ Per-agent declarations override those defaults.
577
+ Fetched fleets preserve these settings when they run agent turns.
578
+ Model API keys and authentication files stay outside fleet metadata.
579
+
569
580
  ## Batch jobs
570
581
 
571
582
  Use `runBatch()` for parallel tasks that do not need stable fleet membership.
@@ -647,7 +658,7 @@ Deleting the base sandbox remains a separate cleanup step.
647
658
 
648
659
  ## Phone lines
649
660
 
650
- A line gives a sandbox a messaging address that Tangle Hub receives on: an Inkbox iMessage identity or its mailbox, or a Linq WhatsApp number, connected in Hub.
661
+ A line gives a sandbox a messaging address that Tangle Hub receives on through an owned provider connection.
651
662
  Hub routes each message to the attached sandbox, runs one agent session per member, handles STOP and START, and answers on the same line.
652
663
 
653
664
  ```typescript
@@ -672,6 +683,11 @@ Later mail in that thread runs at once, because every Hub mail carries the membe
672
683
  That token works like a password for 30 to 60 days: anyone who receives a forwarded Hub mail can write as that member.
673
684
  Forged mail can also use up a member's daily confirmation notices, but it cannot run a turn.
674
685
 
686
+ Other numbered connections select their provider-owned endpoint with `phoneNumberId`.
687
+ Use `transport: "sms"` for SMS, MMS, or RCS messages, and `transport: "whatsapp"` for Linq WhatsApp.
688
+ Resend email lines set `address` on a verified domain that can send and receive mail.
689
+ Configure the connection's signed inbound webhook before creating a Resend line.
690
+
675
691
  Use `mode: "shared"` with `roles` and several `members` for one agent that many people text.
676
692
  Each member gets their own thread; a `shared`-context role sees other shared members' recent exchanges, and an `own`-context role sees none.
677
693
  Unknown senders are rejected unless `unknownSenders: "guest"` admits them with the `guest` role.
@@ -737,7 +753,10 @@ A gated attachment must reject unknown senders.
737
753
 
738
754
  Members can also call an Inkbox iMessage line.
739
755
  Connect your ph0ny key in Hub, then name the ph0ny agent that voices the calls.
740
- Hub answers only the attachment's members, and each question the agent asks with its `ask_workspace` tool runs in the caller's own thread session, so a call continues the text conversation.
756
+ That ph0ny agent is a second agent, with its own prompt, model and voice: it hears the caller and speaks every word.
757
+ Hub answers only the attachment's members.
758
+ Each question the ph0ny agent asks with its `ask_workspace` tool runs in the caller's own thread session, so your sandbox agent sees the call's questions next to the member's texts.
759
+ The ph0ny agent does not see those texts; it knows only what `ask_workspace` returns.
741
760
 
742
761
  ```typescript
743
762
  await client.lines.enableVoice(line.id, {
@@ -748,6 +767,10 @@ await client.lines.enableVoice(line.id, {
748
767
  ```
749
768
 
750
769
  A gated line takes no calls, because a spoken answer cannot pass the reply gate.
770
+ Hub knows a caller only by caller ID, which can be spoofed, so give a voice line `chat` roles when a call must not reach the member's tools.
771
+
772
+ Hub sends the agent's visible text as the reply, unchanged; no other model rewrites it.
773
+ [Hub lines](../../../docs/hub/lines.md) explains the text and voice paths, the notices a member gets, and measured reply times.
751
774
 
752
775
  Runnable examples: [`lines-email.ts`](./examples/lines-email.ts) (an email line with a sandbox per member), [`lines-shared.ts`](./examples/lines-shared.ts) (two members on one sandbox) and [`lines-voice.ts`](./examples/lines-voice.ts) (voice on an iMessage line).
753
776
 
@@ -1,8 +1,10 @@
1
- import { g as SandboxSession, h as SandboxTaskSession, r as SandboxInstance } from "../sandbox-C7KqjY6Y.js";
2
- import { D as CodeExecutionResult, E as CodeExecutionOptions, Gr as SandboxFleetParent, Ki as SessionListOptions, O as CodeLanguage, Wi as SessionInfo, d as BackendConfig, k as CodeResultPart, za as BackendType } from "../types-UOIM3RS6.js";
3
- import { i as Sandbox } from "../client-B-LZQQ51.js";
1
+ import { h as SandboxTaskSession, r as SandboxInstance, v as SandboxSession } from "../sandbox-DWDqWnsJ.js";
2
+ import { D as CodeExecutionResult, E as CodeExecutionOptions, Gr as SandboxFleetParent, Ki as SessionListOptions, O as CodeLanguage, Wi as SessionInfo, d as BackendConfig, k as CodeResultPart, za as BackendType } from "../types-CFmeauzy.js";
3
+ import { i as Sandbox } from "../client-BHGieo06.js";
4
+ import { o as PreviewAuthorizer } from "../preview-wJJxG42-.js";
4
5
  import * as _$_modelcontextprotocol_sdk_server_index_js0 from "@modelcontextprotocol/sdk/server/index.js";
5
6
  import { JSONSchema } from "zod/v4/core";
7
+ import { ToolSet } from "ai";
6
8
 
7
9
  //#region src/agent/instances.d.ts
8
10
  /**
@@ -94,7 +96,7 @@ declare module "../sandbox.js" {
94
96
  }
95
97
  }
96
98
  //#endregion
97
- //#region src/agent/tools/_specs.d.ts
99
+ //#region src/agent/tools/types.d.ts
98
100
  /** JSON-schema-ish object describing tool inputs. Plain object literal — no Zod required. */
99
101
  type ToolJSONSchema = {
100
102
  type: "object";
@@ -109,18 +111,26 @@ interface ToolHandlerContext {
109
111
  * When unset, the bare-session kernel and the sandbox root workspace are used.
110
112
  */
111
113
  sessionId?: string;
114
+ /** Host-only preview authorization. Not part of tool arguments. */
115
+ previewAuthorize?: PreviewAuthorizer;
116
+ signal?: AbortSignal;
112
117
  }
118
+ /** Values returned by built-in sandbox tools before framework serialization. */
119
+ type ToolHandlerResult = object | string | number | boolean | null | undefined;
113
120
  /**
114
- * Pack-agnostic tool definition. The handler returns whatever the underlying
115
- * SDK method returns; each pack is responsible for serializing it into a
116
- * framework-appropriate tool-result payload.
121
+ * Pack-agnostic tool definition. The handler returns the underlying SDK
122
+ * result; each pack serializes it into its framework tool-result payload.
117
123
  */
118
- interface ToolSpec<TArgs = Record<string, unknown>, TResult = unknown> {
124
+ interface ToolSpec<TArgs = Record<string, unknown>, TResult = ToolHandlerResult> {
119
125
  name: string;
120
126
  description: string;
121
127
  inputSchema: ToolJSONSchema;
128
+ /** False for capabilities that require an explicit host grant. */
129
+ enabledByDefault?: boolean;
122
130
  makeHandler: (ctx: ToolHandlerContext) => (args: TArgs) => Promise<TResult>;
123
131
  }
132
+ //#endregion
133
+ //#region src/agent/tools/_specs.d.ts
124
134
  /** All canonical tool names — derived from the keyed registry below. */
125
135
  type ToolName = keyof typeof TOOL_SPECS;
126
136
  /**
@@ -137,29 +147,48 @@ declare const TOOL_SPECS: {
137
147
  language: "python" | "node" | "typescript" | "bash";
138
148
  source: string;
139
149
  timeout_ms?: number;
140
- }, unknown>;
150
+ }, ToolHandlerResult>;
141
151
  readonly sandbox_exec: ToolSpec<{
142
152
  command: string;
143
153
  cwd?: string;
144
154
  timeout_ms?: number;
145
- }, unknown>;
155
+ }, ToolHandlerResult>;
146
156
  readonly sandbox_read: ToolSpec<{
147
157
  path: string;
148
- }, unknown>;
158
+ }, ToolHandlerResult>;
149
159
  readonly sandbox_write: ToolSpec<{
150
160
  path: string;
151
161
  content: string;
152
- }, unknown>;
162
+ }, ToolHandlerResult>;
153
163
  readonly sandbox_list: ToolSpec<{
154
164
  path: string;
155
- }, unknown>;
165
+ }, ToolHandlerResult>;
156
166
  readonly sandbox_search: ToolSpec<{
157
167
  pattern: string;
158
168
  path?: string;
159
169
  max_results?: number;
160
- }, unknown>;
170
+ }, ToolHandlerResult>;
171
+ readonly sandbox_preview: ToolSpec<{
172
+ cwd?: string;
173
+ name?: string;
174
+ }, ToolHandlerResult>;
175
+ readonly sandbox_preview_get: ToolSpec<{
176
+ previewId: string;
177
+ }, ToolHandlerResult>;
178
+ readonly sandbox_preview_publish: ToolSpec<{
179
+ port: number;
180
+ name?: string;
181
+ }, ToolHandlerResult>;
182
+ readonly sandbox_preview_list: ToolSpec<Record<string, unknown>, ToolHandlerResult>;
183
+ readonly sandbox_preview_remove: ToolSpec<{
184
+ previewId: string;
185
+ }, ToolHandlerResult>;
161
186
  };
162
- /** Canonical ordered list. Packs use this to emit tools in a stable order. */
187
+ /**
188
+ * The legacy default tool set. Kept stable for callers that pass this exported
189
+ * array directly as well as for framework packs. Preview publishing is opt-in
190
+ * through TOOL_SPECS or a pack's explicit tools allow-list.
191
+ */
163
192
  declare const ALL_TOOL_SPECS: ToolSpec[];
164
193
  //#endregion
165
194
  //#region src/agent/mcp-local.d.ts
@@ -168,6 +197,8 @@ interface McpServerOptions {
168
197
  allow?: ToolName[];
169
198
  /** Session scope passed to handlers. */
170
199
  sessionId?: string;
200
+ previewAuthorize?: PreviewAuthorizer;
201
+ signal?: AbortSignal;
171
202
  /** Override the MCP server's reported name. Defaults to "tangle-sandbox". */
172
203
  name?: string;
173
204
  /** Override the reported version string. Defaults to the SDK package version. */
@@ -175,11 +206,12 @@ interface McpServerOptions {
175
206
  }
176
207
  type McpSdkServerModule = typeof _$_modelcontextprotocol_sdk_server_index_js0;
177
208
  type AnyMcpServer = InstanceType<McpSdkServerModule["Server"]>;
209
+ type McpTransport = Parameters<AnyMcpServer["connect"]>[0];
178
210
  interface McpServerHandle {
179
211
  /** The underlying MCP Server instance (typed loosely to avoid a hard dep). */
180
212
  server: AnyMcpServer;
181
213
  /** Connect over a transport (typically StdioServerTransport). */
182
- connect: (transport: unknown) => Promise<void>;
214
+ connect: (transport: McpTransport) => Promise<void>;
183
215
  /** Shut the server down. */
184
216
  close: () => Promise<void>;
185
217
  }
@@ -271,6 +303,8 @@ interface AnthropicToolPackOptions {
271
303
  allow?: ToolName[];
272
304
  /** Session scope passed to handlers (kernel persistence, file routing). */
273
305
  sessionId?: string;
306
+ previewAuthorize?: PreviewAuthorizer;
307
+ signal?: AbortSignal;
274
308
  }
275
309
  interface AnthropicToolPack {
276
310
  /** Tools array — pass directly to `messages.create({ tools })`. */
@@ -527,6 +561,8 @@ declare function openaiLifecycleTools(client: Sandbox, options?: LifecycleToolPa
527
561
  interface MastraToolPackOptions {
528
562
  allow?: ToolName[];
529
563
  sessionId?: string;
564
+ previewAuthorize?: PreviewAuthorizer;
565
+ signal?: AbortSignal;
530
566
  }
531
567
  /**
532
568
  * Build a Mastra tool pack bound to one sandbox.
@@ -573,6 +609,8 @@ interface OpenAIToolResultMessage {
573
609
  interface OpenAIToolPackOptions {
574
610
  allow?: ToolName[];
575
611
  sessionId?: string;
612
+ previewAuthorize?: PreviewAuthorizer;
613
+ signal?: AbortSignal;
576
614
  }
577
615
  interface OpenAIToolPack {
578
616
  tools: OpenAITool[];
@@ -614,8 +652,10 @@ declare function openaiTools(box: SandboxInstance, options?: OpenAIToolPackOptio
614
652
  interface VercelAiToolPackOptions {
615
653
  allow?: ToolName[];
616
654
  sessionId?: string;
655
+ previewAuthorize?: PreviewAuthorizer;
656
+ signal?: AbortSignal;
617
657
  }
618
- type AnyTool = unknown;
658
+ type VercelAiTool = ToolSet[string];
619
659
  /**
620
660
  * Build a Vercel AI SDK tool pack bound to one sandbox. The returned object
621
661
  * is a `Record<toolName, ai.Tool>` ready for `generateText({ tools })`.
@@ -635,6 +675,6 @@ type AnyTool = unknown;
635
675
  * });
636
676
  * ```
637
677
  */
638
- declare function vercelAiTools(box: SandboxInstance, options?: VercelAiToolPackOptions): Promise<Record<string, AnyTool>>;
678
+ declare function vercelAiTools(box: SandboxInstance, options?: VercelAiToolPackOptions): Promise<ToolSet>;
639
679
  //#endregion
640
- export { ALL_FLEET_TOOL_SPECS, ALL_LIFECYCLE_TOOL_SPECS, ALL_TOOL_SPECS, type AnthropicFleetTool, type AnthropicFleetToolPack, type AnthropicLifecycleTool, type AnthropicLifecycleToolPack, type AnthropicTool, type AnthropicToolPack, type AnthropicToolPackOptions, type AnthropicToolResultBlock, type AnthropicToolUseBlock, type CodeExecutionOptions, type CodeExecutionResult, type CodeLanguage, type CodeResultPart, FLEET_TOOL_SPECS, type FleetToolHandlerContext, type FleetToolName, type FleetToolPackOptions, type FleetToolSpec, LIFECYCLE_TOOL_SPECS, type LifecycleToolHandlerContext, type LifecycleToolName, type LifecycleToolPackOptions, type LifecycleToolSpec, type MastraToolPackOptions, type McpServerHandle, type McpServerOptions, type OpenAIFleetTool, type OpenAIFleetToolPack, type OpenAILifecycleTool, type OpenAILifecycleToolPack, type OpenAITool, type OpenAIToolCall, type OpenAIToolPack, type OpenAIToolPackOptions, type OpenAIToolResultMessage, Sandbox, type SandboxAgent, type SandboxAgentForSpec, SandboxAgentManager, type SandboxAgentSpec, type SandboxAgentStopAcknowledgement, type SandboxAgentWorkspace, TOOL_SPECS, type ToolHandlerContext, type ToolName, type ToolSpec, type VercelAiToolPackOptions, anthropicFleetTools, anthropicLifecycleTools, anthropicTools, createMcpServer, mastraFleetTools, mastraTools, openaiFleetTools, openaiLifecycleTools, openaiTools, runCode, vercelAiFleetTools, vercelAiTools };
680
+ export { ALL_FLEET_TOOL_SPECS, ALL_LIFECYCLE_TOOL_SPECS, ALL_TOOL_SPECS, type AnthropicFleetTool, type AnthropicFleetToolPack, type AnthropicLifecycleTool, type AnthropicLifecycleToolPack, type AnthropicTool, type AnthropicToolPack, type AnthropicToolPackOptions, type AnthropicToolResultBlock, type AnthropicToolUseBlock, type CodeExecutionOptions, type CodeExecutionResult, type CodeLanguage, type CodeResultPart, FLEET_TOOL_SPECS, type FleetToolHandlerContext, type FleetToolName, type FleetToolPackOptions, type FleetToolSpec, LIFECYCLE_TOOL_SPECS, type LifecycleToolHandlerContext, type LifecycleToolName, type LifecycleToolPackOptions, type LifecycleToolSpec, type MastraToolPackOptions, type McpServerHandle, type McpServerOptions, type OpenAIFleetTool, type OpenAIFleetToolPack, type OpenAILifecycleTool, type OpenAILifecycleToolPack, type OpenAITool, type OpenAIToolCall, type OpenAIToolPack, type OpenAIToolPackOptions, type OpenAIToolResultMessage, Sandbox, type SandboxAgent, type SandboxAgentForSpec, SandboxAgentManager, type SandboxAgentSpec, type SandboxAgentStopAcknowledgement, type SandboxAgentWorkspace, TOOL_SPECS, type ToolHandlerContext, type ToolName, type ToolSpec, type VercelAiTool, type VercelAiToolPackOptions, anthropicFleetTools, anthropicLifecycleTools, anthropicTools, createMcpServer, mastraFleetTools, mastraTools, openaiFleetTools, openaiLifecycleTools, openaiTools, runCode, vercelAiFleetTools, vercelAiTools };
@@ -1,8 +1,8 @@
1
- import { x as assertCurrentBackendType } from "../runtime-api-DoZsOiOR.js";
2
- import { c as NotFoundError, g as ValidationError, m as StateError } from "../errors-CmYPVl-k.js";
3
- import { n as Sandbox } from "../client-Bd8nskJA.js";
4
- import { t as SandboxInstance } from "../sandbox-DzSE1u7d.js";
5
- import { createRequire } from "node:module";
1
+ import { a as selectSpecs, i as TOOL_SPECS, o as serializeToolResult, r as ALL_TOOL_SPECS, t as createMcpServer } from "../mcp-local-DUT2U_y8.js";
2
+ import { x as assertCurrentBackendType } from "../runtime-api-BZg34WGd.js";
3
+ import { c as NotFoundError, g as ValidationError, m as StateError } from "../errors-BkhlSDW-.js";
4
+ import { n as Sandbox } from "../client-CdbHGWiu.js";
5
+ import { t as SandboxInstance } from "../sandbox-C9VLoJAb.js";
6
6
  import { z } from "zod";
7
7
  //#region src/agent/instances.ts
8
8
  const managers = /* @__PURE__ */ new WeakMap();
@@ -138,300 +138,6 @@ if (!Object.getOwnPropertyDescriptor(SandboxInstance.prototype, "agents")) Objec
138
138
  return managerFor(this);
139
139
  }
140
140
  });
141
- /**
142
- * Keyed registry. `as const` preserves per-tool TArgs/TResult through the
143
- * type system — `TOOL_SPECS.sandbox_run_code.makeHandler` returns a handler
144
- * whose args parameter is the runCodeSpec's typed `{language, source, ...}`,
145
- * not the erased `Record<string, unknown>` that an array-of-ToolSpec loses.
146
- *
147
- * Iteration order matches the order entries are declared here (V8 preserves
148
- * string-key insertion order), so the public surface is stable.
149
- */
150
- const TOOL_SPECS = {
151
- sandbox_run_code: {
152
- name: "sandbox_run_code",
153
- description: "Execute code in a persistent language kernel inside the sandbox. Variables persist across calls with the same session. Returns stdout, stderr, exit code, and a typed `results` array containing matplotlib figures (base64 PNG), pandas DataFrames, JSON via display(), or errors. Prefer this over sandbox_exec for any code that needs structured output.",
154
- inputSchema: {
155
- type: "object",
156
- properties: {
157
- language: {
158
- type: "string",
159
- enum: [
160
- "python",
161
- "node",
162
- "typescript",
163
- "bash"
164
- ],
165
- description: "Kernel language."
166
- },
167
- source: {
168
- type: "string",
169
- description: "Source code to run. Multi-line supported."
170
- },
171
- timeout_ms: {
172
- type: "number",
173
- description: "Per-call timeout. 0 disables. Default 60000."
174
- }
175
- },
176
- required: ["language", "source"],
177
- additionalProperties: false
178
- },
179
- makeHandler: ({ box, sessionId }) => async (args) => {
180
- return await box.runCode(args.language, args.source, {
181
- sessionId,
182
- timeoutMs: args.timeout_ms
183
- });
184
- }
185
- },
186
- sandbox_exec: {
187
- name: "sandbox_exec",
188
- description: "Run a shell command (no persistent state) in the sandbox. Use for one-shot tasks like 'pnpm install' or 'ls'. For code that should share state across calls, prefer sandbox_run_code with a sessionId.",
189
- inputSchema: {
190
- type: "object",
191
- properties: {
192
- command: {
193
- type: "string",
194
- description: "Shell command line."
195
- },
196
- cwd: {
197
- type: "string",
198
- description: "Working directory. Optional."
199
- },
200
- timeout_ms: {
201
- type: "number",
202
- description: "Default 60000."
203
- }
204
- },
205
- required: ["command"],
206
- additionalProperties: false
207
- },
208
- makeHandler: ({ box, sessionId }) => async (args) => {
209
- return await box.exec(args.command, {
210
- cwd: args.cwd,
211
- timeoutMs: args.timeout_ms,
212
- sessionId
213
- });
214
- }
215
- },
216
- sandbox_read: {
217
- name: "sandbox_read",
218
- description: "Read a file from the sandbox filesystem. Relative paths resolve from the workspace root; absolute paths read the container filesystem directly.",
219
- inputSchema: {
220
- type: "object",
221
- properties: { path: { type: "string" } },
222
- required: ["path"],
223
- additionalProperties: false
224
- },
225
- makeHandler: ({ box, sessionId }) => async (args) => {
226
- return { content: await box.read(args.path, { sessionId }) };
227
- }
228
- },
229
- sandbox_write: {
230
- name: "sandbox_write",
231
- description: "Write a file in the sandbox. Creates parent directories as needed. Overwrites existing files.",
232
- inputSchema: {
233
- type: "object",
234
- properties: {
235
- path: { type: "string" },
236
- content: {
237
- type: "string",
238
- description: "Full file contents."
239
- }
240
- },
241
- required: ["path", "content"],
242
- additionalProperties: false
243
- },
244
- makeHandler: ({ box }) => async (args) => {
245
- await box.write(args.path, args.content);
246
- return { ok: true };
247
- }
248
- },
249
- sandbox_list: {
250
- name: "sandbox_list",
251
- description: "List entries in a directory with size, type, and mode.",
252
- inputSchema: {
253
- type: "object",
254
- properties: { path: { type: "string" } },
255
- required: ["path"],
256
- additionalProperties: false
257
- },
258
- makeHandler: ({ box }) => async (args) => {
259
- return { entries: await box.fs.list(args.path) };
260
- }
261
- },
262
- sandbox_search: {
263
- name: "sandbox_search",
264
- description: "Ripgrep-style code search. Returns matching lines with surrounding context.",
265
- inputSchema: {
266
- type: "object",
267
- properties: {
268
- pattern: {
269
- type: "string",
270
- description: "Regex pattern."
271
- },
272
- path: {
273
- type: "string",
274
- description: "Subdirectory to search. Optional."
275
- },
276
- max_results: {
277
- type: "number",
278
- description: "Cap. Default 100."
279
- }
280
- },
281
- required: ["pattern"],
282
- additionalProperties: false
283
- },
284
- makeHandler: ({ box }) => async (args) => {
285
- const matches = [];
286
- const cap = args.max_results ?? 100;
287
- for await (const m of box.search(args.pattern, {
288
- cwd: args.path,
289
- maxResults: cap
290
- })) {
291
- matches.push(m);
292
- if (matches.length >= cap) break;
293
- }
294
- return { matches };
295
- }
296
- }
297
- };
298
- /** Canonical ordered list. Packs use this to emit tools in a stable order. */
299
- const ALL_TOOL_SPECS = Object.values(TOOL_SPECS);
300
- /** Pack-side helper: filter the registry by an optional allow-list. */
301
- function selectSpecs(allow) {
302
- if (!allow || allow.length === 0) return ALL_TOOL_SPECS;
303
- const set = new Set(allow);
304
- return Object.keys(TOOL_SPECS).filter((name) => set.has(name)).map((name) => TOOL_SPECS[name]);
305
- }
306
- /**
307
- * Best-effort serialization of a tool handler's return value into a string
308
- * tool-result payload. Each pack uses this when its target API expects a
309
- * string `content` field; packs that support structured content (Anthropic
310
- * multi-block) can opt out and serialize differently.
311
- *
312
- * `CodeExecutionResult` is serialized as JSON because the LLM benefits from
313
- * seeing the structured results array; images come through as base64 strings
314
- * which the model can read or hand back to the user.
315
- */
316
- function serializeToolResult(value) {
317
- if (typeof value === "string") return value;
318
- try {
319
- return JSON.stringify(value, null, 2);
320
- } catch {
321
- return String(value);
322
- }
323
- }
324
- //#endregion
325
- //#region src/agent/mcp-local.ts
326
- /**
327
- * Local MCP (Model Context Protocol) server bridge.
328
- *
329
- * `createMcpServer(box, { allow })` returns an MCP `Server` instance wired
330
- * with the same tool registry the framework packs use. Pair it with a
331
- * transport (most commonly stdio) and your sandbox becomes a paste-able
332
- * MCP source for Claude Desktop, Cursor, Zed, or any other MCP client.
333
- *
334
- * Complements `box.getMcpEndpoint()` — that returns a hosted HTTPS+JWT MCP
335
- * URL for users who can expose one; this gives users a fully local server
336
- * that runs inside their own process.
337
- *
338
- * `@modelcontextprotocol/sdk` is dynamically imported (optional peer dep).
339
- * Install in your app:
340
- * pnpm add @modelcontextprotocol/sdk
341
- */
342
- const SDK_VERSION = (() => {
343
- try {
344
- return createRequire(import.meta.url)("../../package.json").version ?? "0.0.0";
345
- } catch {
346
- return "0.0.0";
347
- }
348
- })();
349
- /**
350
- * Build an MCP server backed by one sandbox. The server registers
351
- * `tools/list` and `tools/call` handlers populated from the same registry
352
- * the framework packs use.
353
- *
354
- * @example
355
- * ```ts
356
- * // tangle-mcp-server.ts — used as the command in your MCP client config.
357
- * import { Sandbox } from "@tangle-network/sandbox";
358
- * import { createMcpServer } from "@tangle-network/sandbox/agent";
359
- * import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
360
- *
361
- * const client = new Sandbox({ apiKey: process.env.TANGLE_API_KEY });
362
- * const box = await client.get(process.env.SANDBOX_ID!);
363
- * const { connect } = await createMcpServer(box, { sessionId: "claude-desktop" });
364
- * await connect(new StdioServerTransport());
365
- * ```
366
- *
367
- * Claude Desktop config snippet:
368
- * ```json
369
- * {
370
- * "mcpServers": {
371
- * "tangle-sandbox": {
372
- * "command": "node",
373
- * "args": ["./tangle-mcp-server.js"],
374
- * "env": { "TANGLE_API_KEY": "...", "SANDBOX_ID": "..." }
375
- * }
376
- * }
377
- * }
378
- * ```
379
- */
380
- async function createMcpServer(box, options = {}) {
381
- let serverModule;
382
- let typesModule;
383
- try {
384
- [serverModule, typesModule] = await Promise.all([import("@modelcontextprotocol/sdk/server/index.js"), import("@modelcontextprotocol/sdk/types.js")]);
385
- } catch {
386
- throw new Error("createMcpServer(): the `@modelcontextprotocol/sdk` package is not installed. Install it via `pnpm add @modelcontextprotocol/sdk`.");
387
- }
388
- const specs = selectSpecs(options.allow);
389
- const ctx = {
390
- box,
391
- sessionId: options.sessionId
392
- };
393
- const handlers = /* @__PURE__ */ new Map();
394
- for (const spec of specs) handlers.set(spec.name, spec.makeHandler(ctx));
395
- const server = new serverModule.Server({
396
- name: options.name ?? "tangle-sandbox",
397
- version: options.version ?? SDK_VERSION
398
- }, { capabilities: { tools: {} } });
399
- server.setRequestHandler(typesModule.ListToolsRequestSchema, async () => ({ tools: specs.map((s) => ({
400
- name: s.name,
401
- description: s.description,
402
- inputSchema: s.inputSchema
403
- })) }));
404
- server.setRequestHandler(typesModule.CallToolRequestSchema, async (req) => {
405
- const r = req;
406
- const handler = handlers.get(r.params.name);
407
- if (!handler) return {
408
- isError: true,
409
- content: [{
410
- type: "text",
411
- text: `Unknown tool: ${r.params.name}`
412
- }]
413
- };
414
- try {
415
- return { content: [{
416
- type: "text",
417
- text: serializeToolResult(await handler(r.params.arguments ?? {}))
418
- }] };
419
- } catch (err) {
420
- return {
421
- isError: true,
422
- content: [{
423
- type: "text",
424
- text: err instanceof Error ? err.message : String(err)
425
- }]
426
- };
427
- }
428
- });
429
- return {
430
- server,
431
- connect: (transport) => server.connect(transport),
432
- close: () => server.close()
433
- };
434
- }
435
141
  //#endregion
436
142
  //#region src/agent/run-code.ts
437
143
  /**
@@ -476,10 +182,15 @@ function anthropicTools(box, options = {}) {
476
182
  const specs = selectSpecs(options.allow);
477
183
  const ctx = {
478
184
  box,
479
- sessionId: options.sessionId
185
+ sessionId: options.sessionId,
186
+ previewAuthorize: options.previewAuthorize,
187
+ signal: options.signal
480
188
  };
481
189
  const handlers = /* @__PURE__ */ new Map();
482
- for (const spec of specs) handlers.set(spec.name, spec.makeHandler(ctx));
190
+ for (const spec of specs) {
191
+ const handler = spec.makeHandler(ctx);
192
+ handlers.set(spec.name, (args) => handler(args));
193
+ }
483
194
  const tools = specs.map((s) => ({
484
195
  name: s.name,
485
196
  description: s.description,
@@ -1171,7 +882,9 @@ async function mastraTools(box, options = {}) {
1171
882
  const specs = selectSpecs(options.allow);
1172
883
  const ctx = {
1173
884
  box,
1174
- sessionId: options.sessionId
885
+ sessionId: options.sessionId,
886
+ previewAuthorize: options.previewAuthorize,
887
+ signal: options.signal
1175
888
  };
1176
889
  const result = {};
1177
890
  for (const spec of specs) {
@@ -1216,10 +929,15 @@ function openaiTools(box, options = {}) {
1216
929
  const specs = selectSpecs(options.allow);
1217
930
  const ctx = {
1218
931
  box,
1219
- sessionId: options.sessionId
932
+ sessionId: options.sessionId,
933
+ previewAuthorize: options.previewAuthorize,
934
+ signal: options.signal
1220
935
  };
1221
936
  const handlers = /* @__PURE__ */ new Map();
1222
- for (const spec of specs) handlers.set(spec.name, spec.makeHandler(ctx));
937
+ for (const spec of specs) {
938
+ const handler = spec.makeHandler(ctx);
939
+ handlers.set(spec.name, async (args) => serializeToolResult(await handler(args)));
940
+ }
1223
941
  const tools = specs.map((s) => ({
1224
942
  type: "function",
1225
943
  function: {
@@ -1249,7 +967,7 @@ function openaiTools(box, options = {}) {
1249
967
  return {
1250
968
  role: "tool",
1251
969
  tool_call_id: call.id,
1252
- content: serializeToolResult(result)
970
+ content: result
1253
971
  };
1254
972
  } catch (err) {
1255
973
  return {
@@ -1300,7 +1018,9 @@ async function vercelAiTools(box, options = {}) {
1300
1018
  const specs = selectSpecs(options.allow);
1301
1019
  const ctx = {
1302
1020
  box,
1303
- sessionId: options.sessionId
1021
+ sessionId: options.sessionId,
1022
+ previewAuthorize: options.previewAuthorize,
1023
+ signal: options.signal
1304
1024
  };
1305
1025
  const result = {};
1306
1026
  for (const spec of specs) {
@@ -0,0 +1,2 @@
1
+ import { a as PreviewAuthorizationRequest, c as PublishAgentPreviewOptions, d as getAgentPreview, f as listAgentPreviews, h as resolveSelfSandbox, i as AgentPreviewOptions, l as assertPreviewId, m as removeAgentPreview, n as servePreviewMcp, o as PreviewAuthorizer, p as publishAgentPreview, r as AgentPreviewError, s as PreviewExecutionContext, t as PREVIEW_TOOLS, u as ensureAgentPreview } from "../preview-wJJxG42-.js";
2
+ export { AgentPreviewError, AgentPreviewOptions, PREVIEW_TOOLS, PreviewAuthorizationRequest, PreviewAuthorizer, PreviewExecutionContext, PublishAgentPreviewOptions, assertPreviewId, ensureAgentPreview, getAgentPreview, listAgentPreviews, publishAgentPreview, removeAgentPreview, resolveSelfSandbox, servePreviewMcp };