@tangle-network/sandbox 0.60.78-develop.20261017134105.a6b32a2 → 0.60.78-develop.20261021201434.3bcd5ef

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 (66) hide show
  1. package/README.md +61 -0
  2. package/dist/agent/index.d.ts +4 -4
  3. package/dist/agent/index.js +5 -5
  4. package/dist/agent/preview.d.ts +1 -1
  5. package/dist/agent/preview.js +2 -2
  6. package/dist/{agent-run-outcome-CTEpjCEZ.d.ts → agent-run-outcome-brwJbH5S.d.ts} +1 -1
  7. package/dist/auth/index.d.ts +2 -2
  8. package/dist/auth/index.js +5 -5
  9. package/dist/{backend-types-D6bYbvMB.js → backend-types-CLvdSX8V.js} +41 -1
  10. package/dist/{browser-interactive-control-controller-rpTbyvAS.d.ts → browser-interactive-control-controller-CvObO_Kf.d.ts} +1 -1
  11. package/dist/{browser-interactive-control-controller-BJf0P_J4.js → browser-interactive-control-controller-DHx53yre.js} +16 -1
  12. package/dist/{chunked-upload-DtIvkKNo.js → chunked-upload-DN2twsUu.js} +2 -59
  13. package/dist/{chunked-upload-file-DnsHEjg0.js → chunked-upload-file-Dpv1YsoA.js} +2 -1
  14. package/dist/{cli-auth-bundle-cSJjPeFF.js → cli-auth-bundle-CFeHsq-5.js} +23 -11
  15. package/dist/{client-R1tw-4Px.js → client-CgtR203z.js} +3349 -3341
  16. package/dist/client-Dr8qasCR.d.ts +6076 -0
  17. package/dist/collaboration/index.d.ts +1 -1
  18. package/dist/collaboration/index.js +1 -1
  19. package/dist/{collaboration-DaJU5O0E.js → collaboration-g_HzXa6f.js} +5 -5
  20. package/dist/core.d.ts +7 -7
  21. package/dist/core.js +7 -6
  22. package/dist/direct-http2-Dar5erTH.js +99 -0
  23. package/dist/{errors-DSJBKmGZ.js → errors-BfbOP_rx.js} +171 -22
  24. package/dist/{index-DO7GVpk_.d.ts → index-C8VSFtWl.d.ts} +1 -1
  25. package/dist/{index-DZ27pdB8.d.ts → index-CVjTnRWP.d.ts} +1 -1
  26. package/dist/{sandbox-CoIGxzm_.d.ts → index-D5dVNm76.d.ts} +2117 -1519
  27. package/dist/index.d.ts +12 -4704
  28. package/dist/index.js +40 -15
  29. package/dist/intelligence/index.js +1 -1
  30. package/dist/interactive-control.d.ts +1 -1
  31. package/dist/interactive-control.js +1 -1
  32. package/dist/{interactive-controller-CJ24g8Va.js → interactive-controller-OAsASPd_.js} +662 -620
  33. package/dist/interactive-controller-nMhGqXxq.d.ts +41 -0
  34. package/dist/keep-alive-fetch-BBzJDWyt.js +247 -0
  35. package/dist/{lines-DodQslsf.d.ts → lines-C5CPSg8n.d.ts} +21 -17
  36. package/dist/lines-C5ER4aN_.js +298 -0
  37. package/dist/lines.d.ts +1 -1
  38. package/dist/lines.js +1 -295
  39. package/dist/{local-cli-auth-CBV7Vjk5.js → local-cli-auth-D-CQ0-ub.js} +1 -1
  40. package/dist/{mcp-local-DjryqUiY.js → mcp-local-BjLG7VHY.js} +1 -1
  41. package/dist/{preview-wpGGk0bu.d.ts → preview-COO7TSBk.d.ts} +3 -3
  42. package/dist/public-templates-BDrchm0J.d.ts +80 -0
  43. package/dist/public-templates.d.ts +2 -0
  44. package/dist/public-templates.js +173 -0
  45. package/dist/{raw-evidence-archive-Br5a3xZ_.js → raw-evidence-archive-CDYDqHNv.js} +161 -69
  46. package/dist/runtime.d.ts +49 -41
  47. package/dist/runtime.js +8 -8
  48. package/dist/{sandbox-C7Tk62qn.js → sandbox-BrZxAq11.js} +9048 -8939
  49. package/dist/{secp256k1-Dx2XABHz.js → secp256k1-CmLpsmWl.js} +1 -1
  50. package/dist/session-gateway/index.d.ts +23 -67
  51. package/dist/session-gateway/index.js +578 -451
  52. package/dist/tangle/index.d.ts +1 -1
  53. package/dist/tangle/index.js +1 -1
  54. package/dist/{tangle-Ba4Kz5zT.js → tangle-GiPBak5X.js} +176 -169
  55. package/dist/terminal-stream-types-ClZCArRg.d.ts +662 -0
  56. package/dist/{types-B_QF-iHm.d.ts → types-CtH0GRql.d.ts} +6161 -5812
  57. package/package.json +11 -6
  58. package/dist/client-Lhxo82x1.d.ts +0 -1261
  59. package/dist/errors-mPL-qvgF.d.ts +0 -347
  60. package/dist/index-DRto9Ijb.d.ts +0 -579
  61. package/dist/managed-process-B7WfqKmi.d.ts +0 -15
  62. package/dist/terminal-stream-jdYomM1m.d.ts +0 -389
  63. /package/dist/{cli-auth-bundle-ODe06Ts7.d.ts → cli-auth-bundle-Dyw3hCGx.d.ts} +0 -0
  64. /package/dist/{line-application-Cq6dJLBD.js → line-application-DY9ZTdgF.js} +0 -0
  65. /package/dist/{preview-operations-DqSo-IBm.js → preview-operations-Ca02vPDJ.js} +0 -0
  66. /package/dist/{utils-B7_9Hl_z.js → utils-BGvM02yJ.js} +0 -0
@@ -0,0 +1,41 @@
1
+ import { o as TerminalStreamReconnectAuthority, u as ScopedToken } from "./terminal-stream-types-ClZCArRg.js";
2
+ import { rr as TerminalStream } from "./types-CtH0GRql.js";
3
+ import { a as InteractiveSessionControlController, c as InteractiveSessionIdentity, f as InteractiveAttachOptions, h as InteractiveRequestOptions, n as BrowserInteractiveSessionControlControllerOptions, o as InteractiveSessionControlControllerOptions, s as InteractiveSessionControlTransport } from "./browser-interactive-control-controller-CvObO_Kf.js";
4
+ import { AgentInteractiveSessionRef } from "@tangle-network/agent-interface";
5
+
6
+ //#region src/interactive-controller.d.ts
7
+ /** The request fields supplied by an attach caller before control is claimed. */
8
+ type InteractiveAttachRequest = Omit<InteractiveAttachOptions, "control">;
9
+ /** Transport used by the status → claim → WebSocket controller. */
10
+ interface InteractiveSessionControllerTransport extends InteractiveSessionControlTransport {
11
+ attach(sessionId: string, ref: AgentInteractiveSessionRef, request: InteractiveAttachOptions, options?: InteractiveRequestOptions, reconnectAuthority?: TerminalStreamReconnectAuthority): Promise<TerminalStream>;
12
+ }
13
+ interface InteractiveSessionControllerOptions extends InteractiveSessionControlControllerOptions {}
14
+ /**
15
+ * Attach-capable controller for one exact interactive process.
16
+ *
17
+ * Control ownership lives in the dependency-light base controller. This layer
18
+ * adds only the terminal attach operation after that ownership is resolved.
19
+ */
20
+ declare class InteractiveSessionController extends InteractiveSessionControlController {
21
+ private readonly attachTransport;
22
+ private attachInFlight?;
23
+ constructor(attachTransport: InteractiveSessionControllerTransport, options: InteractiveSessionControllerOptions);
24
+ attach(request: InteractiveAttachRequest, requestOptions?: InteractiveRequestOptions): Promise<TerminalStream>;
25
+ /**
26
+ * Open a stream for a claim returned by this controller's `resolve()`.
27
+ * The controller releases that claim when the stream cannot be opened.
28
+ */
29
+ attachWithIdentity(identity: InteractiveSessionIdentity, request: InteractiveAttachRequest, requestOptions?: InteractiveRequestOptions): Promise<TerminalStream>;
30
+ }
31
+ /** Browser transport options for the attach-capable controller. */
32
+ interface BrowserInteractiveSessionControllerOptions extends InteractiveSessionControllerOptions, BrowserInteractiveSessionControlControllerOptions {
33
+ /** Mint a future session-runtime token for every browser terminal dial. */
34
+ terminalTokenProvider?: (signal?: AbortSignal) => Promise<ScopedToken>;
35
+ }
36
+ /** Concrete controller for browser deep links and terminal attachment. */
37
+ declare class BrowserInteractiveSessionController extends InteractiveSessionController {
38
+ constructor(options: BrowserInteractiveSessionControllerOptions);
39
+ }
40
+ //#endregion
41
+ export { InteractiveSessionControllerOptions as a, InteractiveSessionController as i, BrowserInteractiveSessionControllerOptions as n, InteractiveSessionControllerTransport as o, InteractiveAttachRequest as r, BrowserInteractiveSessionController as t };
@@ -0,0 +1,247 @@
1
+ //#region src/lib/keep-alive-fetch.ts
2
+ /** How long an idle SDK socket stays open. The servers keep theirs open for 35 s and more. */
3
+ const KEEP_ALIVE_TIMEOUT_MS = 6e4;
4
+ const GLOBAL_DISPATCHER = Symbol.for("undici.globalDispatcher.1");
5
+ /** Report a span. A hook that throws must never fail an SDK call. */
6
+ function emitTiming(hook, entry) {
7
+ if (!hook) return;
8
+ try {
9
+ hook(entry);
10
+ } catch {}
11
+ }
12
+ /** Milliseconds, at 0.1 ms: the resolution these spans can honestly claim. */
13
+ function ms(value) {
14
+ return Math.round(value * 10) / 10;
15
+ }
16
+ let cachedHost;
17
+ let cachedAgent = null;
18
+ function readGlobalDispatcher() {
19
+ const read = () => globalThis[GLOBAL_DISPATCHER];
20
+ const host = read();
21
+ if (host) return host;
22
+ globalThis.Headers;
23
+ return read();
24
+ }
25
+ /** The options undici stored on an Agent, if this version keeps them where we look. */
26
+ function agentOptions(agent) {
27
+ for (const symbol of Object.getOwnPropertySymbols(agent)) {
28
+ if (symbol.description !== "options") continue;
29
+ const value = agent[symbol];
30
+ if (value && typeof value === "object") return value;
31
+ }
32
+ }
33
+ function buildKeepAliveAgent(host) {
34
+ const AgentClass = Object.getPrototypeOf(host)?.constructor;
35
+ if (typeof AgentClass !== "function" || AgentClass.name !== "Agent") return null;
36
+ const options = agentOptions(host);
37
+ if (!options || options.keepAliveTimeout !== void 0) return null;
38
+ try {
39
+ return new AgentClass({
40
+ ...options,
41
+ keepAliveTimeout: KEEP_ALIVE_TIMEOUT_MS
42
+ });
43
+ } catch {
44
+ return null;
45
+ }
46
+ }
47
+ /**
48
+ * The dispatcher SDK calls pass to `fetch`, or `undefined` to keep the host's.
49
+ * Rebuilt when the host replaces its global dispatcher, so a test that installs
50
+ * a mock agent, or an app that reconfigures its own, is never bypassed.
51
+ */
52
+ function keepAliveDispatcher() {
53
+ const host = readGlobalDispatcher();
54
+ if (!host) return void 0;
55
+ if (host !== cachedHost) {
56
+ const previous = cachedAgent;
57
+ cachedHost = host;
58
+ cachedAgent = buildKeepAliveAgent(host);
59
+ Promise.resolve(previous?.close?.()).catch(() => void 0);
60
+ }
61
+ return cachedAgent ?? void 0;
62
+ }
63
+ /**
64
+ * In-flight requests by undici request. A response whose body is never read
65
+ * never completes, so the map is bounded rather than trusted to drain.
66
+ */
67
+ const MAX_LIVE_CAPTURES = 256;
68
+ const captures = /* @__PURE__ */ new Map();
69
+ const socketMarks = /* @__PURE__ */ new WeakMap();
70
+ let dispatching;
71
+ let observing;
72
+ function subscribeChannels(channels) {
73
+ const now = () => performance.now();
74
+ channels.subscribe("net.client.socket", (message) => {
75
+ const socket = message.socket;
76
+ if (!socket || captures.size === 0) return;
77
+ const marks = {
78
+ createdAt: now(),
79
+ claimed: false
80
+ };
81
+ socketMarks.set(socket, marks);
82
+ const once = socket.once;
83
+ if (typeof once !== "function") return;
84
+ once.call(socket, "lookup", () => {
85
+ marks.lookupAt = now();
86
+ });
87
+ once.call(socket, "connect", () => {
88
+ marks.connectAt = now();
89
+ });
90
+ once.call(socket, "secureConnect", () => {
91
+ marks.secureAt = now();
92
+ });
93
+ });
94
+ channels.subscribe("undici:request:create", (message) => {
95
+ const request = message.request;
96
+ if (!dispatching || !request) return;
97
+ dispatching.request = request;
98
+ captures.set(request, dispatching);
99
+ if (captures.size > MAX_LIVE_CAPTURES) {
100
+ const oldest = captures.keys().next().value;
101
+ if (oldest !== void 0) captures.delete(oldest);
102
+ }
103
+ });
104
+ channels.subscribe("undici:client:sendHeaders", (message) => {
105
+ const { request, socket } = message;
106
+ const capture = request ? captures.get(request) : void 0;
107
+ if (!capture) return;
108
+ capture.sentAt = now();
109
+ const marks = socket ? socketMarks.get(socket) : void 0;
110
+ if (marks && !marks.claimed) {
111
+ marks.claimed = true;
112
+ capture.marks = marks;
113
+ }
114
+ });
115
+ channels.subscribe("undici:request:headers", (message) => {
116
+ const request = message.request;
117
+ const capture = request ? captures.get(request) : void 0;
118
+ if (capture) capture.headersAt = now();
119
+ });
120
+ channels.subscribe("undici:request:trailers", (message) => {
121
+ const request = message.request;
122
+ const capture = request ? captures.get(request) : void 0;
123
+ if (!capture) return;
124
+ capture.doneAt = now();
125
+ captures.delete(request);
126
+ capture.finish();
127
+ });
128
+ channels.subscribe("undici:request:error", (message) => {
129
+ const request = message.request;
130
+ const capture = request ? captures.get(request) : void 0;
131
+ if (!capture) return;
132
+ capture.failed = true;
133
+ capture.doneAt = now();
134
+ captures.delete(request);
135
+ capture.finish();
136
+ });
137
+ }
138
+ /** Subscribe once. False where the runtime has no Node diagnostics channels. */
139
+ function observeRequests() {
140
+ observing ??= import("node:diagnostics_channel").then((channels) => {
141
+ if (typeof channels.subscribe !== "function") return false;
142
+ subscribeChannels(channels);
143
+ return true;
144
+ }, () => false);
145
+ return observing;
146
+ }
147
+ /** A dispatcher that tells `capture` which undici request its dispatch created. */
148
+ function tagged(base, capture) {
149
+ return new Proxy(base, { get(target, property) {
150
+ if (property === "dispatch") return (options, handler) => {
151
+ dispatching = capture;
152
+ try {
153
+ return target.dispatch(options, handler);
154
+ } finally {
155
+ dispatching = void 0;
156
+ }
157
+ };
158
+ const value = Reflect.get(target, property, target);
159
+ return typeof value === "function" ? value.bind(target) : value;
160
+ } });
161
+ }
162
+ function phasesOf(capture) {
163
+ if (capture.sentAt === void 0 || capture.headersAt === void 0) return;
164
+ const phases = { ttfbMs: ms(capture.headersAt - capture.sentAt) };
165
+ const marks = capture.marks;
166
+ if (marks?.connectAt !== void 0) {
167
+ if (marks.lookupAt !== void 0) phases.dnsMs = ms(marks.lookupAt - marks.createdAt);
168
+ phases.connectMs = ms(marks.connectAt - (marks.lookupAt ?? marks.createdAt));
169
+ if (marks.secureAt !== void 0) phases.tlsMs = ms(marks.secureAt - marks.connectAt);
170
+ }
171
+ if (capture.doneAt !== void 0 && !capture.failed) phases.bodyMs = ms(capture.doneAt - capture.headersAt);
172
+ return phases;
173
+ }
174
+ /**
175
+ * `fetch` for an SDK call: the keep-alive dispatcher on Node, and a timing
176
+ * entry per request when the client has a hook. Calls `globalThis.fetch` at
177
+ * call time, so a caller's fetch override still receives the request.
178
+ */
179
+ async function fetchWithKeepAlive(url, init, options) {
180
+ let dispatcher = keepAliveDispatcher();
181
+ const hook = options.onTiming;
182
+ if (!hook) return dispatcher ? globalThis.fetch(url, {
183
+ ...init,
184
+ dispatcher
185
+ }) : globalThis.fetch(url, init);
186
+ const startedAt = performance.now();
187
+ const method = init.method ?? "GET";
188
+ const observed = await observeRequests();
189
+ const host = dispatcher ?? (observed ? readGlobalDispatcher() : void 0);
190
+ let capture;
191
+ let finished;
192
+ if (observed && host) {
193
+ let finish = () => {};
194
+ finished = new Promise((resolve) => {
195
+ finish = resolve;
196
+ });
197
+ capture = {
198
+ startedAt,
199
+ finish
200
+ };
201
+ dispatcher = tagged(host, capture);
202
+ }
203
+ let response;
204
+ try {
205
+ response = await globalThis.fetch(url, dispatcher ? {
206
+ ...init,
207
+ dispatcher
208
+ } : init);
209
+ } catch (error) {
210
+ if (capture?.request) captures.delete(capture.request);
211
+ emitTiming(hook, {
212
+ name: "sdk.request",
213
+ durMs: ms(performance.now() - startedAt),
214
+ desc: "failed",
215
+ method,
216
+ path: options.path,
217
+ ...capture ? { failure: {
218
+ requestCreated: capture.request !== void 0,
219
+ requestHeadersSent: capture.sentAt !== void 0,
220
+ responseHeadersReceived: capture.headersAt !== void 0
221
+ } } : {}
222
+ });
223
+ throw error;
224
+ }
225
+ const report = () => {
226
+ const phases = capture ? phasesOf(capture) : void 0;
227
+ const socket = phases ? capture?.marks ? "new" : "reused" : void 0;
228
+ const endedAt = capture?.doneAt ?? capture?.headersAt ?? performance.now();
229
+ const serverTiming = response.headers.get("server-timing");
230
+ emitTiming(hook, {
231
+ name: "sdk.request",
232
+ durMs: ms(endedAt - startedAt),
233
+ desc: socket ? `socket=${socket}` : "",
234
+ method,
235
+ path: options.path,
236
+ status: response.status,
237
+ ...socket ? { socket } : {},
238
+ ...phases ? { phases } : {},
239
+ ...serverTiming ? { serverTiming } : {}
240
+ });
241
+ };
242
+ if (capture?.request && finished) finished.then(report);
243
+ else report();
244
+ return response;
245
+ }
246
+ //#endregion
247
+ export { fetchWithKeepAlive as n, emitTiming as t };
@@ -1,4 +1,4 @@
1
- import { B as CreateSandboxOptions, d as BackendConfig } from "./types-B_QF-iHm.js";
1
+ import { Sa as BackendConfig, ar as CreateSandboxOptions } from "./types-CtH0GRql.js";
2
2
 
3
3
  //#region src/line-application.d.ts
4
4
  /** Bounded callback request bytes after canonicalization, including JSON framing. */
@@ -73,7 +73,7 @@ declare function parseLineApplicationRequest(value: unknown): LineApplicationReq
73
73
  /** A raw agent response is not this receipt. Applications report only settled output. */
74
74
  declare function parseLineApplicationResult(value: unknown, request: Pick<LineApplicationRequest, "binding" | "messageId" | "attachmentId" | "acceptedExecutionId">): LineApplicationResult;
75
75
  //#endregion
76
- //#region src/lines.d.ts
76
+ //#region src/line-types.d.ts
77
77
  /** The transport a line carries. */
78
78
  type LineTransport = "imessage" | "sms" | "whatsapp" | "email" | "telegram" | "voice";
79
79
  /** What a role's members share and may do in the attached sandbox. */
@@ -338,20 +338,6 @@ type LineApplicationAttachOptions = Omit<LineAttachOptions, "mode" | "members" |
338
338
  };
339
339
  limits?: Omit<Partial<LineLimits>, "allowance">;
340
340
  };
341
- /**
342
- * The instance key that serves one member: `keyPrefix` plus the first 32 hex
343
- * characters of the SHA-256 of the member's address as Hub stores it (E.164,
344
- * or a lowercased email). It depends only on the prefix and the address, so a
345
- * person keeps their box across re-attaches, and your own code can reach it
346
- * with `client.instances.ensure({ key })`. This helper applies only to
347
- * address-bound members. Hub derives a different key for `subjectId` members.
348
- */
349
- declare function lineInstanceKey(keyPrefix: string, address: string): Promise<string>;
350
- /** Stable setup retry identity. This label never grants profile or line access. */
351
- declare function profileChannelReference(profileId: string, input: Pick<LineFromConnectionInput, "connectionId" | "transport"> & {
352
- phoneNumberId?: string;
353
- address?: string;
354
- }): Promise<string>;
355
341
  /** Fields shared by line creation from an owned Hub connection. */
356
342
  interface LineFromConnectionCommon {
357
343
  connectionId: string;
@@ -573,6 +559,24 @@ interface LineMessage {
573
559
  interface LinesHttpClient {
574
560
  fetch(path: string, options?: RequestInit): Promise<Response>;
575
561
  }
562
+ //#endregion
563
+ //#region src/line-identity.d.ts
564
+ /**
565
+ * The instance key that serves one member: `keyPrefix` plus the first 32 hex
566
+ * characters of the SHA-256 of the member's address as Hub stores it (E.164,
567
+ * or a lowercased email). It depends only on the prefix and the address, so a
568
+ * person keeps their box across re-attaches, and your own code can reach it
569
+ * with `client.instances.ensure({ key })`. This helper applies only to
570
+ * address-bound members. Hub derives a different key for `subjectId` members.
571
+ */
572
+ declare function lineInstanceKey(keyPrefix: string, address: string): Promise<string>;
573
+ /** Stable setup retry identity. This label never grants profile or line access. */
574
+ declare function profileChannelReference(profileId: string, input: Pick<LineFromConnectionInput, "connectionId" | "transport"> & {
575
+ phoneNumberId?: string;
576
+ address?: string;
577
+ }): Promise<string>;
578
+ //#endregion
579
+ //#region src/lines.d.ts
576
580
  /** `client.lines`: your lines, their members and their threads. */
577
581
  declare class LinesClient {
578
582
  private readonly http;
@@ -685,4 +689,4 @@ declare class SandboxLines {
685
689
  detach(number: string): Promise<void>;
686
690
  }
687
691
  //#endregion
688
- export { LineSendReceipt as A, lineInstanceKey as B, LineReplyCode as C, LineRespondView as D, LineRespondAgent as E, LineVoice as F, LineApplicationRequest as G, LINE_APPLICATION_REPLY_MAX_CHARS as H, LineVoiceOptions as I, LineApplicationView as J, LineApplicationResult as K, LinesClient as L, LineSenderVerificationStart as M, LineThread as N, LineRole as O, LineTransport as P, LinesHttpClient as R, LineReminderPreferences as S, LineReplyGate as T, LINE_APPLICATION_REQUEST_MAX_BYTES as U, profileChannelReference as V, LineApplication as W, parseLineApplicationResult as X, parseLineApplicationRequest as Y, LineMemberPatch as _, LineApplicationAttachOptions as a, LineNumberInventory as b, LineAttachmentReauthorization as c, LineImage as d, LineInstanceAttachOptions as f, LineMemberInstance as g, LineMember as h, LineAllowanceSubject as i, LineSenderVerification as j, LineSendInput as k, LineExecutionKey as l, LineLimits as m, LineAgentRolePolicy as n, LineAttachOptions as o, LineInstanceCreate as p, LineApplicationState as q, LineAllowance as r, LineAttachment as s, Line as t, LineFromConnectionInput as u, LineMemberSpec as v, LineReplyCodeInput as w, LineProvider as x, LineMessage as y, SandboxLines as z };
692
+ export { LineRespondAgent as A, LineVoiceOptions as B, LineMessage as C, LineReplyCode as D, LineReminderPreferences as E, LineSenderVerification as F, LineApplicationRequest as G, LINE_APPLICATION_REPLY_MAX_CHARS as H, LineSenderVerificationStart as I, LineApplicationView as J, LineApplicationResult as K, LineThread as L, LineRole as M, LineSendInput as N, LineReplyCodeInput as O, LineSendReceipt as P, LineTransport as R, LineMemberSpec as S, LineProvider as T, LINE_APPLICATION_REQUEST_MAX_BYTES as U, LinesHttpClient as V, LineApplication as W, parseLineApplicationResult as X, parseLineApplicationRequest as Y, LineInstanceCreate as _, Line as a, LineMemberInstance as b, LineAllowanceSubject as c, LineAttachment as d, LineAttachmentReauthorization as f, LineInstanceAttachOptions as g, LineImage as h, profileChannelReference as i, LineRespondView as j, LineReplyGate as k, LineApplicationAttachOptions as l, LineFromConnectionInput as m, SandboxLines as n, LineAgentRolePolicy as o, LineExecutionKey as p, LineApplicationState as q, lineInstanceKey as r, LineAllowance as s, LinesClient as t, LineAttachOptions as u, LineLimits as v, LineNumberInventory as w, LineMemberPatch as x, LineMember as y, LineVoice as z };
@@ -0,0 +1,298 @@
1
+ import { T as ValidationError, n as parseErrorResponse } from "./errors-BfbOP_rx.js";
2
+ //#region src/line-identity.ts
3
+ /**
4
+ * The instance key that serves one member: `keyPrefix` plus the first 32 hex
5
+ * characters of the SHA-256 of the member's address as Hub stores it (E.164,
6
+ * or a lowercased email). It depends only on the prefix and the address, so a
7
+ * person keeps their box across re-attaches, and your own code can reach it
8
+ * with `client.instances.ensure({ key })`. This helper applies only to
9
+ * address-bound members. Hub derives a different key for `subjectId` members.
10
+ */
11
+ async function lineInstanceKey(keyPrefix, address) {
12
+ const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(address));
13
+ return `${keyPrefix}${Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, "0")).join("").slice(0, 32)}`;
14
+ }
15
+ /** Stable setup retry identity. This label never grants profile or line access. */
16
+ async function profileChannelReference(profileId, input) {
17
+ if (!/^ap_[A-Za-z0-9_-]{1,61}$/.test(profileId)) throw new ValidationError("Use a stored Platform profile ID");
18
+ const identity = JSON.stringify([
19
+ input.connectionId,
20
+ input.transport,
21
+ input.phoneNumberId ?? null,
22
+ input.address?.trim().toLowerCase() ?? null
23
+ ]);
24
+ const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(identity));
25
+ return `profile:${profileId}:${Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, "0")).join("").slice(0, 32)}`;
26
+ }
27
+ //#endregion
28
+ //#region src/lines.ts
29
+ /**
30
+ * Lines: give a sandbox a phone number or messaging address.
31
+ *
32
+ * A line is an address that Tangle Hub receives on, such as an Inkbox
33
+ * iMessage identity or Linq WhatsApp number. Attaching it to a sandbox makes
34
+ * Hub route each inbound message to that sandbox. Each member gets a separate
35
+ * thread in its own agent session. Hub sends the agent's answer on the same
36
+ * line. Hub owns routing, consent (STOP/START), unknown senders and
37
+ * metering, so an app only chooses who may text and in which mode.
38
+ *
39
+ * @example
40
+ * ```ts
41
+ * const line = await client.lines.fromConnection({ connectionId, transport: "imessage" });
42
+ * await box.lines.attach({
43
+ * number: line.id,
44
+ * mode: "personal",
45
+ * members: [{ address: "+15550100001", role: "owner" }],
46
+ * });
47
+ * // Text `line.connect` to `line.routerAddress`, then write to the agent.
48
+ * ```
49
+ *
50
+ * A line can also give every member their own sandbox, so a public line
51
+ * serves each person from an isolated box with its own files:
52
+ *
53
+ * ```ts
54
+ * await client.lines.attach({
55
+ * number: line.id,
56
+ * mode: "shared",
57
+ * members: [{ address: "+15550100001", role: "owner" }],
58
+ * unknownSenders: "guest",
59
+ * roles: { owner: { context: "own", tools: "act" }, guest: { context: "own", tools: "act" } },
60
+ * instance: { keyPrefix: "person:", create: { idleTimeoutSeconds: 600 } },
61
+ * });
62
+ * ```
63
+ */
64
+ const LINE_ID = /^ln_[A-Za-z0-9_-]+$/;
65
+ async function hubData(response) {
66
+ const body = await response.text();
67
+ if (!response.ok) throw parseErrorResponse(response.status, body, void 0, response.headers);
68
+ const parsed = JSON.parse(body);
69
+ if (parsed.success !== true || parsed.data === void 0) throw parseErrorResponse(502, body, void 0, response.headers);
70
+ return parsed.data;
71
+ }
72
+ function json(method, body) {
73
+ return {
74
+ method,
75
+ headers: { "Content-Type": "application/json" },
76
+ body: JSON.stringify(body)
77
+ };
78
+ }
79
+ /** `client.lines`: your lines, their members and their threads. */
80
+ var LinesClient = class {
81
+ constructor(http) {
82
+ this.http = http;
83
+ }
84
+ /**
85
+ * Create a line from an owned Inkbox or Linq connection, or return the line
86
+ * already pinned to that provider identity. Hub owns inbound routing and
87
+ * never re-keys the connection.
88
+ */
89
+ async fromConnection(input) {
90
+ return (await hubData(await this.http.fetch("/v1/lines", json("POST", input)))).line;
91
+ }
92
+ /** Your lines. `sandboxId` narrows to lines attached to that sandbox. */
93
+ async list(options = {}) {
94
+ const params = new URLSearchParams();
95
+ if (options.sandboxId) params.set("sandboxId", options.sandboxId);
96
+ if (options.profileId) params.set("profileId", options.profileId);
97
+ const query = params.size ? `?${params}` : "";
98
+ return (await hubData(await this.http.fetch(`/v1/lines${query}`))).lines;
99
+ }
100
+ /** Supported combinations from the maintained host channel catalog. */
101
+ async providers() {
102
+ return (await hubData(await this.http.fetch("/v1/lines/providers"))).providers;
103
+ }
104
+ /** Metadata only; no reservation and no provider credentials are returned. */
105
+ async numbers(connectionId, transport) {
106
+ const params = new URLSearchParams({
107
+ connectionId,
108
+ transport
109
+ });
110
+ return hubData(await this.http.fetch(`/v1/lines/numbers?${params}`));
111
+ }
112
+ /** Choose the payer/execution authority for a cookie-authenticated attachment. */
113
+ async executionKeys() {
114
+ return (await hubData(await this.http.fetch("/v1/lines/execution-keys"))).keys;
115
+ }
116
+ async get(lineId) {
117
+ return (await hubData(await this.http.fetch(`/v1/lines/${encodeURIComponent(lineId)}`))).line;
118
+ }
119
+ /** A line id for a line id or one of your lines' addresses. */
120
+ async resolve(number) {
121
+ if (LINE_ID.test(number)) return number;
122
+ const line = (await this.list()).find((l) => l.address === number);
123
+ if (!line) throw new ValidationError(`No line with address ${number}`);
124
+ return line.id;
125
+ }
126
+ /** Start a signed Inkbox iMessage owner-handset test for an unattached line. */
127
+ async startSenderVerification(number) {
128
+ const lineId = await this.resolve(number);
129
+ return hubData(await this.http.fetch(`/v1/lines/${encodeURIComponent(lineId)}/sender-verifications`, json("POST", {})));
130
+ }
131
+ /** Read proof state with the same owner API key that started the test. */
132
+ async getSenderVerification(number, testId) {
133
+ if (!/^lsv_[A-Za-z0-9_-]+$/.test(testId)) throw new ValidationError("A valid sender verification id is required");
134
+ const lineId = await this.resolve(number);
135
+ return hubData(await this.http.fetch(`/v1/lines/${encodeURIComponent(lineId)}/sender-verifications/${encodeURIComponent(testId)}`));
136
+ }
137
+ /**
138
+ * Attach a line to member sandboxes or one application callback. Hub checks
139
+ * the owner key and keeps one active attachment. The callback must resolve
140
+ * each declared customer's subject to its own authorized private target.
141
+ */
142
+ async attach(options) {
143
+ const lineId = await this.resolve(options.number);
144
+ const { number: _number, ...rest } = options;
145
+ return (await hubData(await this.http.fetch(`/v1/lines/${encodeURIComponent(lineId)}/attachment`, json("PUT", rest)))).attachment;
146
+ }
147
+ /** Bind the current API key to this same attachment after app key rotation.
148
+ * Hub checks the observed attachment and old key, app key lineage, owner,
149
+ * workspace and sandbox. A race leaves the existing binding unchanged.
150
+ */
151
+ async reauthorizeAttachment(number, expected) {
152
+ if (!/^lat_[A-Za-z0-9_-]+$/.test(expected.expectedAttachmentId)) throw new ValidationError("A valid expected attachment id is required");
153
+ if (!/^key_[A-Za-z0-9_-]+$/.test(expected.expectedRunAsKeyId)) throw new ValidationError("A valid expected execution key id is required");
154
+ const lineId = await this.resolve(number);
155
+ return (await hubData(await this.http.fetch(`/v1/lines/${encodeURIComponent(lineId)}/attachment/reauthorize`, json("PUT", expected)))).attachment;
156
+ }
157
+ /**
158
+ * Detach a line (by id or address), whatever it is attached to. This is
159
+ * the way to detach a line attached with `instance`, which names no
160
+ * sandbox. Each member's own sandbox stays under its instance key. Returns
161
+ * false when the line was not attached.
162
+ */
163
+ async detach(number, options = {}) {
164
+ if (options.expectedAttachmentId !== void 0 && !/^lat_[A-Za-z0-9_-]+$/.test(options.expectedAttachmentId)) throw new ValidationError("Invalid expected attachment identity");
165
+ const lineId = await this.resolve(number);
166
+ return (await hubData(await this.http.fetch(`/v1/lines/${encodeURIComponent(lineId)}/attachment`, {
167
+ method: "DELETE",
168
+ ...options.expectedAttachmentId ? { headers: { "if-match": `"${options.expectedAttachmentId}"` } } : {}
169
+ }))).detached;
170
+ }
171
+ /** Detach only this observed attachment. A replacement is left untouched.
172
+ * The distinct native route makes older hosts refuse rather than ignore
173
+ * the condition. This never falls back to unconditional line detachment.
174
+ */
175
+ async detachAttachment(number, attachmentId) {
176
+ if (!/^[A-Za-z0-9_-]{1,256}$/.test(attachmentId)) throw new ValidationError("A valid expected attachment id is required");
177
+ const lineId = await this.resolve(number);
178
+ return (await hubData(await this.http.fetch(`/v1/lines/${encodeURIComponent(lineId)}/attachments/${encodeURIComponent(attachmentId)}`, { method: "DELETE" }))).detached;
179
+ }
180
+ /**
181
+ * Retire a detached line's Hub routing and free its workspace transport slot.
182
+ * Hub refuses an attached or voice-enabled line. A retry by line id returns
183
+ * false; the provider connection and message history remain.
184
+ */
185
+ async release(number) {
186
+ const lineId = await this.resolve(number);
187
+ return (await hubData(await this.http.fetch(`/v1/lines/${encodeURIComponent(lineId)}`, { method: "DELETE" }))).released;
188
+ }
189
+ /**
190
+ * Take calls for an active Hub line. Without a phone number ID, the line
191
+ * must be Inkbox iMessage; Hub changes its call action and adds
192
+ * `ask_workspace` to the agent. With an owned ph0ny phone number ID, Hub
193
+ * binds that Twilio number to the line's admission hook and leaves the
194
+ * line's provider call settings unchanged.
195
+ */
196
+ async enableVoice(lineId, options) {
197
+ return (await hubData(await this.http.fetch(`/v1/lines/${encodeURIComponent(lineId)}`, json("PATCH", { voice: {
198
+ enabled: true,
199
+ ph0ny: {
200
+ connectionId: options.ph0nyConnectionId,
201
+ agentId: options.ph0nyAgentId,
202
+ ...options.ph0nyPhoneNumberId ? { phoneNumberId: options.ph0nyPhoneNumberId } : {}
203
+ }
204
+ } })))).line;
205
+ }
206
+ /** Stop taking calls on a line: Hub refuses them and Inkbox rejects them. */
207
+ async disableVoice(lineId) {
208
+ return (await hubData(await this.http.fetch(`/v1/lines/${encodeURIComponent(lineId)}`, json("PATCH", { voice: { enabled: false } })))).line;
209
+ }
210
+ /**
211
+ * Queue a proactive message to an active, consenting member. Hub reuses the
212
+ * member's authenticated provider conversation, rechecks STOP immediately
213
+ * before delivery, and defers delivery during the recipient's saved quiet hours.
214
+ */
215
+ async send(lineId, input) {
216
+ return hubData(await this.http.fetch(`/v1/lines/${encodeURIComponent(lineId)}/send`, json("POST", input)));
217
+ }
218
+ /** Read the native outbox receipt. Queued is not a delivery confirmation. */
219
+ async sentMessage(lineId, messageId) {
220
+ return hubData(await this.http.fetch(`/v1/lines/${encodeURIComponent(lineId)}/outbox/${encodeURIComponent(messageId)}`));
221
+ }
222
+ /** Only the recipient's proven message can enable reminders or choose quiet hours. */
223
+ async reminders(lineId, memberId) {
224
+ return hubData(await this.http.fetch(`/v1/lines/${encodeURIComponent(lineId)}/members/${encodeURIComponent(memberId)}/reminders`));
225
+ }
226
+ /** Members of the line's active attachment. */
227
+ members(lineId) {
228
+ const base = `/v1/lines/${encodeURIComponent(lineId)}/members`;
229
+ const http = this.http;
230
+ return {
231
+ async list() {
232
+ return (await hubData(await http.fetch(base))).members;
233
+ },
234
+ async add(spec) {
235
+ return (await hubData(await http.fetch(base, json("POST", spec)))).member;
236
+ },
237
+ async update(memberId, patch) {
238
+ return (await hubData(await http.fetch(`${base}/${encodeURIComponent(memberId)}`, json("PATCH", patch)))).member;
239
+ },
240
+ async remove(memberId) {
241
+ await hubData(await http.fetch(`${base}/${encodeURIComponent(memberId)}`, { method: "DELETE" }));
242
+ }
243
+ };
244
+ }
245
+ /** Read one retained message without depending on a recent-message page. */
246
+ async message(lineId, messageId) {
247
+ return (await hubData(await this.http.fetch(`/v1/lines/${encodeURIComponent(lineId)}/messages/${encodeURIComponent(messageId)}`))).message;
248
+ }
249
+ /** Threads of a line (one per member) and their messages, newest first. */
250
+ threads(lineId) {
251
+ const base = `/v1/lines/${encodeURIComponent(lineId)}/threads`;
252
+ const http = this.http;
253
+ return {
254
+ async list() {
255
+ return (await hubData(await http.fetch(base))).threads;
256
+ },
257
+ async messages(threadId) {
258
+ return (await hubData(await http.fetch(`${base}/${encodeURIComponent(threadId)}/messages`))).messages;
259
+ }
260
+ };
261
+ }
262
+ };
263
+ /** `sandbox.lines`: attach lines to this sandbox. */
264
+ var SandboxLines = class {
265
+ lines;
266
+ constructor(http, sandboxId) {
267
+ this.http = http;
268
+ this.sandboxId = sandboxId;
269
+ this.lines = new LinesClient(http);
270
+ }
271
+ /**
272
+ * Attach a line to this sandbox. Hub checks that your API key can run this
273
+ * sandbox, and each turn runs as a short-lived child of that key. Attaching
274
+ * again with the same options returns the same attachment.
275
+ */
276
+ async attach(options) {
277
+ const lineId = await this.lines.resolve(options.number);
278
+ const { number: _number, ...rest } = options;
279
+ return (await hubData(await this.http.fetch(`/v1/lines/${encodeURIComponent(lineId)}/attachment`, json("PUT", {
280
+ ...rest,
281
+ sandboxId: this.sandboxId
282
+ })))).attachment;
283
+ }
284
+ /** Lines attached to this sandbox. */
285
+ async list() {
286
+ return this.lines.list({ sandboxId: this.sandboxId });
287
+ }
288
+ /** Detach a line (by id or address) from this sandbox. */
289
+ async detach(number) {
290
+ const lineId = await this.lines.resolve(number);
291
+ const line = await this.lines.get(lineId);
292
+ if (!line.attachment) return;
293
+ if (line.attachment.sandboxId !== this.sandboxId) throw new ValidationError(`Line ${lineId} is attached to another sandbox`);
294
+ await this.lines.detachAttachment(lineId, line.attachment.id);
295
+ }
296
+ };
297
+ //#endregion
298
+ export { profileChannelReference as i, SandboxLines as n, lineInstanceKey as r, LinesClient as t };
package/dist/lines.d.ts CHANGED
@@ -1,2 +1,2 @@
1
- import { A as LineSendReceipt, B as lineInstanceKey, C as LineReplyCode, D as LineRespondView, E as LineRespondAgent, F as LineVoice, I as LineVoiceOptions, L as LinesClient, M as LineSenderVerificationStart, N as LineThread, O as LineRole, P as LineTransport, R as LinesHttpClient, S as LineReminderPreferences, T as LineReplyGate, V as profileChannelReference, _ as LineMemberPatch, a as LineApplicationAttachOptions, b as LineNumberInventory, c as LineAttachmentReauthorization, d as LineImage, f as LineInstanceAttachOptions, g as LineMemberInstance, h as LineMember, i as LineAllowanceSubject, j as LineSenderVerification, k as LineSendInput, l as LineExecutionKey, m as LineLimits, n as LineAgentRolePolicy, o as LineAttachOptions, p as LineInstanceCreate, r as LineAllowance, s as LineAttachment, t as Line, u as LineFromConnectionInput, v as LineMemberSpec, w as LineReplyCodeInput, x as LineProvider, y as LineMessage, z as SandboxLines } from "./lines-DodQslsf.js";
1
+ import { A as LineRespondAgent, B as LineVoiceOptions, C as LineMessage, D as LineReplyCode, E as LineReminderPreferences, F as LineSenderVerification, I as LineSenderVerificationStart, L as LineThread, M as LineRole, N as LineSendInput, O as LineReplyCodeInput, P as LineSendReceipt, R as LineTransport, S as LineMemberSpec, T as LineProvider, V as LinesHttpClient, _ as LineInstanceCreate, a as Line, b as LineMemberInstance, c as LineAllowanceSubject, d as LineAttachment, f as LineAttachmentReauthorization, g as LineInstanceAttachOptions, h as LineImage, i as profileChannelReference, j as LineRespondView, k as LineReplyGate, l as LineApplicationAttachOptions, m as LineFromConnectionInput, n as SandboxLines, o as LineAgentRolePolicy, p as LineExecutionKey, r as lineInstanceKey, s as LineAllowance, t as LinesClient, u as LineAttachOptions, v as LineLimits, w as LineNumberInventory, x as LineMemberPatch, y as LineMember, z as LineVoice } from "./lines-C5CPSg8n.js";
2
2
  export { Line, LineAgentRolePolicy, LineAllowance, LineAllowanceSubject, LineApplicationAttachOptions, LineAttachOptions, LineAttachment, LineAttachmentReauthorization, LineExecutionKey, LineFromConnectionInput, LineImage, LineInstanceAttachOptions, LineInstanceCreate, LineLimits, LineMember, LineMemberInstance, LineMemberPatch, LineMemberSpec, LineMessage, LineNumberInventory, LineProvider, LineReminderPreferences, LineReplyCode, LineReplyCodeInput, LineReplyGate, LineRespondAgent, LineRespondView, LineRole, LineSendInput, LineSendReceipt, LineSenderVerification, LineSenderVerificationStart, LineThread, LineTransport, LineVoice, LineVoiceOptions, LinesClient, LinesHttpClient, SandboxLines, lineInstanceKey, profileChannelReference };