@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
@@ -0,0 +1,429 @@
1
+ import { a as listAgentPreviews, i as getAgentPreview, o as publishAgentPreview, r as ensureAgentPreview, s as removeAgentPreview, t as AgentPreviewError } from "./preview-operations-Dgbi46FH.js";
2
+ import { createRequire } from "node:module";
3
+ //#region \0rolldown/runtime.js
4
+ var __defProp = Object.defineProperty;
5
+ var __exportAll = (all, no_symbols) => {
6
+ let target = {};
7
+ for (var name in all) __defProp(target, name, {
8
+ get: all[name],
9
+ enumerable: true
10
+ });
11
+ if (!no_symbols) __defProp(target, Symbol.toStringTag, { value: "Module" });
12
+ return target;
13
+ };
14
+ //#endregion
15
+ //#region src/agent/tools/preview.ts
16
+ function input(args, keys) {
17
+ if (!args || typeof args !== "object" || Array.isArray(args) || Object.keys(args).some((key) => !keys.includes(key))) throw new AgentPreviewError("PREVIEW_INVALID_INPUT", `Accepted fields: ${keys.join(", ") || "none"}; the host binds sandbox/session`);
18
+ }
19
+ const execution = (ctx) => ({
20
+ authorize: ctx.previewAuthorize,
21
+ signal: ctx.signal
22
+ });
23
+ const name = {
24
+ type: "string",
25
+ minLength: 1,
26
+ maxLength: 128,
27
+ description: "Human-readable app/service label; not an access policy."
28
+ };
29
+ const previewId = {
30
+ type: "string",
31
+ minLength: 1,
32
+ description: "The exact preview ID returned by the platform."
33
+ };
34
+ /**
35
+ * Keyed registry. `as const` preserves per-tool TArgs/TResult through the
36
+ * type system — `TOOL_SPECS.sandbox_run_code.makeHandler` returns a handler
37
+ * whose args parameter is the runCodeSpec's typed `{language, source, ...}`,
38
+ * not the erased `Record<string, unknown>` that an array-of-ToolSpec loses.
39
+ *
40
+ * Iteration order matches the order entries are declared here (V8 preserves
41
+ * string-key insertion order), so the public surface is stable.
42
+ */
43
+ const TOOL_SPECS = {
44
+ sandbox_run_code: {
45
+ name: "sandbox_run_code",
46
+ 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.",
47
+ inputSchema: {
48
+ type: "object",
49
+ properties: {
50
+ language: {
51
+ type: "string",
52
+ enum: [
53
+ "python",
54
+ "node",
55
+ "typescript",
56
+ "bash"
57
+ ],
58
+ description: "Kernel language."
59
+ },
60
+ source: {
61
+ type: "string",
62
+ description: "Source code to run. Multi-line supported."
63
+ },
64
+ timeout_ms: {
65
+ type: "number",
66
+ description: "Per-call timeout. 0 disables. Default 60000."
67
+ }
68
+ },
69
+ required: ["language", "source"],
70
+ additionalProperties: false
71
+ },
72
+ makeHandler: ({ box, sessionId }) => async (args) => {
73
+ return await box.runCode(args.language, args.source, {
74
+ sessionId,
75
+ timeoutMs: args.timeout_ms
76
+ });
77
+ }
78
+ },
79
+ sandbox_exec: {
80
+ name: "sandbox_exec",
81
+ 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.",
82
+ inputSchema: {
83
+ type: "object",
84
+ properties: {
85
+ command: {
86
+ type: "string",
87
+ description: "Shell command line."
88
+ },
89
+ cwd: {
90
+ type: "string",
91
+ description: "Working directory. Optional."
92
+ },
93
+ timeout_ms: {
94
+ type: "number",
95
+ description: "Default 60000."
96
+ }
97
+ },
98
+ required: ["command"],
99
+ additionalProperties: false
100
+ },
101
+ makeHandler: ({ box, sessionId }) => async (args) => {
102
+ return await box.exec(args.command, {
103
+ cwd: args.cwd,
104
+ timeoutMs: args.timeout_ms,
105
+ sessionId
106
+ });
107
+ }
108
+ },
109
+ sandbox_read: {
110
+ name: "sandbox_read",
111
+ description: "Read a file from the sandbox filesystem. Relative paths resolve from the workspace root; absolute paths read the container filesystem directly.",
112
+ inputSchema: {
113
+ type: "object",
114
+ properties: { path: { type: "string" } },
115
+ required: ["path"],
116
+ additionalProperties: false
117
+ },
118
+ makeHandler: ({ box, sessionId }) => async (args) => {
119
+ return { content: await box.read(args.path, { sessionId }) };
120
+ }
121
+ },
122
+ sandbox_write: {
123
+ name: "sandbox_write",
124
+ description: "Write a file in the sandbox. Creates parent directories as needed. Overwrites existing files.",
125
+ inputSchema: {
126
+ type: "object",
127
+ properties: {
128
+ path: { type: "string" },
129
+ content: {
130
+ type: "string",
131
+ description: "Full file contents."
132
+ }
133
+ },
134
+ required: ["path", "content"],
135
+ additionalProperties: false
136
+ },
137
+ makeHandler: ({ box }) => async (args) => {
138
+ await box.write(args.path, args.content);
139
+ return { ok: true };
140
+ }
141
+ },
142
+ sandbox_list: {
143
+ name: "sandbox_list",
144
+ description: "List entries in a directory with size, type, and mode.",
145
+ inputSchema: {
146
+ type: "object",
147
+ properties: { path: { type: "string" } },
148
+ required: ["path"],
149
+ additionalProperties: false
150
+ },
151
+ makeHandler: ({ box }) => async (args) => {
152
+ return { entries: await box.fs.list(args.path) };
153
+ }
154
+ },
155
+ sandbox_search: {
156
+ name: "sandbox_search",
157
+ description: "Ripgrep-style code search. Returns matching lines with surrounding context.",
158
+ inputSchema: {
159
+ type: "object",
160
+ properties: {
161
+ pattern: {
162
+ type: "string",
163
+ description: "Regex pattern."
164
+ },
165
+ path: {
166
+ type: "string",
167
+ description: "Subdirectory to search. Optional."
168
+ },
169
+ max_results: {
170
+ type: "number",
171
+ description: "Cap. Default 100."
172
+ }
173
+ },
174
+ required: ["pattern"],
175
+ additionalProperties: false
176
+ },
177
+ makeHandler: ({ box }) => async (args) => {
178
+ const matches = [];
179
+ const cap = args.max_results ?? 100;
180
+ for await (const m of box.search(args.pattern, {
181
+ cwd: args.path,
182
+ maxResults: cap
183
+ })) {
184
+ matches.push(m);
185
+ if (matches.length >= cap) break;
186
+ }
187
+ return { matches };
188
+ }
189
+ },
190
+ sandbox_preview: {
191
+ name: "sandbox_preview",
192
+ enabledByDefault: false,
193
+ description: "Start/reuse one project's managed server and publish its actual preview URL. Use a different cwd for each app; existing apps are not replaced. Executes project startup code and may expose content publicly; use only when authorized.",
194
+ inputSchema: {
195
+ type: "object",
196
+ properties: {
197
+ cwd: {
198
+ type: "string",
199
+ description: "Project directory in the bound workspace."
200
+ },
201
+ name
202
+ },
203
+ additionalProperties: false
204
+ },
205
+ makeHandler: (ctx) => async (args) => {
206
+ input(args, ["cwd", "name"]);
207
+ return ensureAgentPreview(ctx.box, {
208
+ ...args,
209
+ sessionId: ctx.sessionId
210
+ }, execution(ctx));
211
+ }
212
+ },
213
+ sandbox_preview_get: {
214
+ name: "sandbox_preview_get",
215
+ enabledByDefault: false,
216
+ description: "Read a known preview's current URL, routing readiness and diagnostics without publishing it.",
217
+ inputSchema: {
218
+ type: "object",
219
+ properties: { previewId },
220
+ required: ["previewId"],
221
+ additionalProperties: false
222
+ },
223
+ makeHandler: (ctx) => async (args) => {
224
+ input(args, ["previewId"]);
225
+ return getAgentPreview(ctx.box, args.previewId, execution(ctx));
226
+ }
227
+ },
228
+ sandbox_preview_publish: {
229
+ name: "sandbox_preview_publish",
230
+ enabledByDefault: false,
231
+ description: "Publish an existing HTTP service on an explicit port. Does not start a process or replace other previews. Use for custom servers or several services in one repository. Publishing can expose app content publicly.",
232
+ inputSchema: {
233
+ type: "object",
234
+ properties: {
235
+ port: {
236
+ type: "integer",
237
+ minimum: 1,
238
+ maximum: 65535
239
+ },
240
+ name
241
+ },
242
+ required: ["port"],
243
+ additionalProperties: false
244
+ },
245
+ makeHandler: (ctx) => async (args) => {
246
+ input(args, ["port", "name"]);
247
+ return publishAgentPreview(ctx.box, args, execution(ctx));
248
+ }
249
+ },
250
+ sandbox_preview_list: {
251
+ name: "sandbox_preview_list",
252
+ enabledByDefault: false,
253
+ description: "List this sandbox's published services with their exact URLs, ports, status and app labels. Does not publish unexposed ports. A ready record is not a fresh health check; use sandbox_preview_get to check it.",
254
+ inputSchema: {
255
+ type: "object",
256
+ properties: {},
257
+ additionalProperties: false
258
+ },
259
+ makeHandler: (ctx) => async (args) => {
260
+ input(args, []);
261
+ return listAgentPreviews(ctx.box, execution(ctx));
262
+ }
263
+ },
264
+ sandbox_preview_remove: {
265
+ name: "sandbox_preview_remove",
266
+ enabledByDefault: false,
267
+ description: "Unpublish exactly one preview, leaving its process and other applications alone. Requires authorization to change publication.",
268
+ inputSchema: {
269
+ type: "object",
270
+ properties: { previewId },
271
+ required: ["previewId"],
272
+ additionalProperties: false
273
+ },
274
+ makeHandler: (ctx) => async (args) => {
275
+ input(args, ["previewId"]);
276
+ await removeAgentPreview(ctx.box, args.previewId, execution(ctx));
277
+ return { removed: args.previewId };
278
+ }
279
+ }
280
+ };
281
+ /**
282
+ * The legacy default tool set. Kept stable for callers that pass this exported
283
+ * array directly as well as for framework packs. Preview publishing is opt-in
284
+ * through TOOL_SPECS or a pack's explicit tools allow-list.
285
+ */
286
+ const ALL_TOOL_SPECS = Object.values(TOOL_SPECS).filter((spec) => spec.enabledByDefault !== false);
287
+ /** Pack-side helper: filter the registry by an optional allow-list. */
288
+ function selectSpecs(allow) {
289
+ if (!allow || allow.length === 0) return ALL_TOOL_SPECS;
290
+ const set = new Set(allow);
291
+ return Object.keys(TOOL_SPECS).filter((name) => set.has(name)).map((name) => TOOL_SPECS[name]);
292
+ }
293
+ /**
294
+ * Best-effort serialization of a tool handler's return value into a string
295
+ * tool-result payload. Each pack uses this when its target API expects a
296
+ * string `content` field; packs that support structured content (Anthropic
297
+ * multi-block) can opt out and serialize differently.
298
+ *
299
+ * `CodeExecutionResult` is serialized as JSON because the LLM benefits from
300
+ * seeing the structured results array; images come through as base64 strings
301
+ * which the model can read or hand back to the user.
302
+ */
303
+ function serializeToolResult(value) {
304
+ if (typeof value === "string") return value;
305
+ try {
306
+ return JSON.stringify(value, null, 2);
307
+ } catch {
308
+ return String(value);
309
+ }
310
+ }
311
+ //#endregion
312
+ //#region src/agent/mcp-local.ts
313
+ /**
314
+ * Local MCP (Model Context Protocol) server bridge.
315
+ *
316
+ * `createMcpServer(box, { allow })` returns an MCP `Server` instance wired
317
+ * with the same tool registry the framework packs use. Pair it with a
318
+ * transport (most commonly stdio) and your sandbox becomes a paste-able
319
+ * MCP source for Claude Desktop, Cursor, Zed, or any other MCP client.
320
+ *
321
+ * Complements `box.getMcpEndpoint()` — that returns a hosted HTTPS+JWT MCP
322
+ * URL for users who can expose one; this gives users a fully local server
323
+ * that runs inside their own process.
324
+ *
325
+ * `@modelcontextprotocol/sdk` is dynamically imported (optional peer dep).
326
+ * Install in your app:
327
+ * pnpm add @modelcontextprotocol/sdk
328
+ */
329
+ var mcp_local_exports = /* @__PURE__ */ __exportAll({ createMcpServer: () => createMcpServer });
330
+ const SDK_VERSION = (() => {
331
+ try {
332
+ return createRequire(import.meta.url)("../../package.json").version ?? "0.0.0";
333
+ } catch {
334
+ return "0.0.0";
335
+ }
336
+ })();
337
+ /**
338
+ * Build an MCP server backed by one sandbox. The server registers
339
+ * `tools/list` and `tools/call` handlers populated from the same registry
340
+ * the framework packs use.
341
+ *
342
+ * @example
343
+ * ```ts
344
+ * // tangle-mcp-server.ts — used as the command in your MCP client config.
345
+ * import { Sandbox } from "@tangle-network/sandbox";
346
+ * import { createMcpServer } from "@tangle-network/sandbox/agent";
347
+ * import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
348
+ *
349
+ * const client = new Sandbox({ apiKey: process.env.TANGLE_API_KEY });
350
+ * const box = await client.get(process.env.SANDBOX_ID!);
351
+ * const { connect } = await createMcpServer(box, { sessionId: "claude-desktop" });
352
+ * await connect(new StdioServerTransport());
353
+ * ```
354
+ *
355
+ * Claude Desktop config snippet:
356
+ * ```json
357
+ * {
358
+ * "mcpServers": {
359
+ * "tangle-sandbox": {
360
+ * "command": "node",
361
+ * "args": ["./tangle-mcp-server.js"],
362
+ * "env": { "TANGLE_API_KEY": "...", "SANDBOX_ID": "..." }
363
+ * }
364
+ * }
365
+ * }
366
+ * ```
367
+ */
368
+ async function createMcpServer(box, options = {}) {
369
+ let serverModule;
370
+ let typesModule;
371
+ try {
372
+ [serverModule, typesModule] = await Promise.all([import("@modelcontextprotocol/sdk/server/index.js"), import("@modelcontextprotocol/sdk/types.js")]);
373
+ } catch {
374
+ throw new Error("createMcpServer(): the `@modelcontextprotocol/sdk` package is not installed. Install it via `pnpm add @modelcontextprotocol/sdk`.");
375
+ }
376
+ const specs = selectSpecs(options.allow);
377
+ const ctx = {
378
+ box,
379
+ sessionId: options.sessionId,
380
+ previewAuthorize: options.previewAuthorize,
381
+ signal: options.signal
382
+ };
383
+ const handlers = /* @__PURE__ */ new Map();
384
+ for (const spec of specs) {
385
+ const handler = spec.makeHandler(ctx);
386
+ handlers.set(spec.name, async (args) => serializeToolResult(await handler(args)));
387
+ }
388
+ const server = new serverModule.Server({
389
+ name: options.name ?? "tangle-sandbox",
390
+ version: options.version ?? SDK_VERSION
391
+ }, { capabilities: { tools: {} } });
392
+ server.setRequestHandler(typesModule.ListToolsRequestSchema, async () => ({ tools: specs.map((s) => ({
393
+ name: s.name,
394
+ description: s.description,
395
+ inputSchema: s.inputSchema
396
+ })) }));
397
+ server.setRequestHandler(typesModule.CallToolRequestSchema, async (req) => {
398
+ const r = req;
399
+ const handler = handlers.get(r.params.name);
400
+ if (!handler) return {
401
+ isError: true,
402
+ content: [{
403
+ type: "text",
404
+ text: `Unknown tool: ${r.params.name}`
405
+ }]
406
+ };
407
+ try {
408
+ return { content: [{
409
+ type: "text",
410
+ text: await handler(r.params.arguments ?? {})
411
+ }] };
412
+ } catch (err) {
413
+ return {
414
+ isError: true,
415
+ content: [{
416
+ type: "text",
417
+ text: err instanceof Error ? err.message : String(err)
418
+ }]
419
+ };
420
+ }
421
+ });
422
+ return {
423
+ server,
424
+ connect: (transport) => server.connect(transport),
425
+ close: () => server.close()
426
+ };
427
+ }
428
+ //#endregion
429
+ export { selectSpecs as a, TOOL_SPECS as i, mcp_local_exports as n, serializeToolResult as o, ALL_TOOL_SPECS as r, createMcpServer as t };
@@ -0,0 +1,212 @@
1
+ //#region src/agent/preview-operations.ts
2
+ async function authorize(context, request) {
3
+ context.signal?.throwIfAborted();
4
+ await context.authorize?.(request);
5
+ context.signal?.throwIfAborted();
6
+ }
7
+ function validPort(port) {
8
+ if (!Number.isInteger(port) || port < 1 || port > 65535) throw new AgentPreviewError("PREVIEW_INVALID_INPUT", "Port must be an integer between 1 and 65535");
9
+ }
10
+ function validName(name) {
11
+ let hasControlCharacters = false;
12
+ if (typeof name === "string") for (const character of name) {
13
+ const codePoint = character.codePointAt(0);
14
+ if (codePoint !== void 0 && (codePoint < 32 || codePoint === 127)) {
15
+ hasControlCharacters = true;
16
+ break;
17
+ }
18
+ }
19
+ if (name !== void 0 && (typeof name !== "string" || !name.trim() || name.length > 128 || hasControlCharacters)) throw new AgentPreviewError("PREVIEW_INVALID_INPUT", "App name must be 1-128 printable characters");
20
+ }
21
+ function assertPreviewId(id) {
22
+ if (typeof id !== "string" || !/^[A-Za-z0-9][A-Za-z0-9._:-]{0,255}$/.test(id)) throw new AgentPreviewError("PREVIEW_INVALID_INPUT", "A valid previewId is required");
23
+ }
24
+ /** A failed preview never becomes a fabricated URL or an account-wide lookup. */
25
+ var AgentPreviewError = class extends Error {
26
+ constructor(code, message, status) {
27
+ super(message);
28
+ this.code = code;
29
+ this.status = status;
30
+ this.name = "AgentPreviewError";
31
+ }
32
+ };
33
+ /**
34
+ * Resolve only the sandbox bound to this credential. No list/name lookup, env
35
+ * id, owner fallback, or key delegation is allowed on this path. An ordinary
36
+ * owner client should select a sandbox explicitly instead.
37
+ */
38
+ async function resolveSelfSandbox(client) {
39
+ const response = await client.fetch("/v1/sandboxes/self/identity", {
40
+ method: "GET",
41
+ redirect: "error"
42
+ });
43
+ if (!response.ok) {
44
+ await response.body?.cancel().catch(() => void 0);
45
+ throw new AgentPreviewError("SANDBOX_SELF_REFUSED", `Sandbox self identity was refused (HTTP ${response.status}); use a sandbox-bound runtime credential and a host supporting self identity`, response.status);
46
+ }
47
+ const body = await response.json();
48
+ if (!body || typeof body !== "object" || !("sandboxId" in body) || typeof body.sandboxId !== "string" || !/^[A-Za-z0-9][A-Za-z0-9._:-]{0,255}$/.test(body.sandboxId)) throw new AgentPreviewError("SANDBOX_SELF_INVALID_RESPONSE", "Sandbox self identity returned no valid bound sandbox id");
49
+ const box = await client.get(body.sandboxId);
50
+ if (!box || box.id !== body.sandboxId) throw new AgentPreviewError("SANDBOX_SELF_INVALID_RESPONSE", "The credential's sandbox is unavailable; self resolution never selects another sandbox");
51
+ return box;
52
+ }
53
+ /**
54
+ * Start/reuse the selected workspace's managed server and publish its preview.
55
+ * This is an explicit publishing operation, not a background post-turn hook.
56
+ * The returned URL has passed the existing routing readiness check; that is
57
+ * not proof of application correctness or per-recipient access control.
58
+ */
59
+ async function ensureAgentPreview(box, options = {}, context = {}) {
60
+ if (!options || typeof options !== "object" || Array.isArray(options) || Object.keys(options).some((key) => key !== "sessionId" && key !== "cwd" && key !== "name") || Object.values(options).some((value) => value !== void 0 && (typeof value !== "string" || !value.trim() || value.includes("\0")))) throw new AgentPreviewError("PREVIEW_INVALID_INPUT", "Preview accepts only nonempty cwd, sessionId and name strings");
61
+ validName(options.name);
62
+ await authorize(context, {
63
+ operation: "start",
64
+ phase: "before",
65
+ sessionId: options.sessionId,
66
+ cwd: options.cwd
67
+ });
68
+ const server = await box.process.ensureDevServer({
69
+ sessionId: options.sessionId,
70
+ cwd: options.cwd
71
+ });
72
+ const port = server.port;
73
+ if (typeof port !== "number" || !Number.isInteger(port) || port < 1 || port > 65535) throw new AgentPreviewError("PREVIEW_INVALID_RESPONSE", "Managed server returned no valid listening port");
74
+ return publishPreview(box, {
75
+ port,
76
+ name: options.name
77
+ }, context, {
78
+ operation: "start",
79
+ sessionId: options.sessionId,
80
+ cwd: options.cwd,
81
+ workspaceRoot: server.workspaceRoot
82
+ });
83
+ }
84
+ /** Publish an already-running service, including multiple services in one repo. */
85
+ async function publishAgentPreview(box, options, context = {}) {
86
+ if (!options || typeof options !== "object" || Array.isArray(options) || Object.keys(options).some((key) => key !== "port" && key !== "name")) throw new AgentPreviewError("PREVIEW_INVALID_INPUT", "Publishing accepts only port and name");
87
+ validPort(options.port);
88
+ validName(options.name);
89
+ await authorize(context, {
90
+ operation: "publish",
91
+ phase: "before",
92
+ port: options.port
93
+ });
94
+ return publishPreview(box, options, context, { operation: "publish" });
95
+ }
96
+ function managedAppIdentity(link) {
97
+ const app = link.metadata?.app;
98
+ if (!app || typeof app !== "object" || Array.isArray(app)) return;
99
+ const cwd = app.cwd;
100
+ const sessionId = app.sessionId;
101
+ if (typeof cwd !== "string" || !cwd) return;
102
+ return {
103
+ cwd,
104
+ ...typeof sessionId === "string" && sessionId ? { sessionId } : {}
105
+ };
106
+ }
107
+ async function publishPreview(box, options, context, scope) {
108
+ const { port } = options;
109
+ const request = {
110
+ operation: scope.operation,
111
+ sessionId: scope.sessionId,
112
+ cwd: scope.cwd,
113
+ port
114
+ };
115
+ await authorize(context, {
116
+ ...request,
117
+ phase: "publish"
118
+ });
119
+ const before = await box.previewLinks.list();
120
+ const metadata = { app: {
121
+ ...options.name ? { name: options.name } : {},
122
+ ...scope.workspaceRoot ? { cwd: scope.workspaceRoot } : {},
123
+ ...scope.sessionId ? { sessionId: scope.sessionId } : {}
124
+ } };
125
+ let creation;
126
+ try {
127
+ creation = await box.previewLinks.create(port, { metadata });
128
+ assertPreviewId(creation.previewId);
129
+ if (creation.port !== port) throw new AgentPreviewError("PREVIEW_INVALID_RESPONSE", "Preview creation returned a different service port");
130
+ const link = await box.previewLinks.waitUntilReady(creation.previewId, { signal: context.signal });
131
+ validateReadyPreview(link, port, creation.previewId);
132
+ await authorize(context, {
133
+ ...request,
134
+ previewId: link.previewId,
135
+ phase: "after"
136
+ });
137
+ if (scope.operation === "start" && scope.workspaceRoot) for (const previous of before) {
138
+ if (previous.previewId === link.previewId) continue;
139
+ const identity = managedAppIdentity(previous);
140
+ if (identity?.cwd !== scope.workspaceRoot || identity.sessionId !== scope.sessionId) continue;
141
+ await authorize(context, {
142
+ operation: "remove",
143
+ phase: "before",
144
+ previewId: previous.previewId,
145
+ port: previous.port,
146
+ sessionId: scope.sessionId,
147
+ cwd: scope.cwd
148
+ });
149
+ await box.previewLinks.remove(previous.previewId);
150
+ }
151
+ return link;
152
+ } catch (error) {
153
+ if (creation?.created) await box.previewLinks.remove(creation.previewId).catch(() => void 0);
154
+ throw error;
155
+ }
156
+ }
157
+ function validateReadyPreview(link, port, previewId) {
158
+ if (link.status !== "ready") throw new AgentPreviewError("PREVIEW_NOT_READY", "Preview routing is not ready");
159
+ let url;
160
+ try {
161
+ url = new URL(link.url);
162
+ } catch {
163
+ throw new AgentPreviewError("PREVIEW_INVALID_RESPONSE", "Preview returned an invalid URL");
164
+ }
165
+ if (link.port !== port || link.previewId !== previewId || !["http:", "https:"].includes(url.protocol) || url.username || url.password) throw new AgentPreviewError("PREVIEW_INVALID_RESPONSE", "Preview does not identify the selected HTTP service");
166
+ }
167
+ /** Lists recorded publications, not every listening port. Never auto-publishes. */
168
+ async function listAgentPreviews(box, context = {}) {
169
+ await authorize(context, {
170
+ operation: "list",
171
+ phase: "before"
172
+ });
173
+ const links = await box.previewLinks.list();
174
+ await authorize(context, {
175
+ operation: "list",
176
+ phase: "after"
177
+ });
178
+ return links;
179
+ }
180
+ async function getAgentPreview(box, previewId, context = {}) {
181
+ assertPreviewId(previewId);
182
+ await authorize(context, {
183
+ operation: "get",
184
+ phase: "before",
185
+ previewId
186
+ });
187
+ const link = await box.previewLinks.get(previewId);
188
+ await authorize(context, {
189
+ operation: "get",
190
+ phase: "after",
191
+ previewId,
192
+ port: link.port
193
+ });
194
+ return link;
195
+ }
196
+ /** Unpublishes one service; does not stop it or affect other app URLs. */
197
+ async function removeAgentPreview(box, previewId, context = {}) {
198
+ assertPreviewId(previewId);
199
+ await authorize(context, {
200
+ operation: "remove",
201
+ phase: "before",
202
+ previewId
203
+ });
204
+ await box.previewLinks.remove(previewId);
205
+ await authorize(context, {
206
+ operation: "remove",
207
+ phase: "after",
208
+ previewId
209
+ });
210
+ }
211
+ //#endregion
212
+ export { listAgentPreviews as a, resolveSelfSandbox as c, getAgentPreview as i, assertPreviewId as n, publishAgentPreview as o, ensureAgentPreview as r, removeAgentPreview as s, AgentPreviewError as t };