@tangle-network/hub-sdk 0.22.0-develop.20260814044321.7b71e30 → 0.22.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.
package/dist/index.js CHANGED
@@ -1,7 +1,277 @@
1
1
  import { SSEChunkParser } from "@tangle-network/sdk-telemetry";
2
+ //#region src/json-init.ts
3
+ /** The init of a request whose body is JSON. Every client builds its bodies
4
+ * here, so the content type cannot drift from the encoding. */
5
+ function jsonInit(method, body) {
6
+ return {
7
+ method,
8
+ body: JSON.stringify(body),
9
+ headers: { "Content-Type": "application/json" }
10
+ };
11
+ }
12
+ //#endregion
13
+ //#region src/allowances.ts
14
+ var HubAllowancesClient = class {
15
+ constructor(request) {
16
+ this.request = request;
17
+ }
18
+ async plan(meter) {
19
+ return (await this.request(this.path(meter), { method: "GET" })).plan;
20
+ }
21
+ async setPlan(meter, plan) {
22
+ return (await this.request(this.path(meter), this.body("PUT", plan))).plan;
23
+ }
24
+ /** Admit one turn or refuse it. Retrying the same `turnId` never counts twice. */
25
+ async admit(meter, input) {
26
+ return (await this.request(`${this.path(meter)}/turns`, this.body("POST", input))).allowance;
27
+ }
28
+ /** What the member's next turn would get, without counting anything. */
29
+ async status(meter, subject) {
30
+ const query = new URLSearchParams();
31
+ if (subject.role) query.set("role", subject.role);
32
+ if (subject.payer) query.set("payer", subject.payer);
33
+ if (subject.payerRole) query.set("payerRole", subject.payerRole);
34
+ const suffix = query.size ? `?${query}` : "";
35
+ return (await this.request(`${this.memberPath(meter, subject.member)}${suffix}`, { method: "GET" })).allowance;
36
+ }
37
+ /** Move a member to the paid allowance until `expiresAt` (the paid period's end). */
38
+ async grant(meter, member, input) {
39
+ return (await this.request(`${this.memberPath(meter, member)}/grant`, this.body("PUT", {
40
+ tier: "paid",
41
+ ...input
42
+ }))).grant;
43
+ }
44
+ /** Synchronize a paid grant by durable product revision. Null expiry writes
45
+ * a retained revocation. A delayed older update is refused, never reactivated.
46
+ * There is no fallback to the unversioned grant endpoint on older servers. */
47
+ async syncGrant(meter, member, input) {
48
+ const { grant } = await this.request(`${this.memberPath(meter, member)}/grant/sync`, this.body("PUT", input));
49
+ if (grant.member !== member || grant.source !== input.source || grant.revision !== input.revision || grant.reference !== input.reference || grant.expiresAt !== (input.expiresAt === null ? null : new Date(input.expiresAt).toISOString())) throw new Error("The Hub returned a mismatched grant synchronization receipt");
50
+ return grant;
51
+ }
52
+ async revoke(meter, member) {
53
+ await this.request(`${this.memberPath(meter, member)}/grant`, { method: "DELETE" });
54
+ }
55
+ /** Turns per member and per line on one UTC day (default today). */
56
+ async usage(meter, day) {
57
+ const suffix = day ? `?day=${encodeURIComponent(day)}` : "";
58
+ return (await this.request(`${this.path(meter)}/usage${suffix}`, { method: "GET" })).usage;
59
+ }
60
+ path(meter) {
61
+ return `/v1/hub/allowances/${encodeURIComponent(meter)}`;
62
+ }
63
+ memberPath(meter, member) {
64
+ return `${this.path(meter)}/members/${encodeURIComponent(member)}`;
65
+ }
66
+ body(method, body) {
67
+ return jsonInit(method, body);
68
+ }
69
+ };
70
+ //#endregion
71
+ //#region src/apps.ts
72
+ function encodedId(id) {
73
+ if (typeof id !== "string" || !id || id.length > 256 || id === "." || id === "..") throw new Error("A bounded app or grant id is required");
74
+ return encodeURIComponent(id);
75
+ }
76
+ var HubAppsClient = class {
77
+ grants;
78
+ constructor(request) {
79
+ this.request = request;
80
+ this.grants = {
81
+ list: () => this.request("/v1/me/app-grants", { method: "GET" }),
82
+ revoke: async (grantId) => this.request(`/v1/me/app-grants/${encodedId(grantId)}/revoke`, { method: "POST" })
83
+ };
84
+ }
85
+ list() {
86
+ return this.request("/v1/apps", { method: "GET" });
87
+ }
88
+ /** The secret is returned only by creation; keep it in your server vault. */
89
+ create(input) {
90
+ return this.request("/v1/apps", jsonInit("POST", input));
91
+ }
92
+ /** Immutable association of two existing records with the same owner. */
93
+ async linkOAuthClient(appId, clientId) {
94
+ return this.request(`/v1/apps/${encodedId(appId)}/oidc-client`, jsonInit("POST", { clientId }));
95
+ }
96
+ async revoke(appId) {
97
+ return this.request(`/v1/apps/${encodedId(appId)}/revoke`, { method: "POST" });
98
+ }
99
+ };
100
+ //#endregion
101
+ //#region src/inbound-webhooks.ts
102
+ var HubInboundWebhooksClient = class {
103
+ constructor(request) {
104
+ this.request = request;
105
+ }
106
+ async create(connectionId, options = {}) {
107
+ return this.request(this.path(connectionId), jsonInit("POST", options));
108
+ }
109
+ async get(connectionId) {
110
+ return this.request(this.path(connectionId), { method: "GET" });
111
+ }
112
+ /** Add one owned Linq WhatsApp number without rotating the webhook secret. */
113
+ async ensurePhoneNumber(connectionId, phoneNumberId) {
114
+ if (!phoneNumberId || phoneNumberId.length > 128 || !/^[\x21-\x7e]+$/.test(phoneNumberId)) throw new Error("A bounded phone-number id is required");
115
+ return this.request(`${this.path(connectionId)}/phone-numbers/ensure`, jsonInit("POST", { phoneNumberId }));
116
+ }
117
+ /** Remove event subscriptions first. This does not silently rotate a live URL. */
118
+ async delete(connectionId) {
119
+ return this.request(this.path(connectionId), { method: "DELETE" });
120
+ }
121
+ path(connectionId) {
122
+ if (!connectionId || connectionId.length > 256) throw new Error("A bounded connection id is required");
123
+ return `/v1/hub/connections/${encodeURIComponent(connectionId)}/inbound-webhook`;
124
+ }
125
+ };
126
+ //#endregion
127
+ //#region src/line-grants.ts
128
+ function path(binding, suffix = "") {
129
+ if (!binding.workspaceId || !binding.workspaceAgentId) throw new Error("A workspace and agent are required for a line grant");
130
+ return `/v1/hub/line-grants/current${suffix}?${new URLSearchParams({
131
+ workspaceId: binding.workspaceId,
132
+ workspaceAgentId: binding.workspaceAgentId
133
+ })}`;
134
+ }
135
+ /** Every call uses HubClient's authHeaders, so one-use app broker tokens can be minted per request. */
136
+ var HubLineGrantsClient = class {
137
+ constructor(request) {
138
+ this.request = request;
139
+ }
140
+ current(binding) {
141
+ return this.request(path(binding), { method: "GET" });
142
+ }
143
+ async line(binding) {
144
+ return (await this.request(path(binding, "/line"), { method: "GET" })).line;
145
+ }
146
+ async attach(binding, input) {
147
+ return (await this.request(path(binding, "/attachment"), jsonInit("PUT", input))).attachment;
148
+ }
149
+ detach(binding) {
150
+ return this.request(path(binding, "/attachment"), { method: "DELETE" });
151
+ }
152
+ async threads(binding) {
153
+ return (await this.request(path(binding, "/threads"), { method: "GET" })).threads;
154
+ }
155
+ async messages(binding, threadId) {
156
+ if (!threadId || threadId.length > 256) throw new Error("A bounded line thread id is required");
157
+ return (await this.request(path(binding, `/threads/${encodeURIComponent(threadId)}/messages`), { method: "GET" })).messages;
158
+ }
159
+ revoke(binding) {
160
+ return this.request(path(binding), { method: "DELETE" });
161
+ }
162
+ };
163
+ //#endregion
164
+ //#region src/lines.ts
165
+ /** Line calls share HubClient authentication and envelope handling. */
166
+ var HubLinesClient = class {
167
+ members;
168
+ checkins;
169
+ constructor(request, createWorkflow) {
170
+ this.request = request;
171
+ this.createWorkflow = createWorkflow;
172
+ this.members = { list: async (lineId) => (await this.request(`/v1/hub/lines/${encodeURIComponent(lineId)}/members`, { method: "GET" })).members };
173
+ this.checkins = { schedule: (cron, options) => {
174
+ const name = options.name ?? `line-checkin-${crypto.randomUUID().slice(0, 8)}`;
175
+ const yaml = [
176
+ `name: ${JSON.stringify(name)}`,
177
+ "on:",
178
+ ` schedule: { cron: ${JSON.stringify(cron)}, timezone: ${JSON.stringify(options.timezone)} }`,
179
+ "do:",
180
+ " - agent.run:",
181
+ " line:",
182
+ ` id: ${JSON.stringify(options.lineId)}`,
183
+ ` member: ${JSON.stringify(options.member)}`,
184
+ ` prompt: ${JSON.stringify(options.prompt)}`
185
+ ].join("\n");
186
+ return this.createWorkflow(yaml);
187
+ } };
188
+ }
189
+ async scheduleSend(cron, options) {
190
+ const name = options.name ?? `line-send-${crypto.randomUUID().slice(0, 8)}`;
191
+ const yaml = [
192
+ `name: ${JSON.stringify(name)}`,
193
+ "on:",
194
+ ` schedule: { cron: ${JSON.stringify(cron)}, timezone: ${JSON.stringify(options.timezone)} }`,
195
+ "do:",
196
+ " - line.send:",
197
+ ` lineId: ${JSON.stringify(options.lineId)}`,
198
+ ` memberId: ${JSON.stringify(options.memberId)}`,
199
+ ` text: ${JSON.stringify(options.text)}`,
200
+ ...options.notBefore ? [` notBefore: ${JSON.stringify(options.notBefore)}`] : []
201
+ ].join("\n");
202
+ return this.createWorkflow(yaml);
203
+ }
204
+ async context() {
205
+ return this.request("/v1/hub/lines/context", { method: "GET" });
206
+ }
207
+ async send(lineId, input) {
208
+ return this.request(`/v1/hub/lines/${encodeURIComponent(lineId)}/send`, jsonInit("POST", input));
209
+ }
210
+ async remind(lineId, input) {
211
+ return this.request(`/v1/hub/lines/${encodeURIComponent(lineId)}/remind`, jsonInit("POST", input));
212
+ }
213
+ };
214
+ //#endregion
215
+ //#region src/managed-numbers.ts
216
+ /** Administrative number operations through Hub's authenticated transport.
217
+ * A mutation is one attempt; an uncertain create reuses its quote and reference. */
218
+ var HubManagedNumbersClient = class {
219
+ constructor(request) {
220
+ this.request = request;
221
+ }
222
+ readiness() {
223
+ return this.request("/v1/hub/numbers/readiness", { method: "GET" });
224
+ }
225
+ /** One page of orders. Scope by `clientReference` to ask about one binding,
226
+ * and follow `nextCursor` for the rest; a page is never ownership evidence. */
227
+ list(query = {}) {
228
+ const params = new URLSearchParams();
229
+ if (query.clientReference !== void 0) params.set("clientReference", query.clientReference);
230
+ if (query.cursor !== void 0) params.set("cursor", query.cursor);
231
+ if (query.limit !== void 0) params.set("limit", String(query.limit));
232
+ const search = params.toString();
233
+ return this.request(`/v1/hub/numbers${search ? `?${search}` : ""}`, { method: "GET" });
234
+ }
235
+ get(id) {
236
+ return this.request(this.path(id), { method: "GET" });
237
+ }
238
+ quote(input) {
239
+ return this.request("/v1/hub/numbers/quote", this.post(input));
240
+ }
241
+ /** `clientReference` and `transport`, when given, must match the signed
242
+ * quote or Hub refuses the purchase with a conflict. */
243
+ create(input) {
244
+ return this.request("/v1/hub/numbers", this.post(input));
245
+ }
246
+ /** Fences references so no order can take them again. Call it as the last
247
+ * step before retiring the resource they name: a purchase that races the
248
+ * retirement is then refused (`409 number_reference_fenced`) instead of
249
+ * binding a line to a resource that is gone. Refused with
250
+ * `409 number_reference_held` while a live order holds one of them; cancel
251
+ * it first. A cancelled order no longer holds its reference, so the fence
252
+ * succeeds as soon as `cancel` returns, whether or not its release is still
253
+ * pending. Repeating a fence is harmless. */
254
+ fence(input) {
255
+ return this.request("/v1/hub/numbers/fences", this.post(input));
256
+ }
257
+ advance(id) {
258
+ return this.request(`${this.path(id)}/advance`, this.post({}));
259
+ }
260
+ cancel(id) {
261
+ return this.request(`${this.path(id)}/cancel`, this.post({}));
262
+ }
263
+ path(id) {
264
+ if (!/^num_[a-f0-9]{36}$/.test(id)) throw new Error("Invalid managed number order id");
265
+ return `/v1/hub/numbers/${encodeURIComponent(id)}`;
266
+ }
267
+ post(body) {
268
+ return jsonInit("POST", body);
269
+ }
270
+ };
271
+ //#endregion
2
272
  //#region src/redaction.ts
3
273
  const SECRET_KEY_PATTERN = /(api[_-]?key|authorization|capability[_-]?token|token|secret)/i;
4
- const SECRET_VALUE_PATTERN = /\b(?:sk-tan[-_]|hubcap_|hct_|gh[pousr]_)[A-Za-z0-9_=-]+\b/g;
274
+ const SECRET_VALUE_PATTERN = /\b(?:sk-tan[-_]|hubcap_|hct_|lrc_|gh[pousr]_)[A-Za-z0-9_.=-]+\b/g;
5
275
  function redactHubValue(value) {
6
276
  if (typeof value === "string") return value.replace(SECRET_VALUE_PATTERN, "[REDACTED]");
7
277
  if (Array.isArray(value)) return value.map((item) => redactHubValue(item));
@@ -52,8 +322,10 @@ function isHubSuccessEnvelope(value) {
52
322
  function isRecord$1(value) {
53
323
  return typeof value === "object" && value !== null;
54
324
  }
55
- function optString(value) {
56
- return typeof value === "string" ? value : "";
325
+ /** Read a wire field as a string, or "" when the server sent anything else.
326
+ * `raw` is that field straight off the parsed payload, before any check. */
327
+ function optString(raw) {
328
+ return typeof raw === "string" ? raw : "";
57
329
  }
58
330
  /** An agent iteration's terminal status (`iteration.ended`) — only ever
59
331
  * succeeded/failed; an iteration is never guard-skipped. */
@@ -81,63 +353,63 @@ function isRunDoneStatus(value) {
81
353
  * malformed `token` can never reach a consumer as `{ delta: undefined }`, and
82
354
  * new server event kinds don't break older clients.
83
355
  */
84
- function toRunStreamEvent(eventType, data) {
356
+ function toRunStreamEvent(eventType, raw) {
85
357
  if (eventType === "ping") return { type: "ping" };
86
- if (!isRecord$1(data)) return null;
358
+ if (!isRecord$1(raw)) return null;
87
359
  switch (eventType) {
88
- case "snapshot": return typeof data.id === "string" && typeof data.workflowId === "string" && typeof data.status === "string" && Array.isArray(data.actionResults) ? {
360
+ case "snapshot": return typeof raw.id === "string" && typeof raw.workflowId === "string" && typeof raw.status === "string" && Array.isArray(raw.actionResults) ? {
89
361
  type: "snapshot",
90
- run: data
362
+ run: raw
91
363
  } : null;
92
- case "token": return typeof data.delta === "string" && typeof data.actionIndex === "number" ? {
364
+ case "token": return typeof raw.delta === "string" && typeof raw.actionIndex === "number" ? {
93
365
  type: "token",
94
- actionIndex: data.actionIndex,
95
- delta: data.delta,
96
- at: optString(data.at)
366
+ actionIndex: raw.actionIndex,
367
+ delta: raw.delta,
368
+ at: optString(raw.at)
97
369
  } : null;
98
- case "run.done": return isRunDoneStatus(data.status) ? {
370
+ case "run.done": return isRunDoneStatus(raw.status) ? {
99
371
  type: "run.done",
100
- status: data.status,
101
- error: typeof data.error === "string" ? data.error : null,
102
- ...typeof data.at === "string" ? { at: data.at } : {}
372
+ status: raw.status,
373
+ error: typeof raw.error === "string" ? raw.error : null,
374
+ ...typeof raw.at === "string" ? { at: raw.at } : {}
103
375
  } : null;
104
- case "run.waiting": return typeof data.decisionId === "string" && data.decisionId.length > 0 ? {
376
+ case "run.waiting": return typeof raw.decisionId === "string" && raw.decisionId.length > 0 ? {
105
377
  type: "run.waiting",
106
- decisionId: data.decisionId,
107
- ...typeof data.at === "string" ? { at: data.at } : {}
378
+ decisionId: raw.decisionId,
379
+ ...typeof raw.at === "string" ? { at: raw.at } : {}
108
380
  } : null;
109
- case "action.started": return typeof data.index === "number" && typeof data.kind === "string" && typeof data.at === "string" ? {
381
+ case "action.started": return typeof raw.index === "number" && typeof raw.kind === "string" && typeof raw.at === "string" ? {
110
382
  type: "action.started",
111
- index: data.index,
112
- kind: data.kind,
113
- at: data.at
383
+ index: raw.index,
384
+ kind: raw.kind,
385
+ at: raw.at
114
386
  } : null;
115
- case "action.finished": return typeof data.index === "number" && typeof data.kind === "string" && isActionFinishedStatus(data.status) && typeof data.at === "string" ? {
387
+ case "action.finished": return typeof raw.index === "number" && typeof raw.kind === "string" && isActionFinishedStatus(raw.status) && typeof raw.at === "string" ? {
116
388
  type: "action.finished",
117
- index: data.index,
118
- kind: data.kind,
119
- status: data.status,
120
- at: data.at,
121
- ...typeof data.costUsd === "number" ? { costUsd: data.costUsd } : {},
122
- ...typeof data.error === "string" ? { error: data.error } : {}
389
+ index: raw.index,
390
+ kind: raw.kind,
391
+ status: raw.status,
392
+ at: raw.at,
393
+ ...typeof raw.costUsd === "number" ? { costUsd: raw.costUsd } : {},
394
+ ...typeof raw.error === "string" ? { error: raw.error } : {}
123
395
  } : null;
124
- case "iteration.started": return typeof data.actionIndex === "number" && typeof data.iterationIndex === "number" && typeof data.at === "string" ? {
396
+ case "iteration.started": return typeof raw.actionIndex === "number" && typeof raw.iterationIndex === "number" && typeof raw.at === "string" ? {
125
397
  type: "iteration.started",
126
- actionIndex: data.actionIndex,
127
- iterationIndex: data.iterationIndex,
128
- at: data.at,
129
- ...typeof data.model === "string" ? { model: data.model } : {}
398
+ actionIndex: raw.actionIndex,
399
+ iterationIndex: raw.iterationIndex,
400
+ at: raw.at,
401
+ ...typeof raw.model === "string" ? { model: raw.model } : {}
130
402
  } : null;
131
- case "iteration.ended": return typeof data.actionIndex === "number" && typeof data.iterationIndex === "number" && isIterationStatus(data.status) && typeof data.at === "string" ? {
403
+ case "iteration.ended": return typeof raw.actionIndex === "number" && typeof raw.iterationIndex === "number" && isIterationStatus(raw.status) && typeof raw.at === "string" ? {
132
404
  type: "iteration.ended",
133
- actionIndex: data.actionIndex,
134
- iterationIndex: data.iterationIndex,
135
- status: data.status,
136
- at: data.at,
137
- ...typeof data.outputPreview === "string" ? { outputPreview: data.outputPreview } : {},
138
- ...typeof data.inputTokens === "number" ? { inputTokens: data.inputTokens } : {},
139
- ...typeof data.outputTokens === "number" ? { outputTokens: data.outputTokens } : {},
140
- ...typeof data.costUsd === "number" ? { costUsd: data.costUsd } : {}
405
+ actionIndex: raw.actionIndex,
406
+ iterationIndex: raw.iterationIndex,
407
+ status: raw.status,
408
+ at: raw.at,
409
+ ...typeof raw.outputPreview === "string" ? { outputPreview: raw.outputPreview } : {},
410
+ ...typeof raw.inputTokens === "number" ? { inputTokens: raw.inputTokens } : {},
411
+ ...typeof raw.outputTokens === "number" ? { outputTokens: raw.outputTokens } : {},
412
+ ...typeof raw.costUsd === "number" ? { costUsd: raw.costUsd } : {}
141
413
  } : null;
142
414
  default: return null;
143
415
  }
@@ -145,8 +417,8 @@ function toRunStreamEvent(eventType, data) {
145
417
  /** True for an aborted/timed-out fetch (or any abort). fetch rejects with the
146
418
  * signal's reason — a DOMException named `AbortError` (caller) or `TimeoutError`
147
419
  * (AbortSignal.timeout). */
148
- function isAbortError(err) {
149
- return err instanceof Error && (err.name === "AbortError" || err.name === "TimeoutError");
420
+ function isAbortError(cause) {
421
+ return cause instanceof Error && (cause.name === "AbortError" || cause.name === "TimeoutError");
150
422
  }
151
423
  /** A signal that aborts when the caller's signal aborts OR `timeoutMs` elapses.
152
424
  * Returns undefined when neither bound applies (no per-request abort needed). */
@@ -225,8 +497,11 @@ var HubClient = class HubClient {
225
497
  fetch;
226
498
  apiKey;
227
499
  authHeaders;
500
+ allowances;
501
+ apps;
228
502
  connections;
229
503
  channels;
504
+ numbers;
230
505
  eventSubscriptions;
231
506
  permissions;
232
507
  tokens;
@@ -235,11 +510,17 @@ var HubClient = class HubClient {
235
510
  audit;
236
511
  githubApp;
237
512
  workflows;
513
+ lines;
514
+ lineGrants;
238
515
  constructor(options) {
239
516
  this.baseUrl = options.baseUrl.replace(/\/+$/, "");
240
517
  this.apiKey = options.apiKey;
241
518
  this.authHeaders = options.authHeaders;
242
519
  this.fetch = options.fetch ?? fetch.bind(globalThis);
520
+ this.allowances = new HubAllowancesClient((path, init) => this.request(path, init));
521
+ this.apps = new HubAppsClient((path, init) => this.request(path, init));
522
+ this.lineGrants = new HubLineGrantsClient((path, init) => this.request(path, init));
523
+ this.numbers = new HubManagedNumbersClient((path, init) => this.request(path, init));
243
524
  this.connections = new HubConnectionsClient((path, init) => this.request(path, init));
244
525
  this.channels = new HubChannelsClient((path, init) => this.request(path, init));
245
526
  this.eventSubscriptions = new HubEventSubscriptionsClient((path, init) => this.request(path, init));
@@ -250,6 +531,7 @@ var HubClient = class HubClient {
250
531
  this.audit = new HubAuditClient((path, init) => this.request(path, init));
251
532
  this.githubApp = new HubGithubAppClient((path, init) => this.request(path, init));
252
533
  this.workflows = new HubWorkflowsClient((path, init) => this.request(path, init), (path, init) => this.stream(path, init), (path, init) => this.requestBytes(path, init));
534
+ this.lines = new HubLinesClient((path, init) => this.request(path, init), (yaml) => this.workflows.create(yaml));
253
535
  }
254
536
  static fromEnv(options = {}) {
255
537
  const env = options.env ?? readProcessEnv();
@@ -362,11 +644,7 @@ var HubTokensClient = class {
362
644
  this.request = request;
363
645
  }
364
646
  async mint(options) {
365
- return this.request("/v1/hub/tokens", {
366
- method: "POST",
367
- body: JSON.stringify(options),
368
- headers: { "Content-Type": "application/json" }
369
- });
647
+ return this.request("/v1/hub/tokens", jsonInit("POST", options));
370
648
  }
371
649
  async list(options = {}) {
372
650
  const searchParams = new URLSearchParams();
@@ -400,38 +678,22 @@ var HubPermissionsClient = class {
400
678
  return this.request(`/v1/hub/policies?connectionId=${encodeURIComponent(connectionId)}`, { method: "GET" });
401
679
  }
402
680
  async set(input) {
403
- return this.request("/v1/hub/policies", {
404
- method: "PUT",
405
- body: JSON.stringify(input),
406
- headers: { "Content-Type": "application/json" }
407
- });
681
+ return this.request("/v1/hub/policies", jsonInit("PUT", input));
408
682
  }
409
683
  /** Reset an action to its default by deleting any stored override. */
410
684
  async delete(input) {
411
- return this.request("/v1/hub/policies", {
412
- method: "DELETE",
413
- body: JSON.stringify(input),
414
- headers: { "Content-Type": "application/json" }
415
- });
685
+ return this.request("/v1/hub/policies", jsonInit("DELETE", input));
416
686
  }
417
687
  /** Bulk-allow every write action of a connection's provider. Reads are
418
688
  * already allowed for sandbox agents; destructive actions stay `ask`.
419
689
  * Idempotent: actions with an existing policy are left untouched. */
420
690
  async allowWrites(connectionId) {
421
- return this.request("/v1/hub/policies/allow-writes", {
422
- method: "POST",
423
- body: JSON.stringify({ connectionId }),
424
- headers: { "Content-Type": "application/json" }
425
- });
691
+ return this.request("/v1/hub/policies/allow-writes", jsonInit("POST", { connectionId }));
426
692
  }
427
693
  /** Inverse of `allowWrites`: delete only the rows it created for this
428
694
  * connection. Manual per-action decisions are left intact. */
429
695
  async revertWrites(connectionId) {
430
- return this.request("/v1/hub/policies/revert-writes", {
431
- method: "POST",
432
- body: JSON.stringify({ connectionId }),
433
- headers: { "Content-Type": "application/json" }
434
- });
696
+ return this.request("/v1/hub/policies/revert-writes", jsonInit("POST", { connectionId }));
435
697
  }
436
698
  };
437
699
  var HubToolsClient = class {
@@ -439,34 +701,32 @@ var HubToolsClient = class {
439
701
  this.request = request;
440
702
  }
441
703
  async search(query, options = {}) {
442
- return this.request("/v1/hub/tools/search", {
443
- method: "POST",
444
- body: JSON.stringify({
445
- query,
446
- provider: options.provider,
447
- limit: options.limit
448
- }),
449
- headers: { "Content-Type": "application/json" }
450
- });
704
+ return this.request("/v1/hub/tools/search", jsonInit("POST", {
705
+ query,
706
+ provider: options.provider,
707
+ limit: options.limit
708
+ }));
451
709
  }
452
710
  async sources() {
453
711
  return this.request("/v1/hub/tools/sources", { method: "GET" });
454
712
  }
455
713
  async describe(path) {
456
- return this.request("/v1/hub/tools/describe", {
457
- method: "POST",
458
- body: JSON.stringify({ path }),
459
- headers: { "Content-Type": "application/json" }
460
- });
714
+ return this.request("/v1/hub/tools/describe", jsonInit("POST", { path }));
461
715
  }
462
- async invoke(path, input, options = {}) {
463
- const execInit = this.buildExecInit(path, input, options.connectionId);
716
+ /**
717
+ * Run one hub tool. `raw` is the tool input: the SDK forwards it verbatim as
718
+ * the request body's `input`, and the server validates it against the tool's
719
+ * own schema, so the client never gives it a shape.
720
+ */
721
+ async invoke(path, raw, options = {}) {
722
+ const execInit = this.buildExecInit(path, raw, options);
464
723
  try {
465
724
  return await this.request("/v1/hub/exec", execInit);
466
725
  } catch (error) {
467
726
  if (!(error instanceof HubSdkError) || !requiresCapabilityToken(error)) throw error;
727
+ const approvalId = getApprovalId(error);
728
+ if (approvalId && options.approve !== true) throw error;
468
729
  if (options.approve) {
469
- const approvalId = getApprovalId(error);
470
730
  if (!approvalId) throw error;
471
731
  const approved = await this.request(`/v1/hub/approvals/${encodeURIComponent(approvalId)}/approve`, { method: "POST" });
472
732
  validateApprovedExecution(approved, path, options.connectionId);
@@ -484,15 +744,11 @@ var HubToolsClient = class {
484
744
  });
485
745
  }
486
746
  }
487
- const minted = await this.request("/v1/hub/tokens", {
488
- method: "POST",
489
- body: JSON.stringify({
490
- actionPath: path,
491
- connectionId: options.connectionId,
492
- provider: options.connectionId ? void 0 : path.split(".")[0]
493
- }),
494
- headers: { "Content-Type": "application/json" }
495
- });
747
+ const minted = await this.request("/v1/hub/tokens", jsonInit("POST", {
748
+ actionPath: path,
749
+ connectionId: options.connectionId,
750
+ provider: options.connectionId ? void 0 : path.split(".")[0]
751
+ }));
496
752
  return this.request("/v1/hub/exec", {
497
753
  ...execInit,
498
754
  headers: {
@@ -501,16 +757,13 @@ var HubToolsClient = class {
501
757
  }
502
758
  });
503
759
  }
504
- buildExecInit(path, input, connectionId) {
505
- return {
506
- method: "POST",
507
- body: JSON.stringify({
508
- path,
509
- input,
510
- connectionId
511
- }),
512
- headers: { "Content-Type": "application/json" }
513
- };
760
+ buildExecInit(path, raw, options) {
761
+ return jsonInit("POST", {
762
+ path,
763
+ input: raw,
764
+ connectionId: options.connectionId,
765
+ idempotencyKey: options.idempotencyKey
766
+ });
514
767
  }
515
768
  };
516
769
  function requiresCapabilityToken(error) {
@@ -540,6 +793,17 @@ function validateApprovedExecution(approved, path, connectionId) {
540
793
  }
541
794
  });
542
795
  }
796
+ const GITHUB_EXACT_CONNECT_SCOPES = [
797
+ "read:user",
798
+ "repo",
799
+ "read:org"
800
+ ];
801
+ function sameOAuthScopeSet(left, right) {
802
+ if (!Array.isArray(left)) return false;
803
+ const leftSet = new Set(left);
804
+ const rightSet = new Set(right);
805
+ return leftSet.size === left.length && rightSet.size === right.length && leftSet.size === rightSet.size && [...leftSet].every((scope) => rightSet.has(scope));
806
+ }
543
807
  var HubChannelsClient = class {
544
808
  constructor(request) {
545
809
  this.request = request;
@@ -548,11 +812,7 @@ var HubChannelsClient = class {
548
812
  return this.request("/v1/hub/channels", { method: "GET" });
549
813
  }
550
814
  async createEmail(input = {}) {
551
- return this.request("/v1/hub/channels/email", {
552
- method: "POST",
553
- body: JSON.stringify(input),
554
- headers: { "Content-Type": "application/json" }
555
- });
815
+ return this.request("/v1/hub/channels/email", jsonInit("POST", input));
556
816
  }
557
817
  async delete(channelId) {
558
818
  return this.request(`/v1/hub/channels/${encodeURIComponent(channelId)}`, { method: "DELETE" });
@@ -566,19 +826,17 @@ var HubEventSubscriptionsClient = class {
566
826
  return this.request("/v1/hub/event-subscriptions", { method: "GET" });
567
827
  }
568
828
  async create(input) {
569
- return this.request("/v1/hub/event-subscriptions", {
570
- method: "POST",
571
- body: JSON.stringify(input),
572
- headers: { "Content-Type": "application/json" }
573
- });
829
+ return this.request("/v1/hub/event-subscriptions", jsonInit("POST", input));
574
830
  }
575
831
  async delete(subscriptionId) {
576
832
  return this.request(`/v1/hub/event-subscriptions/${encodeURIComponent(subscriptionId)}`, { method: "DELETE" });
577
833
  }
578
834
  };
579
835
  var HubConnectionsClient = class {
836
+ inboundWebhook;
580
837
  constructor(request) {
581
838
  this.request = request;
839
+ this.inboundWebhook = new HubInboundWebhooksClient(request);
582
840
  }
583
841
  async list() {
584
842
  return this.request("/v1/hub/connections", { method: "GET" });
@@ -590,40 +848,38 @@ var HubConnectionsClient = class {
590
848
  return this.request("/v1/hub/providers", { method: "GET" });
591
849
  }
592
850
  async start(provider, options = {}) {
593
- return this.request(`/v1/hub/connections/${encodeURIComponent(provider)}/start`, {
594
- method: "POST",
595
- body: JSON.stringify({
596
- returnUrl: options.returnUrl,
597
- cli: options.cli,
598
- connectionParameters: options.connectionParameters
599
- }),
600
- headers: { "Content-Type": "application/json" }
851
+ if (options.requestedScopes !== void 0 && (provider !== "github" || !sameOAuthScopeSet(options.requestedScopes, GITHUB_EXACT_CONNECT_SCOPES))) throw new HubSdkError({
852
+ code: "HUB_INVALID_INPUT",
853
+ message: "GitHub requestedScopes must be read:user, repo, and read:org"
854
+ });
855
+ const started = await this.request(`/v1/hub/connections/${encodeURIComponent(provider)}/start`, jsonInit("POST", {
856
+ returnUrl: options.returnUrl,
857
+ cli: options.cli,
858
+ connectionParameters: options.connectionParameters,
859
+ requestedScopes: options.requestedScopes
860
+ }));
861
+ if (options.requestedScopes !== void 0 && (started.provider !== provider || !sameOAuthScopeSet(started.scopes, options.requestedScopes))) throw new HubSdkError({
862
+ code: "HUB_CONFIG_MISSING",
863
+ message: "Hub did not preserve the requested OAuth scopes"
601
864
  });
865
+ return started;
602
866
  }
603
867
  async startWhatsappEmbeddedSignup(options = {}) {
604
- return this.request("/v1/hub/connections/whatsapp-business/embedded-signup/start", {
605
- method: "POST",
606
- body: JSON.stringify({ returnUrl: options.returnUrl }),
607
- headers: { "Content-Type": "application/json" }
608
- });
868
+ return this.request("/v1/hub/connections/whatsapp-business/embedded-signup/start", jsonInit("POST", { returnUrl: options.returnUrl }));
609
869
  }
610
870
  async completeWhatsappEmbeddedSignup(input) {
611
- return this.request("/v1/hub/connections/whatsapp-business/embedded-signup/complete", {
612
- method: "POST",
613
- body: JSON.stringify(input),
614
- headers: { "Content-Type": "application/json" }
615
- });
871
+ return this.request("/v1/hub/connections/whatsapp-business/embedded-signup/complete", jsonInit("POST", input));
616
872
  }
617
873
  /** Connect a non-OAuth (api-key) connector by submitting the user's key.
618
874
  * The server validates the key with a live probe before persisting and
619
875
  * returns the created (or reconnected) connection — there is no redirect,
620
- * unlike `start`. */
621
- async connectApiKey(provider, apiKey) {
622
- return this.request(`/v1/hub/connections/${encodeURIComponent(provider)}/connect-key`, {
623
- method: "POST",
624
- body: JSON.stringify({ apiKey }),
625
- headers: { "Content-Type": "application/json" }
626
- });
876
+ * unlike `start`. Cloudbeds requires propertyId metadata and PriceLabs
877
+ * requires listing ID/PMS pairs; other providers have no metadata. */
878
+ async connectApiKey(provider, apiKey, metadata) {
879
+ return this.request(`/v1/hub/connections/${encodeURIComponent(provider)}/connect-key`, jsonInit("POST", {
880
+ apiKey,
881
+ ...metadata === void 0 ? {} : { metadata }
882
+ }));
627
883
  }
628
884
  async revoke(connectionId) {
629
885
  return this.request(`/v1/hub/connections/${encodeURIComponent(connectionId)}`, { method: "DELETE" });
@@ -651,11 +907,7 @@ var HubGithubAppClient = class {
651
907
  this.request = request;
652
908
  }
653
909
  async mintInstallationToken(input) {
654
- return this.request("/v1/hub/github-app/mint-installation-token", {
655
- method: "POST",
656
- body: JSON.stringify(input),
657
- headers: { "Content-Type": "application/json" }
658
- });
910
+ return this.request("/v1/hub/github-app/mint-installation-token", jsonInit("POST", input));
659
911
  }
660
912
  /** Every installation the caller may act through — their own and any org's
661
913
  * they were verified against. The management surface's read. */
@@ -730,11 +982,7 @@ var HubWorkflowsClient = class {
730
982
  return this.request(`/v1/workflows/${encodeURIComponent(id)}`, { method: "GET" });
731
983
  }
732
984
  async create(yaml) {
733
- return this.request("/v1/workflows", {
734
- method: "POST",
735
- body: JSON.stringify({ yaml }),
736
- headers: { "Content-Type": "application/json" }
737
- });
985
+ return this.request("/v1/workflows", jsonInit("POST", { yaml }));
738
986
  }
739
987
  /**
740
988
  * Replace the workflow's definition from YAML (recompiled server-side,
@@ -745,14 +993,10 @@ var HubWorkflowsClient = class {
745
993
  * concurrent modification, `NOT_FOUND` for an unknown/foreign id.
746
994
  */
747
995
  async update(id, yaml, opts = {}) {
748
- return this.request(`/v1/workflows/${encodeURIComponent(id)}`, {
749
- method: "PUT",
750
- body: JSON.stringify({
751
- yaml,
752
- ...opts.note !== void 0 ? { note: opts.note } : {}
753
- }),
754
- headers: { "Content-Type": "application/json" }
755
- });
996
+ return this.request(`/v1/workflows/${encodeURIComponent(id)}`, jsonInit("PUT", {
997
+ yaml,
998
+ ...opts.note !== void 0 ? { note: opts.note } : {}
999
+ }));
756
1000
  }
757
1001
  async delete(id) {
758
1002
  await this.request(`/v1/workflows/${encodeURIComponent(id)}`, { method: "DELETE" });
@@ -763,11 +1007,7 @@ var HubWorkflowsClient = class {
763
1007
  * via `update`, but it can still be paused/resumed here).
764
1008
  */
765
1009
  async setEnabled(id, enabled) {
766
- return this.request(`/v1/workflows/${encodeURIComponent(id)}`, {
767
- method: "PATCH",
768
- body: JSON.stringify({ enabled }),
769
- headers: { "Content-Type": "application/json" }
770
- });
1010
+ return this.request(`/v1/workflows/${encodeURIComponent(id)}`, jsonInit("PATCH", { enabled }));
771
1011
  }
772
1012
  /**
773
1013
  * One page of run history, newest first. Pass the previous page's
@@ -795,9 +1035,7 @@ var HubWorkflowsClient = class {
795
1035
  async run(id, inputs, opts = {}) {
796
1036
  const hasInputs = inputs !== void 0 && Object.keys(inputs).length > 0;
797
1037
  return this.request(`/v1/workflows/${encodeURIComponent(id)}/run`, {
798
- method: "POST",
799
- body: JSON.stringify(hasInputs ? { inputs } : {}),
800
- headers: { "Content-Type": "application/json" },
1038
+ ...jsonInit("POST", hasInputs ? { inputs } : {}),
801
1039
  ...opts.signal ? { signal: opts.signal } : {}
802
1040
  });
803
1041
  }
@@ -976,11 +1214,7 @@ var HubWorkflowsClient = class {
976
1214
  * YAML no longer compiles, `CONFLICT` on a concurrent modification.
977
1215
  */
978
1216
  async rollback(id, rev) {
979
- return this.request(`/v1/workflows/${encodeURIComponent(id)}/rollback`, {
980
- method: "POST",
981
- body: JSON.stringify({ rev }),
982
- headers: { "Content-Type": "application/json" }
983
- });
1217
+ return this.request(`/v1/workflows/${encodeURIComponent(id)}/rollback`, jsonInit("POST", { rev }));
984
1218
  }
985
1219
  /**
986
1220
  * Deterministic health stats over the workflow's last N terminal runs
@@ -1001,11 +1235,7 @@ var HubWorkflowsClient = class {
1001
1235
  * until an owner approves.
1002
1236
  */
1003
1237
  async propose(id, input) {
1004
- return this.request(`/v1/workflows/${encodeURIComponent(id)}/proposals`, {
1005
- method: "POST",
1006
- body: JSON.stringify(input),
1007
- headers: { "Content-Type": "application/json" }
1008
- });
1238
+ return this.request(`/v1/workflows/${encodeURIComponent(id)}/proposals`, jsonInit("POST", input));
1009
1239
  }
1010
1240
  /**
1011
1241
  * Pending (proposed) and declined (rejected) revisions, newest first, with
@@ -1032,11 +1262,7 @@ var HubWorkflowsClient = class {
1032
1262
  * pending proposal.
1033
1263
  */
1034
1264
  async rejectProposal(id, rev, opts = {}) {
1035
- return this.request(`/v1/workflows/${encodeURIComponent(id)}/proposals/${encodeURIComponent(String(rev))}/reject`, {
1036
- method: "POST",
1037
- body: JSON.stringify(opts.reason !== void 0 ? { reason: opts.reason } : {}),
1038
- headers: { "Content-Type": "application/json" }
1039
- });
1265
+ return this.request(`/v1/workflows/${encodeURIComponent(id)}/proposals/${encodeURIComponent(String(rev))}/reject`, jsonInit("POST", opts.reason !== void 0 ? { reason: opts.reason } : {}));
1040
1266
  }
1041
1267
  /**
1042
1268
  * Mint a fresh webhook hook token, retiring the current one immediately.
@@ -1112,29 +1338,24 @@ var HubWorkflowsClient = class {
1112
1338
  /**
1113
1339
  * Upsert a key; returns the entry with its NEW version (increments on every
1114
1340
  * write). Throws `HubSdkError(KV_VALUE_TOO_LARGE)` past the 64KiB value cap
1115
- * or `KV_KEY_LIMIT` past the per-workflow key cap.
1341
+ * or `KV_KEY_LIMIT` past the per-workflow key cap. `raw` is the caller's
1342
+ * value, stored and read back verbatim, so the client never gives it a shape.
1116
1343
  */
1117
- async putKv(id, key, value) {
1118
- return this.request(`/v1/workflows/${encodeURIComponent(id)}/kv/${encodeURIComponent(key)}`, {
1119
- method: "PUT",
1120
- body: JSON.stringify({ value }),
1121
- headers: { "Content-Type": "application/json" }
1122
- });
1344
+ async putKv(id, key, raw) {
1345
+ return this.request(`/v1/workflows/${encodeURIComponent(id)}/kv/${encodeURIComponent(key)}`, jsonInit("PUT", { value: raw }));
1123
1346
  }
1124
1347
  /**
1125
1348
  * Compare-and-swap: the write lands only when the stored version still
1126
1349
  * equals `expectedVersion`; otherwise `HubSdkError(KV_VERSION_CONFLICT)`
1127
- * (409) — re-read and retry. Creation is {@link putKv}'s job.
1350
+ * (409) — re-read and retry. Creation is {@link putKv}'s job. `raw` is the
1351
+ * caller's value, stored and read back verbatim, so the client never gives it
1352
+ * a shape.
1128
1353
  */
1129
- async casKv(id, key, expectedVersion, value) {
1130
- return this.request(`/v1/workflows/${encodeURIComponent(id)}/kv/${encodeURIComponent(key)}/cas`, {
1131
- method: "POST",
1132
- body: JSON.stringify({
1133
- expectedVersion,
1134
- value
1135
- }),
1136
- headers: { "Content-Type": "application/json" }
1137
- });
1354
+ async casKv(id, key, expectedVersion, raw) {
1355
+ return this.request(`/v1/workflows/${encodeURIComponent(id)}/kv/${encodeURIComponent(key)}/cas`, jsonInit("POST", {
1356
+ expectedVersion,
1357
+ value: raw
1358
+ }));
1138
1359
  }
1139
1360
  /** Delete a key; idempotent — `deleted` reports whether a row was removed. */
1140
1361
  async deleteKv(id, key) {
@@ -1154,11 +1375,7 @@ var HubWorkflowsClient = class {
1154
1375
  * (400); an unknown template id throws `NOT_FOUND`.
1155
1376
  */
1156
1377
  async instantiateTemplate(templateId, parameters) {
1157
- return this.request(`/v1/workflows/templates/${encodeURIComponent(templateId)}/instantiate`, {
1158
- method: "POST",
1159
- body: JSON.stringify(parameters ? { parameters } : {}),
1160
- headers: { "Content-Type": "application/json" }
1161
- });
1378
+ return this.request(`/v1/workflows/templates/${encodeURIComponent(templateId)}/instantiate`, jsonInit("POST", parameters ? { parameters } : {}));
1162
1379
  }
1163
1380
  /**
1164
1381
  * The caller's open decisions across all workflows — the always-available
@@ -1185,11 +1402,7 @@ var HubWorkflowsClient = class {
1185
1402
  * (409 — answered, timed out, or cancelled first).
1186
1403
  */
1187
1404
  async resolveRunDecision(id, runId, input) {
1188
- return this.request(`/v1/workflows/${encodeURIComponent(id)}/runs/${encodeURIComponent(runId)}/decision/resolve`, {
1189
- method: "POST",
1190
- body: JSON.stringify(input),
1191
- headers: { "Content-Type": "application/json" }
1192
- });
1405
+ return this.request(`/v1/workflows/${encodeURIComponent(id)}/runs/${encodeURIComponent(runId)}/decision/resolve`, jsonInit("POST", input));
1193
1406
  }
1194
1407
  /**
1195
1408
  * Dry-run a YAML definition against the platform compiler without saving it.
@@ -1202,14 +1415,10 @@ var HubWorkflowsClient = class {
1202
1415
  * the unconnected providers is the point.
1203
1416
  */
1204
1417
  async validate(yaml, opts = {}) {
1205
- return this.request("/v1/workflows/validate", {
1206
- method: "POST",
1207
- body: JSON.stringify({
1208
- yaml,
1209
- ...opts.structural ? { structural: true } : {}
1210
- }),
1211
- headers: { "Content-Type": "application/json" }
1212
- });
1418
+ return this.request("/v1/workflows/validate", jsonInit("POST", {
1419
+ yaml,
1420
+ ...opts.structural ? { structural: true } : {}
1421
+ }));
1213
1422
  }
1214
1423
  async schema() {
1215
1424
  return this.request("/v1/workflows/schema", { method: "GET" });
@@ -1473,6 +1682,6 @@ function requestFailure(code, status, error, headers) {
1473
1682
  };
1474
1683
  }
1475
1684
  //#endregion
1476
- export { HUB_API_KEY_ENV_VAR, HUB_CAPABILITY_TOKEN_ENV_VAR, HUB_URL_ENV_VAR, HubApprovalsClient, HubAuditClient, HubChannelsClient, HubClient, HubConnectionsClient, HubEventDeliveryError, HubEventSubscriptionsClient, HubGithubAppClient, HubPermissionsClient, HubSdkError, HubTokensClient, HubToolsClient, HubWorkflowsClient, authenticateHubEventRequest, deriveHubEventCallbackSecret, parseHubEventDelivery, redactHubValue, resolveHubAuth, resolveHubBaseUrl, verifyHubEventSignature };
1685
+ export { HUB_API_KEY_ENV_VAR, HUB_CAPABILITY_TOKEN_ENV_VAR, HUB_URL_ENV_VAR, HubAllowancesClient, HubApprovalsClient, HubAppsClient, HubAuditClient, HubChannelsClient, HubClient, HubConnectionsClient, HubEventDeliveryError, HubEventSubscriptionsClient, HubGithubAppClient, HubInboundWebhooksClient, HubLineGrantsClient, HubLinesClient, HubManagedNumbersClient, HubPermissionsClient, HubSdkError, HubTokensClient, HubToolsClient, HubWorkflowsClient, authenticateHubEventRequest, deriveHubEventCallbackSecret, parseHubEventDelivery, redactHubValue, resolveHubAuth, resolveHubBaseUrl, verifyHubEventSignature };
1477
1686
 
1478
1687
  //# sourceMappingURL=index.js.map