@tangle-network/sandbox 0.58.0 → 0.58.1

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 (38) hide show
  1. package/dist/agent/index.d.ts +4 -4
  2. package/dist/agent/index.js +3 -3
  3. package/dist/agent/preview.d.ts +1 -1
  4. package/dist/agent/preview.js +2 -2
  5. package/dist/{agent-run-outcome-DV-9cNsk.d.ts → agent-run-outcome-CJP18Ip8.d.ts} +1 -1
  6. package/dist/auth/index.d.ts +1 -1
  7. package/dist/auth/index.js +1 -1
  8. package/dist/{browser-interactive-control-controller-knjCl8Zp.d.ts → browser-interactive-control-controller-1m7jgLeg.d.ts} +1 -1
  9. package/dist/{client-BMdV_CeM.js → client-BHItHEg0.js} +9 -4
  10. package/dist/{client-B1I66sl_.d.ts → client-BI0_ZUUS.d.ts} +6 -4
  11. package/dist/collaboration/index.d.ts +1 -1
  12. package/dist/core.d.ts +6 -5
  13. package/dist/core.js +5 -3
  14. package/dist/{index-CGnI-q1g.d.ts → index-BitiSmBp.d.ts} +2 -2
  15. package/dist/index.d.ts +12 -11
  16. package/dist/index.js +6 -4
  17. package/dist/interactive-control.d.ts +1 -1
  18. package/dist/line-application-DOg7jrnA.js +100 -0
  19. package/dist/lines-DLIo-NTB.d.ts +556 -0
  20. package/dist/lines.d.ts +2 -0
  21. package/dist/lines.js +273 -0
  22. package/dist/{local-cli-auth-DfuFJCcs.js → local-cli-auth-N1IYywxf.js} +1 -1
  23. package/dist/{mcp-local-DXO-9rtB.js → mcp-local-BWsftreI.js} +1 -1
  24. package/dist/{preview-Bz7TXYSf.d.ts → preview-CVrjEPgk.d.ts} +3 -3
  25. package/dist/runtime.d.ts +3 -3
  26. package/dist/{sandbox-DyrDBnjp.js → sandbox-B2kuUBn6.js} +61 -226
  27. package/dist/{sandbox-BMSWYvdP.d.ts → sandbox-DyPRgt1M.d.ts} +5 -411
  28. package/dist/tangle/index.d.ts +1 -1
  29. package/dist/tangle/index.js +1 -1
  30. package/dist/{tangle-BtQkJqfz.js → tangle-DCjIsZI0.js} +1 -1
  31. package/dist/{types-DRyvWIJf.d.ts → types-_Gn4d93t.d.ts} +60 -2
  32. package/package.json +10 -5
  33. /package/dist/{cli-auth-bundle-bRJOyaJO.js → cli-auth-bundle-0VjPAtKt.js} +0 -0
  34. /package/dist/{errors-CNsmhCen.d.ts → errors-AVpynVrG.d.ts} +0 -0
  35. /package/dist/{index-BN7zNEUB.d.ts → index-C48z7K4r.d.ts} +0 -0
  36. /package/dist/{index-X4EEZlMi.d.ts → index-D4u-vv87.d.ts} +0 -0
  37. /package/dist/{preview-operations-Dgbi46FH.js → preview-operations-BhQ4_CF7.js} +0 -0
  38. /package/dist/{terminal-stream-BW4veIsI.d.ts → terminal-stream-Bf2stNDX.d.ts} +0 -0
package/dist/lines.js ADDED
@@ -0,0 +1,273 @@
1
+ import { _ as parseErrorResponse, g as ValidationError } from "./errors-BkhlSDW-.js";
2
+ //#region src/lines.ts
3
+ /**
4
+ * Lines: give a sandbox a phone number or messaging address.
5
+ *
6
+ * A line is an address that Tangle Hub receives on, such as an Inkbox
7
+ * iMessage identity or Linq WhatsApp number. Attaching it to a sandbox makes
8
+ * Hub route each inbound message to that sandbox. Each member gets a separate
9
+ * thread in its own agent session. Hub sends the agent's answer on the same
10
+ * line. Hub owns routing, consent (STOP/START), unknown senders and
11
+ * metering, so an app only chooses who may text and in which mode.
12
+ *
13
+ * @example
14
+ * ```ts
15
+ * const line = await client.lines.fromConnection({ connectionId, transport: "imessage" });
16
+ * await box.lines.attach({
17
+ * number: line.id,
18
+ * mode: "personal",
19
+ * members: [{ address: "+15550100001", role: "owner" }],
20
+ * });
21
+ * // Text `line.connect` to `line.routerAddress`, then write to the agent.
22
+ * ```
23
+ *
24
+ * A line can also give every member their own sandbox, so a public line
25
+ * serves each person from an isolated box with its own files:
26
+ *
27
+ * ```ts
28
+ * await client.lines.attach({
29
+ * number: line.id,
30
+ * mode: "shared",
31
+ * members: [{ address: "+15550100001", role: "owner" }],
32
+ * unknownSenders: "guest",
33
+ * roles: { owner: { context: "own", tools: "act" }, guest: { context: "own", tools: "act" } },
34
+ * instance: { keyPrefix: "person:", create: { idleTimeoutSeconds: 600 } },
35
+ * });
36
+ * ```
37
+ */
38
+ /**
39
+ * The instance key that serves one member: `keyPrefix` plus the first 32 hex
40
+ * characters of the SHA-256 of the member's address as Hub stores it (E.164,
41
+ * or a lowercased email). It depends only on the prefix and the address, so a
42
+ * person keeps their box across re-attaches, and your own code can reach it
43
+ * with `client.instances.ensure({ key })`. This helper applies only to
44
+ * address-bound members. Hub derives a different key for `subjectId` members.
45
+ */
46
+ async function lineInstanceKey(keyPrefix, address) {
47
+ const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(address));
48
+ return `${keyPrefix}${Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, "0")).join("").slice(0, 32)}`;
49
+ }
50
+ /** Stable setup retry identity. This label never grants profile or line access. */
51
+ async function profileChannelReference(profileId, input) {
52
+ if (!/^ap_[A-Za-z0-9_-]{1,61}$/.test(profileId)) throw new ValidationError("Use a stored Platform profile ID");
53
+ const identity = JSON.stringify([
54
+ input.connectionId,
55
+ input.transport,
56
+ input.phoneNumberId ?? null,
57
+ input.address?.trim().toLowerCase() ?? null
58
+ ]);
59
+ const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(identity));
60
+ return `profile:${profileId}:${Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, "0")).join("").slice(0, 32)}`;
61
+ }
62
+ const LINE_ID = /^ln_[A-Za-z0-9_-]+$/;
63
+ async function hubData(response) {
64
+ const body = await response.text();
65
+ if (!response.ok) throw parseErrorResponse(response.status, body, void 0, response.headers);
66
+ const parsed = JSON.parse(body);
67
+ if (parsed.success !== true || parsed.data === void 0) throw parseErrorResponse(502, body, void 0, response.headers);
68
+ return parsed.data;
69
+ }
70
+ function json(method, body) {
71
+ return {
72
+ method,
73
+ headers: { "Content-Type": "application/json" },
74
+ body: JSON.stringify(body)
75
+ };
76
+ }
77
+ /** `client.lines`: your lines, their members and their threads. */
78
+ var LinesClient = class {
79
+ constructor(http) {
80
+ this.http = http;
81
+ }
82
+ /**
83
+ * Create a line from an owned Inkbox or Linq connection, or return the line
84
+ * already pinned to that provider identity. Hub owns inbound routing and
85
+ * never re-keys the connection.
86
+ */
87
+ async fromConnection(input) {
88
+ return (await hubData(await this.http.fetch("/v1/lines", json("POST", input)))).line;
89
+ }
90
+ /** Your lines. `sandboxId` narrows to lines attached to that sandbox. */
91
+ async list(options = {}) {
92
+ const params = new URLSearchParams();
93
+ if (options.sandboxId) params.set("sandboxId", options.sandboxId);
94
+ if (options.profileId) params.set("profileId", options.profileId);
95
+ const query = params.size ? `?${params}` : "";
96
+ return (await hubData(await this.http.fetch(`/v1/lines${query}`))).lines;
97
+ }
98
+ /** Supported combinations from the maintained host channel catalog. */
99
+ async providers() {
100
+ return (await hubData(await this.http.fetch("/v1/lines/providers"))).providers;
101
+ }
102
+ /** Metadata only; no reservation and no provider credentials are returned. */
103
+ async numbers(connectionId, transport) {
104
+ const params = new URLSearchParams({
105
+ connectionId,
106
+ transport
107
+ });
108
+ return hubData(await this.http.fetch(`/v1/lines/numbers?${params}`));
109
+ }
110
+ /** Choose the payer/execution authority for a cookie-authenticated attachment. */
111
+ async executionKeys() {
112
+ return (await hubData(await this.http.fetch("/v1/lines/execution-keys"))).keys;
113
+ }
114
+ async get(lineId) {
115
+ return (await hubData(await this.http.fetch(`/v1/lines/${encodeURIComponent(lineId)}`))).line;
116
+ }
117
+ /** A line id for a line id or one of your lines' addresses. */
118
+ async resolve(number) {
119
+ if (LINE_ID.test(number)) return number;
120
+ const line = (await this.list()).find((l) => l.address === number);
121
+ if (!line) throw new ValidationError(`No line with address ${number}`);
122
+ return line.id;
123
+ }
124
+ /**
125
+ * Attach a line so each member runs in their own sandbox. Hub checks that
126
+ * your API key can run sandboxes, and each turn runs as a short-lived child
127
+ * of that key. Attaching again with the same options returns the same
128
+ * attachment. To attach a line to one sandbox, use `box.lines.attach()`.
129
+ */
130
+ async attach(options) {
131
+ const lineId = await this.resolve(options.number);
132
+ const { number: _number, ...rest } = options;
133
+ return (await hubData(await this.http.fetch(`/v1/lines/${encodeURIComponent(lineId)}/attachment`, json("PUT", rest)))).attachment;
134
+ }
135
+ /**
136
+ * Detach a line (by id or address), whatever it is attached to. This is
137
+ * the way to detach a line attached with `instance`, which names no
138
+ * sandbox. Each member's own sandbox stays under its instance key. Returns
139
+ * false when the line was not attached.
140
+ */
141
+ async detach(number, options = {}) {
142
+ if (options.expectedAttachmentId !== void 0 && !/^lat_[A-Za-z0-9_-]+$/.test(options.expectedAttachmentId)) throw new ValidationError("Invalid expected attachment identity");
143
+ const lineId = await this.resolve(number);
144
+ return (await hubData(await this.http.fetch(`/v1/lines/${encodeURIComponent(lineId)}/attachment`, {
145
+ method: "DELETE",
146
+ ...options.expectedAttachmentId ? { headers: { "if-match": `"${options.expectedAttachmentId}"` } } : {}
147
+ }))).detached;
148
+ }
149
+ /** Detach only this observed attachment. A replacement is left untouched.
150
+ * The distinct native route makes older hosts refuse rather than ignore
151
+ * the condition. This never falls back to unconditional line detachment.
152
+ */
153
+ async detachAttachment(number, attachmentId) {
154
+ if (!/^[A-Za-z0-9_-]{1,256}$/.test(attachmentId)) throw new ValidationError("A valid expected attachment id is required");
155
+ const lineId = await this.resolve(number);
156
+ return (await hubData(await this.http.fetch(`/v1/lines/${encodeURIComponent(lineId)}/attachments/${encodeURIComponent(attachmentId)}`, { method: "DELETE" }))).detached;
157
+ }
158
+ /**
159
+ * Retire a detached line's Hub routing and free its workspace transport slot.
160
+ * Hub refuses an attached or voice-enabled line. A retry by line id returns
161
+ * false; the provider connection and message history remain.
162
+ */
163
+ async release(number) {
164
+ const lineId = await this.resolve(number);
165
+ return (await hubData(await this.http.fetch(`/v1/lines/${encodeURIComponent(lineId)}`, { method: "DELETE" }))).released;
166
+ }
167
+ /**
168
+ * Take calls on a line (Inkbox iMessage lines). Hub points the identity's
169
+ * incoming calls at itself, binds the ph0ny agent to the line and adds the
170
+ * agent's `ask_workspace` tool. Enabling again replaces every credential.
171
+ */
172
+ async enableVoice(lineId, options) {
173
+ return (await hubData(await this.http.fetch(`/v1/lines/${encodeURIComponent(lineId)}`, json("PATCH", { voice: {
174
+ enabled: true,
175
+ ph0ny: {
176
+ connectionId: options.ph0nyConnectionId,
177
+ agentId: options.ph0nyAgentId
178
+ }
179
+ } })))).line;
180
+ }
181
+ /** Stop taking calls on a line: Hub refuses them and Inkbox rejects them. */
182
+ async disableVoice(lineId) {
183
+ return (await hubData(await this.http.fetch(`/v1/lines/${encodeURIComponent(lineId)}`, json("PATCH", { voice: { enabled: false } })))).line;
184
+ }
185
+ /**
186
+ * Queue a proactive message to an active, consenting member. Hub reuses the
187
+ * member's authenticated provider conversation, rechecks STOP immediately
188
+ * before delivery, and defers delivery during the recipient's saved quiet hours.
189
+ */
190
+ async send(lineId, input) {
191
+ return hubData(await this.http.fetch(`/v1/lines/${encodeURIComponent(lineId)}/send`, json("POST", input)));
192
+ }
193
+ /** Read the native outbox receipt. Queued is not a delivery confirmation. */
194
+ async sentMessage(lineId, messageId) {
195
+ return hubData(await this.http.fetch(`/v1/lines/${encodeURIComponent(lineId)}/outbox/${encodeURIComponent(messageId)}`));
196
+ }
197
+ /** Only the recipient's proven message can enable reminders or choose quiet hours. */
198
+ async reminders(lineId, memberId) {
199
+ return hubData(await this.http.fetch(`/v1/lines/${encodeURIComponent(lineId)}/members/${encodeURIComponent(memberId)}/reminders`));
200
+ }
201
+ /** Members of the line's active attachment. */
202
+ members(lineId) {
203
+ const base = `/v1/lines/${encodeURIComponent(lineId)}/members`;
204
+ const http = this.http;
205
+ return {
206
+ async list() {
207
+ return (await hubData(await http.fetch(base))).members;
208
+ },
209
+ async add(spec) {
210
+ return (await hubData(await http.fetch(base, json("POST", spec)))).member;
211
+ },
212
+ async update(memberId, patch) {
213
+ return (await hubData(await http.fetch(`${base}/${encodeURIComponent(memberId)}`, json("PATCH", patch)))).member;
214
+ },
215
+ async remove(memberId) {
216
+ await hubData(await http.fetch(`${base}/${encodeURIComponent(memberId)}`, { method: "DELETE" }));
217
+ }
218
+ };
219
+ }
220
+ /** Read one retained message without depending on a recent-message page. */
221
+ async message(lineId, messageId) {
222
+ return (await hubData(await this.http.fetch(`/v1/lines/${encodeURIComponent(lineId)}/messages/${encodeURIComponent(messageId)}`))).message;
223
+ }
224
+ /** Threads of a line (one per member) and their messages, newest first. */
225
+ threads(lineId) {
226
+ const base = `/v1/lines/${encodeURIComponent(lineId)}/threads`;
227
+ const http = this.http;
228
+ return {
229
+ async list() {
230
+ return (await hubData(await http.fetch(base))).threads;
231
+ },
232
+ async messages(threadId) {
233
+ return (await hubData(await http.fetch(`${base}/${encodeURIComponent(threadId)}/messages`))).messages;
234
+ }
235
+ };
236
+ }
237
+ };
238
+ /** `sandbox.lines`: attach lines to this sandbox. */
239
+ var SandboxLines = class {
240
+ lines;
241
+ constructor(http, sandboxId) {
242
+ this.http = http;
243
+ this.sandboxId = sandboxId;
244
+ this.lines = new LinesClient(http);
245
+ }
246
+ /**
247
+ * Attach a line to this sandbox. Hub checks that your API key can run this
248
+ * sandbox, and each turn runs as a short-lived child of that key. Attaching
249
+ * again with the same options returns the same attachment.
250
+ */
251
+ async attach(options) {
252
+ const lineId = await this.lines.resolve(options.number);
253
+ const { number: _number, ...rest } = options;
254
+ return (await hubData(await this.http.fetch(`/v1/lines/${encodeURIComponent(lineId)}/attachment`, json("PUT", {
255
+ ...rest,
256
+ sandboxId: this.sandboxId
257
+ })))).attachment;
258
+ }
259
+ /** Lines attached to this sandbox. */
260
+ async list() {
261
+ return this.lines.list({ sandboxId: this.sandboxId });
262
+ }
263
+ /** Detach a line (by id or address) from this sandbox. */
264
+ async detach(number) {
265
+ const lineId = await this.lines.resolve(number);
266
+ const line = await this.lines.get(lineId);
267
+ if (!line.attachment) return;
268
+ if (line.attachment.sandboxId !== this.sandboxId) throw new ValidationError(`Line ${lineId} is attached to another sandbox`);
269
+ await this.lines.detachAttachment(lineId, line.attachment.id);
270
+ }
271
+ };
272
+ //#endregion
273
+ export { LinesClient, SandboxLines, lineInstanceKey, profileChannelReference };
@@ -1,4 +1,4 @@
1
- import { t as AUTH_BUNDLE_PATHS } from "./cli-auth-bundle-bRJOyaJO.js";
1
+ import { t as AUTH_BUNDLE_PATHS } from "./cli-auth-bundle-0VjPAtKt.js";
2
2
  import { existsSync, readFileSync } from "node:fs";
3
3
  import { homedir } from "node:os";
4
4
  import { join } from "node:path";
@@ -1,4 +1,4 @@
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";
1
+ import { a as listAgentPreviews, i as getAgentPreview, o as publishAgentPreview, r as ensureAgentPreview, s as removeAgentPreview, t as AgentPreviewError } from "./preview-operations-BhQ4_CF7.js";
2
2
  import { createRequire } from "node:module";
3
3
  //#region \0rolldown/runtime.js
4
4
  var __defProp = Object.defineProperty;
@@ -1,6 +1,6 @@
1
- import { r as SandboxInstance } from "./sandbox-BMSWYvdP.js";
2
- import { Pn as PreviewLinkInfo, mt as EnsureDevServerOptions } from "./types-DRyvWIJf.js";
3
- import { i as Sandbox } from "./client-B1I66sl_.js";
1
+ import { r as SandboxInstance } from "./sandbox-DyPRgt1M.js";
2
+ import { Pn as PreviewLinkInfo, mt as EnsureDevServerOptions } from "./types-_Gn4d93t.js";
3
+ import { i as Sandbox } from "./client-BI0_ZUUS.js";
4
4
 
5
5
  //#region src/agent/preview-operations.d.ts
6
6
  type AgentPreviewOptions = Pick<EnsureDevServerOptions, "sessionId" | "cwd"> & {
package/dist/runtime.d.ts CHANGED
@@ -1,6 +1,6 @@
1
- import { A as CommitTaskSessionOptions, At as FileUsageResult, Bi as SessionExecutionInfo, Ci as SandboxTerminalManager, Dt as FileTreeOptions, Er as SandboxEvent, Fi as SendSessionMessageOptions, H as CreateTaskSessionOptions, Ii as SendSessionMessageRequest, Ji as SessionMessageAdmission, Li as SentSessionMessage, Ot as FileTreeResult, Si as SandboxTerminalInfo, Sn as ListMessagesOptions, T as ChunkedUploadResult, V as CreateSessionOptions, Vi as SessionExecutionStatus, Wi as SessionInfo, bt as FileReadBatchOptions, fa as TaskSessionInfo, hi as SandboxRuntimeHealth, jt as FileWriteResult, ka as WriteFileOptions, kt as FileUsageOptions, la as TaskSessionChanges, li as SandboxPortBinding, or as RenameOptions, qi as SessionMessage, ua as TaskSessionCommitResult, w as ChunkedUploadOptions, wa as UploadProgress, wi as SandboxTerminalRequestOptions, wt as FileRenameResult, xi as SandboxTerminalCreateOptions, xt as FileReadBatchResult, zi as SessionEventStreamOptions } from "./types-DRyvWIJf.js";
2
- import { _ as TimeoutError, a as FileWriteConflictError, c as NotFoundError, f as SandboxError, g as StateError, h as ServerError, l as PartialFailureError, m as SandboxFailureDetail, n as CapabilityError, p as SandboxErrorJson, s as NetworkError, t as AuthError, u as QuotaError, v as ValidationError } from "./errors-CNsmhCen.js";
3
- import { a as deriveAgentRunOutcome, i as deriveAgentResultOutcome, n as AgentRunOutcomeTracker, r as createAgentRunOutcomeTracker, t as AgentRunOutcome } from "./agent-run-outcome-DV-9cNsk.js";
1
+ import { A as CommitTaskSessionOptions, At as FileUsageResult, Bi as SessionExecutionInfo, Ci as SandboxTerminalManager, Dt as FileTreeOptions, Er as SandboxEvent, Fi as SendSessionMessageOptions, H as CreateTaskSessionOptions, Ii as SendSessionMessageRequest, Ji as SessionMessageAdmission, Li as SentSessionMessage, Ot as FileTreeResult, Si as SandboxTerminalInfo, Sn as ListMessagesOptions, T as ChunkedUploadResult, V as CreateSessionOptions, Vi as SessionExecutionStatus, Wi as SessionInfo, bt as FileReadBatchOptions, fa as TaskSessionInfo, hi as SandboxRuntimeHealth, jt as FileWriteResult, ka as WriteFileOptions, kt as FileUsageOptions, la as TaskSessionChanges, li as SandboxPortBinding, or as RenameOptions, qi as SessionMessage, ua as TaskSessionCommitResult, w as ChunkedUploadOptions, wa as UploadProgress, wi as SandboxTerminalRequestOptions, wt as FileRenameResult, xi as SandboxTerminalCreateOptions, xt as FileReadBatchResult, zi as SessionEventStreamOptions } from "./types-_Gn4d93t.js";
2
+ import { _ as TimeoutError, a as FileWriteConflictError, c as NotFoundError, f as SandboxError, g as StateError, h as ServerError, l as PartialFailureError, m as SandboxFailureDetail, n as CapabilityError, p as SandboxErrorJson, s as NetworkError, t as AuthError, u as QuotaError, v as ValidationError } from "./errors-AVpynVrG.js";
3
+ import { a as deriveAgentRunOutcome, i as deriveAgentResultOutcome, n as AgentRunOutcomeTracker, r as createAgentRunOutcomeTracker, t as AgentRunOutcome } from "./agent-run-outcome-CJP18Ip8.js";
4
4
 
5
5
  //#region src/lib/chunked-upload.d.ts
6
6
  /** The transport a caller wires this module to — {@link SandboxInstance.runtimeFetch}
@@ -2,6 +2,7 @@ import { C as normalizeRuntimeBackendConfig, S as mergeRuntimeBackendConfig, T a
2
2
  import { _ as parseErrorResponse, c as NotFoundError, f as SandboxError, g as ValidationError, h as TimeoutError, m as StateError, n as CapabilityError, p as ServerError, r as EdgeNotReadyError, s as NetworkError, t as AuthError, u as QuotaError } from "./errors-BkhlSDW-.js";
3
3
  import { c as createInteractiveControlHolderId, d as interactiveSessionControlReleaseResponseSchema, f as interactiveSessionControlValidationResponseSchema, i as createBrowserInteractiveSessionControlTransport, o as InteractiveSessionControlController, p as interactiveSessionStatusResponseSchema, r as browserInteractiveTerminalEndpoint, s as assertInteractiveSessionRef, u as interactiveSessionControlClaimResponseSchema } from "./browser-interactive-control-controller-CVGqjPgs.js";
4
4
  import { n as combineAbortSignals, t as awaitWithAbort } from "./abort-signal-CgFhjY_v.js";
5
+ import { SandboxLines } from "./lines.js";
5
6
  import { AgentExactRunControlRefSchema, AgentInteractiveSessionAttachSchema, AgentInteractiveSessionControlClaimAcknowledgementSchema, AgentInteractiveSessionControlClaimRequestSchema, AgentInteractiveSessionControlClaimSchema, AgentInteractiveSessionPromptAcknowledgementSchema, AgentInteractiveSessionPromptCommandSchema, AgentInteractiveSessionRefSchema, AgentInteractiveSessionStartSchema, AgentInteractiveSessionStopAcknowledgementSchema, AgentInteractiveSessionStopCommandSchema, AgentRunCancellationAcknowledgementSchema, AgentRunCancellationRequestSchema, InteractionAcknowledgementSchema, InteractionBindingSchema, InteractionRequestSchema, InteractionResponseCommandSchema, InteractionResponseSchema, TerminalInputSchema, TerminalOutputEventSchema, TerminalReplayWindowSchema, TerminalResizeSchema, TerminalSessionRefSchema, agentInteractiveSessionControlClaimAcknowledgementMatchesRequest, agentInteractiveSessionControlClaimIsNewer, agentInteractiveSessionControlClaimMatchesRef, agentInteractiveSessionPromptAcknowledgementMatchesCommand, agentInteractiveSessionPromptRequestDigest, agentInteractiveSessionRefMatchesStart, agentInteractiveSessionStatusMatchesRef, agentInteractiveSessionStopAcknowledgementMatchesCommand, agentRunCancellationAcknowledgementMatchesRequest, canonicalCandidateDigest, exactAgentInteractiveSessionStart, sha256DigestSchema, terminalSessionUsable } from "@tangle-network/agent-interface";
6
7
  import { z } from "zod";
7
8
  import { AgentInteractiveSessionControlClaimSchema as AgentInteractiveSessionControlClaimSchema$1, AgentInteractiveSessionPromptAcknowledgementSchema as AgentInteractiveSessionPromptAcknowledgementSchema$1, AgentInteractiveSessionRefSchema as AgentInteractiveSessionRefSchema$1, AgentInteractiveSessionStatusSchema, AgentInteractiveSessionStopAcknowledgementSchema as AgentInteractiveSessionStopAcknowledgementSchema$1 } from "@tangle-network/agent-interface/environment-interactive-control";
@@ -229,227 +230,6 @@ function rewrapResponse(original, headers) {
229
230
  return wrapper;
230
231
  }
231
232
  //#endregion
232
- //#region src/lines.ts
233
- /**
234
- * Lines: give a sandbox a phone number or messaging address.
235
- *
236
- * A line is an address that Tangle Hub receives on, such as an Inkbox
237
- * iMessage identity or Linq WhatsApp number. Attaching it to a sandbox makes
238
- * Hub route each inbound message to that sandbox. Each member gets a separate
239
- * thread in its own agent session. Hub sends the agent's answer on the same
240
- * line. Hub owns routing, consent (STOP/START), unknown senders and
241
- * metering, so an app only chooses who may text and in which mode.
242
- *
243
- * @example
244
- * ```ts
245
- * const line = await client.lines.fromConnection({ connectionId, transport: "imessage" });
246
- * await box.lines.attach({
247
- * number: line.id,
248
- * mode: "personal",
249
- * members: [{ address: "+15550100001", role: "owner" }],
250
- * });
251
- * // Text `line.connect` to `line.routerAddress`, then write to the agent.
252
- * ```
253
- *
254
- * A line can also give every member their own sandbox, so a public line
255
- * serves each person from an isolated box with its own files:
256
- *
257
- * ```ts
258
- * await client.lines.attach({
259
- * number: line.id,
260
- * mode: "shared",
261
- * members: [{ address: "+15550100001", role: "owner" }],
262
- * unknownSenders: "guest",
263
- * roles: { owner: { context: "own", tools: "act" }, guest: { context: "own", tools: "act" } },
264
- * instance: { keyPrefix: "person:", create: { idleTimeoutSeconds: 600 } },
265
- * });
266
- * ```
267
- */
268
- /**
269
- * The instance key that serves one member: `keyPrefix` plus the first 32 hex
270
- * characters of the SHA-256 of the member's address as Hub stores it (E.164,
271
- * or a lowercased email). It depends only on the prefix and the address, so a
272
- * person keeps their box across re-attaches, and your own code can reach it
273
- * with `client.instances.ensure({ key })`.
274
- */
275
- async function lineInstanceKey(keyPrefix, address) {
276
- const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(address));
277
- return `${keyPrefix}${Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, "0")).join("").slice(0, 32)}`;
278
- }
279
- const LINE_ID = /^ln_[A-Za-z0-9_-]+$/;
280
- async function hubData(response) {
281
- const body = await response.text();
282
- if (!response.ok) throw parseErrorResponse(response.status, body, void 0, response.headers);
283
- const parsed = JSON.parse(body);
284
- if (parsed.success !== true || parsed.data === void 0) throw parseErrorResponse(502, body, void 0, response.headers);
285
- return parsed.data;
286
- }
287
- function json(method, body) {
288
- return {
289
- method,
290
- headers: { "Content-Type": "application/json" },
291
- body: JSON.stringify(body)
292
- };
293
- }
294
- /** `client.lines`: your lines, their members and their threads. */
295
- var LinesClient = class {
296
- constructor(http) {
297
- this.http = http;
298
- }
299
- /**
300
- * Create a line from an owned Inkbox or Linq connection, or return the line
301
- * already pinned to that provider identity. Hub owns inbound routing and
302
- * never re-keys the connection.
303
- */
304
- async fromConnection(input) {
305
- return (await hubData(await this.http.fetch("/v1/lines", json("POST", input)))).line;
306
- }
307
- /** Your lines. `sandboxId` narrows to lines attached to that sandbox. */
308
- async list(options = {}) {
309
- const query = options.sandboxId ? `?sandboxId=${encodeURIComponent(options.sandboxId)}` : "";
310
- return (await hubData(await this.http.fetch(`/v1/lines${query}`))).lines;
311
- }
312
- async get(lineId) {
313
- return (await hubData(await this.http.fetch(`/v1/lines/${encodeURIComponent(lineId)}`))).line;
314
- }
315
- /** A line id for a line id or one of your lines' addresses. */
316
- async resolve(number) {
317
- if (LINE_ID.test(number)) return number;
318
- const line = (await this.list()).find((l) => l.address === number);
319
- if (!line) throw new ValidationError(`No line with address ${number}`);
320
- return line.id;
321
- }
322
- /**
323
- * Attach a line so each member runs in their own sandbox. Hub checks that
324
- * your API key can run sandboxes, and each turn runs as a short-lived child
325
- * of that key. Attaching again with the same options returns the same
326
- * attachment. To attach a line to one sandbox, use `box.lines.attach()`.
327
- */
328
- async attach(options) {
329
- const lineId = await this.resolve(options.number);
330
- const { number: _number, ...rest } = options;
331
- return (await hubData(await this.http.fetch(`/v1/lines/${encodeURIComponent(lineId)}/attachment`, json("PUT", rest)))).attachment;
332
- }
333
- /**
334
- * Detach a line (by id or address), whatever it is attached to. This is
335
- * the way to detach a line attached with `instance`, which names no
336
- * sandbox. Each member's own sandbox stays under its instance key. Returns
337
- * false when the line was not attached.
338
- */
339
- async detach(number) {
340
- const lineId = await this.resolve(number);
341
- return (await hubData(await this.http.fetch(`/v1/lines/${encodeURIComponent(lineId)}/attachment`, { method: "DELETE" }))).detached;
342
- }
343
- /**
344
- * Retire a detached line's Hub routing and free its workspace transport slot.
345
- * Hub refuses an attached or voice-enabled line. A retry by line id returns
346
- * false; the provider connection and message history remain.
347
- */
348
- async release(number) {
349
- const lineId = await this.resolve(number);
350
- return (await hubData(await this.http.fetch(`/v1/lines/${encodeURIComponent(lineId)}`, { method: "DELETE" }))).released;
351
- }
352
- /**
353
- * Take calls on a line (Inkbox iMessage lines). Hub points the identity's
354
- * incoming calls at itself, binds the ph0ny agent to the line and adds the
355
- * agent's `ask_workspace` tool. Enabling again replaces every credential.
356
- */
357
- async enableVoice(lineId, options) {
358
- return (await hubData(await this.http.fetch(`/v1/lines/${encodeURIComponent(lineId)}`, json("PATCH", { voice: {
359
- enabled: true,
360
- ph0ny: {
361
- connectionId: options.ph0nyConnectionId,
362
- agentId: options.ph0nyAgentId
363
- }
364
- } })))).line;
365
- }
366
- /** Stop taking calls on a line: Hub refuses them and Inkbox rejects them. */
367
- async disableVoice(lineId) {
368
- return (await hubData(await this.http.fetch(`/v1/lines/${encodeURIComponent(lineId)}`, json("PATCH", { voice: { enabled: false } })))).line;
369
- }
370
- /**
371
- * Queue a proactive message to an active, consenting member. Hub reuses the
372
- * member's authenticated provider conversation, rechecks STOP immediately
373
- * before delivery, and defers delivery during the recipient's saved quiet hours.
374
- */
375
- async send(lineId, input) {
376
- return hubData(await this.http.fetch(`/v1/lines/${encodeURIComponent(lineId)}/send`, json("POST", input)));
377
- }
378
- /** Read the native outbox receipt. Queued is not a delivery confirmation. */
379
- async sentMessage(lineId, messageId) {
380
- return hubData(await this.http.fetch(`/v1/lines/${encodeURIComponent(lineId)}/outbox/${encodeURIComponent(messageId)}`));
381
- }
382
- /** Only the recipient's proven message can enable reminders or choose quiet hours. */
383
- async reminders(lineId, memberId) {
384
- return hubData(await this.http.fetch(`/v1/lines/${encodeURIComponent(lineId)}/members/${encodeURIComponent(memberId)}/reminders`));
385
- }
386
- /** Members of the line's active attachment. */
387
- members(lineId) {
388
- const base = `/v1/lines/${encodeURIComponent(lineId)}/members`;
389
- const http = this.http;
390
- return {
391
- async list() {
392
- return (await hubData(await http.fetch(base))).members;
393
- },
394
- async add(spec) {
395
- return (await hubData(await http.fetch(base, json("POST", spec)))).member;
396
- },
397
- async update(memberId, patch) {
398
- return (await hubData(await http.fetch(`${base}/${encodeURIComponent(memberId)}`, json("PATCH", patch)))).member;
399
- },
400
- async remove(memberId) {
401
- await hubData(await http.fetch(`${base}/${encodeURIComponent(memberId)}`, { method: "DELETE" }));
402
- }
403
- };
404
- }
405
- /** Threads of a line (one per member) and their messages, newest first. */
406
- threads(lineId) {
407
- const base = `/v1/lines/${encodeURIComponent(lineId)}/threads`;
408
- const http = this.http;
409
- return {
410
- async list() {
411
- return (await hubData(await http.fetch(base))).threads;
412
- },
413
- async messages(threadId) {
414
- return (await hubData(await http.fetch(`${base}/${encodeURIComponent(threadId)}/messages`))).messages;
415
- }
416
- };
417
- }
418
- };
419
- /** `sandbox.lines`: attach lines to this sandbox. */
420
- var SandboxLines = class {
421
- lines;
422
- constructor(http, sandboxId) {
423
- this.http = http;
424
- this.sandboxId = sandboxId;
425
- this.lines = new LinesClient(http);
426
- }
427
- /**
428
- * Attach a line to this sandbox. Hub checks that your API key can run this
429
- * sandbox, and each turn runs as a short-lived child of that key. Attaching
430
- * again with the same options returns the same attachment.
431
- */
432
- async attach(options) {
433
- const lineId = await this.lines.resolve(options.number);
434
- const { number: _number, ...rest } = options;
435
- return (await hubData(await this.http.fetch(`/v1/lines/${encodeURIComponent(lineId)}/attachment`, json("PUT", {
436
- ...rest,
437
- sandboxId: this.sandboxId
438
- })))).attachment;
439
- }
440
- /** Lines attached to this sandbox. */
441
- async list() {
442
- return this.lines.list({ sandboxId: this.sandboxId });
443
- }
444
- /** Detach a line (by id or address) from this sandbox. */
445
- async detach(number) {
446
- const lineId = await this.lines.resolve(number);
447
- const line = await this.lines.get(lineId);
448
- if (line.attachment && line.attachment.sandboxId !== this.sandboxId) throw new ValidationError(`Line ${lineId} is attached to another sandbox`);
449
- await hubData(await this.http.fetch(`/v1/lines/${encodeURIComponent(lineId)}/attachment`, { method: "DELETE" }));
450
- }
451
- };
452
- //#endregion
453
233
  //#region src/normalize.ts
454
234
  /**
455
235
  * Normalize a raw `connection` payload from the Sandbox API into the SDK's
@@ -521,6 +301,58 @@ function normalizeSandboxShape(raw) {
521
301
  };
522
302
  }
523
303
  //#endregion
304
+ //#region src/managed-process.ts
305
+ var ManagedProcessClient = class {
306
+ constructor(request, environmentId) {
307
+ this.request = request;
308
+ this.environmentId = environmentId;
309
+ }
310
+ async call(method, id, spec, options) {
311
+ if (typeof id !== "string" || !id.length || id.length > 256) throw new ValidationError("Invalid managed process id");
312
+ const headers = new Headers({ "Content-Type": "application/json" });
313
+ if (options?.sessionId) headers.set("X-Session-Id", options.sessionId);
314
+ const response = await this.request(method === "POST" ? "/process/jobs" : `/process/jobs/${encodeURIComponent(id)}`, {
315
+ method,
316
+ headers,
317
+ ...spec ? { body: JSON.stringify(spec) } : {}
318
+ });
319
+ const text = await response.text();
320
+ let value;
321
+ try {
322
+ value = JSON.parse(text);
323
+ } catch {
324
+ if (!response.ok) throw parseErrorResponse(response.status, text, void 0, response.headers);
325
+ throw new ValidationError("Managed process response is not JSON");
326
+ }
327
+ const envelope = value;
328
+ if (method !== "POST" && response.status === 404 && envelope?.error?.code === "MANAGED_PROCESS_NOT_FOUND") return null;
329
+ if (!response.ok) throw parseErrorResponse(response.status, text, void 0, response.headers);
330
+ const record = envelope?.data;
331
+ if (envelope?.success !== true || record?.schema !== 1 || record.spec?.id !== id || record.environmentId !== this.environmentId || ![
332
+ "queued",
333
+ "running",
334
+ "retrying",
335
+ "stopping",
336
+ "succeeded",
337
+ "failed",
338
+ "cancelled",
339
+ "expired"
340
+ ].includes(record.state) || !Number.isSafeInteger(record.attempt) || record.attempt < 0 || typeof record.digest !== "string" || !/^[a-f0-9]{64}$/.test(record.digest)) throw new ValidationError("Managed process response has invalid identity or state");
341
+ return record;
342
+ }
343
+ async submit(spec, options) {
344
+ const record = await this.call("POST", spec.id, spec, options);
345
+ if (!record) throw new ValidationError("Managed process admission returned no record");
346
+ return record;
347
+ }
348
+ get(id, options) {
349
+ return this.call("GET", id, void 0, options);
350
+ }
351
+ cancel(id, options) {
352
+ return this.call("DELETE", id, void 0, options);
353
+ }
354
+ };
355
+ //#endregion
524
356
  //#region src/capabilities.ts
525
357
  function invalidCapabilities(message) {
526
358
  throw new ServerError(`Capability discovery returned ${message}`, 502, {
@@ -6387,6 +6219,10 @@ var SandboxInstance = class SandboxInstance {
6387
6219
  */
6388
6220
  get process() {
6389
6221
  return {
6222
+ jobs: new ManagedProcessClient(async (path, init) => {
6223
+ await this.ensureRunning();
6224
+ return this.runtimeFetch(path, init);
6225
+ }, this.id),
6390
6226
  ensureDevServer: (options) => this.processEnsureDevServer(options),
6391
6227
  spawn: (command, options) => this.processSpawn(command, options),
6392
6228
  spawnExact: (executable, args, options) => this.processSpawnExact(executable, args, options),
@@ -8595,9 +8431,7 @@ var SandboxInstance = class SandboxInstance {
8595
8431
  for (let index = 0; index < binary.length; index += 1) content[index] = binary.charCodeAt(index);
8596
8432
  if (content.length !== raw.sizeBytes) throw new ServerError("Native rollout byte count mismatch");
8597
8433
  const subtle = globalThis.crypto?.subtle;
8598
- if (!subtle) throw new ServerError("Native rollout verification requires Web Crypto");
8599
- const digest = await subtle.digest("SHA-256", content);
8600
- if (`sha256:${Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, "0")).join("")}` !== raw.sha256) throw new ServerError("Native rollout SHA-256 mismatch");
8434
+ if ((subtle ? `sha256:${Array.from(new Uint8Array(await subtle.digest("SHA-256", content)), (byte) => byte.toString(16).padStart(2, "0")).join("")}` : `sha256:${(await import("node:crypto")).createHash("sha256").update(content).digest("hex")}`) !== raw.sha256) throw new ServerError("Native rollout SHA-256 mismatch");
8601
8435
  let exported;
8602
8436
  try {
8603
8437
  exported = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(content));
@@ -8606,7 +8440,8 @@ var SandboxInstance = class SandboxInstance {
8606
8440
  }
8607
8441
  const native = typeof exported === "object" && exported !== null && !Array.isArray(exported) ? exported : void 0;
8608
8442
  const info = native?.info;
8609
- if (typeof info !== "object" || info === null || Array.isArray(info) || info.id !== raw.nativeSessionId || !Array.isArray(native?.messages)) throw new ServerError("Native rollout session ID mismatch");
8443
+ if (typeof info !== "object" || info === null || Array.isArray(info) || info.id !== raw.nativeSessionId) throw new ServerError("Native rollout session ID mismatch");
8444
+ if (!Array.isArray(native?.messages)) throw new ServerError("Malformed native rollout content");
8610
8445
  return {
8611
8446
  ...raw,
8612
8447
  content
@@ -9026,4 +8861,4 @@ function quoteForShell(value) {
9026
8861
  return `'${value.replace(/'/g, "'\\''")}'`;
9027
8862
  }
9028
8863
  //#endregion
9029
- export { SandboxLines as A, collectAgentFinalMessageText as C, normalizeConnection as D, isToolBearingEvent as E, otelTraceIdForTangleTrace as F, toOtelJson as I, rewrapResponse as M, buildTraceExportPayload as N, normalizeSandboxShape as O, exportTraceBundle as P, applySandboxEventText as S, getSandboxEventText as T, InteractiveSessionController as _, normalizeStartupDiagnostics as a, TERMINAL_WS_ECHO_SUBPROTOCOL as b, MAX_EGRESS_DENIALS_LIMIT as c, InteractiveSessionHandle as d, agentInteractiveSessionPromptRequestDigest as f, BrowserInteractiveSessionController as g, createInteractiveTerminalSession as h, normalizeSandboxCreateReceipt as i, lineInstanceKey as j, LinesClient as k, SandboxTaskSession as l, createInteractiveTerminalCapture as m, createSandboxInstanceFromResponse as n, WorkspaceImages as o, InteractiveTerminalFrameLog as p, normalizeCaptureProof as r, GPU_LEASE_PROVIDER_NAMES as s, SandboxInstance as t, SandboxSession as u, TerminalStream as v, collectAgentResponseText as w, requestInteractiveSessionToken as x, TerminalStreamError as y };
8864
+ export { rewrapResponse as A, collectAgentFinalMessageText as C, ManagedProcessClient as D, isToolBearingEvent as E, exportTraceBundle as M, otelTraceIdForTangleTrace as N, normalizeConnection as O, toOtelJson as P, applySandboxEventText as S, getSandboxEventText as T, InteractiveSessionController as _, normalizeStartupDiagnostics as a, TERMINAL_WS_ECHO_SUBPROTOCOL as b, MAX_EGRESS_DENIALS_LIMIT as c, InteractiveSessionHandle as d, agentInteractiveSessionPromptRequestDigest as f, BrowserInteractiveSessionController as g, createInteractiveTerminalSession as h, normalizeSandboxCreateReceipt as i, buildTraceExportPayload as j, normalizeSandboxShape as k, SandboxTaskSession as l, createInteractiveTerminalCapture as m, createSandboxInstanceFromResponse as n, WorkspaceImages as o, InteractiveTerminalFrameLog as p, normalizeCaptureProof as r, GPU_LEASE_PROVIDER_NAMES as s, SandboxInstance as t, SandboxSession as u, TerminalStream as v, collectAgentResponseText as w, requestInteractiveSessionToken as x, TerminalStreamError as y };