@wiro-ai/wiro-agent-connectors 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (67) hide show
  1. package/CHANGELOG.md +29 -0
  2. package/README.md +1131 -34
  3. package/dist/cli.js +15 -12
  4. package/dist/core/credentials.d.ts +21 -0
  5. package/dist/core/credentials.js +45 -0
  6. package/dist/core/origins.d.ts +18 -0
  7. package/dist/core/origins.js +40 -0
  8. package/dist/core/upload-hosts.d.ts +15 -0
  9. package/dist/core/upload-hosts.js +43 -0
  10. package/dist/host/describe.d.ts +10 -0
  11. package/dist/host/describe.js +38 -0
  12. package/dist/host/env.d.ts +25 -2
  13. package/dist/host/env.js +24 -7
  14. package/dist/host/guarded-fetch.d.ts +36 -9
  15. package/dist/host/guarded-fetch.js +175 -52
  16. package/dist/host/index.d.ts +8 -5
  17. package/dist/host/index.js +12 -1
  18. package/dist/host/load.js +31 -1
  19. package/dist/host/server.d.ts +13 -2
  20. package/dist/host/server.js +15 -2
  21. package/dist/types.d.ts +96 -5
  22. package/dist/vendors/adapty.js +1303 -0
  23. package/dist/vendors/adjust.js +1372 -0
  24. package/dist/vendors/apollo.js +2499 -0
  25. package/dist/vendors/apple-appstore.js +2798 -0
  26. package/dist/vendors/beehiiv.js +1965 -0
  27. package/dist/vendors/blogger.js +1687 -0
  28. package/dist/vendors/bluesky.js +850 -127
  29. package/dist/vendors/brevo.js +2195 -0
  30. package/dist/vendors/calendarific.js +1116 -0
  31. package/dist/vendors/devto.js +685 -92
  32. package/dist/vendors/facebook-pages.js +2185 -0
  33. package/dist/vendors/firebase.js +1333 -0
  34. package/dist/vendors/ga4.js +1585 -0
  35. package/dist/vendors/gmail.js +1962 -0
  36. package/dist/vendors/google-ads.js +2201 -0
  37. package/dist/vendors/google-business.js +1621 -0
  38. package/dist/vendors/google-calendar.js +1936 -0
  39. package/dist/vendors/google-drive.js +2654 -0
  40. package/dist/vendors/google-merchant-center.js +1742 -0
  41. package/dist/vendors/google-play.js +1856 -0
  42. package/dist/vendors/google-search-console.js +1572 -0
  43. package/dist/vendors/hashnode.js +1722 -0
  44. package/dist/vendors/instagram.js +2249 -0
  45. package/dist/vendors/kaggle.js +2043 -0
  46. package/dist/vendors/keepa.js +2087 -0
  47. package/dist/vendors/linkedin.js +1588 -0
  48. package/dist/vendors/mailchimp.js +2402 -0
  49. package/dist/vendors/mastodon.js +1836 -0
  50. package/dist/vendors/meta-ads.js +2375 -0
  51. package/dist/vendors/notion.js +1950 -0
  52. package/dist/vendors/pinterest.js +1744 -0
  53. package/dist/vendors/qiita.js +1552 -0
  54. package/dist/vendors/reddit.js +1791 -0
  55. package/dist/vendors/revenuecat.js +1593 -0
  56. package/dist/vendors/roasit.js +1460 -0
  57. package/dist/vendors/sendgrid.js +2188 -0
  58. package/dist/vendors/serper.js +901 -179
  59. package/dist/vendors/shopify.js +2511 -0
  60. package/dist/vendors/threads.js +1869 -0
  61. package/dist/vendors/tiktok.js +2199 -0
  62. package/dist/vendors/tumblr.js +1793 -0
  63. package/dist/vendors/twitter.js +1650 -0
  64. package/dist/vendors/woocommerce.js +2258 -0
  65. package/dist/vendors/wordpress.js +1904 -0
  66. package/dist/vendors/youtube.js +2542 -0
  67. package/package.json +1 -1
@@ -0,0 +1,2199 @@
1
+ /* tiktok connector module (MIT License). Built from src/vendors/tiktok; do not edit. */
2
+ "use strict";
3
+
4
+ // src/core/errors.ts
5
+ var ToolFailure = class extends Error {
6
+ details;
7
+ constructor(message, details = {}) {
8
+ super(message);
9
+ this.name = "ToolFailure";
10
+ this.details = details;
11
+ }
12
+ };
13
+ var OutcomeUnknown = class extends Error {
14
+ constructor(message) {
15
+ super(message);
16
+ this.name = "OutcomeUnknown";
17
+ }
18
+ };
19
+
20
+ // src/core/accounts.ts
21
+ function allowedAccounts(accounts, key) {
22
+ if (accounts === null) return null;
23
+ const list = accounts?.[key];
24
+ return Array.isArray(list) ? list.map(String) : [];
25
+ }
26
+ function requireAccounts(accounts, key, ids, label = "account") {
27
+ const allowed = allowedAccounts(accounts, key);
28
+ if (allowed === null) return;
29
+ const requested = (Array.isArray(ids) ? ids : [ids]).map(String);
30
+ const refused = requested.filter((id) => !allowed.includes(id));
31
+ if (!refused.length) return;
32
+ throw new ToolFailure(
33
+ `The ${label} ${refused.join(", ")} ${refused.length > 1 ? "are" : "is"} not among the ${label}s chosen for this connection. ` + (allowed.length ? `Use one of: ${allowed.join(", ")}.` : `No ${label} is chosen for it yet.`) + " Nothing was sent."
34
+ );
35
+ }
36
+
37
+ // src/core/text.ts
38
+ var encoder = new TextEncoder();
39
+ var decoder = new TextDecoder();
40
+ function utf8Bytes(text) {
41
+ return encoder.encode(text);
42
+ }
43
+ function utf8Length(text) {
44
+ return encoder.encode(text).length;
45
+ }
46
+ function utf8Decode(bytes) {
47
+ return decoder.decode(bytes);
48
+ }
49
+ function base64Encode(bytes) {
50
+ let binary = "";
51
+ for (let i = 0; i < bytes.length; i += 32768) {
52
+ binary += String.fromCharCode(...bytes.subarray(i, i + 32768));
53
+ }
54
+ return btoa(binary);
55
+ }
56
+ function base64UrlEncode(bytes) {
57
+ return base64Encode(bytes).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
58
+ }
59
+ function base64UrlDecode(text) {
60
+ if (!/^[A-Za-z0-9_-]*$/.test(text)) throw new Error("not base64url");
61
+ const padded = text.replace(/-/g, "+").replace(/_/g, "/") + "===".slice((text.length + 3) % 4);
62
+ const binary = atob(padded);
63
+ const bytes = new Uint8Array(binary.length);
64
+ for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);
65
+ return bytes;
66
+ }
67
+ async function sha256Hex(text) {
68
+ const digest = new Uint8Array(await crypto.subtle.digest("SHA-256", utf8Bytes(text)));
69
+ return Array.from(digest, (byte) => byte.toString(16).padStart(2, "0")).join("");
70
+ }
71
+ function truncate(text, max) {
72
+ if (text.length <= max) return text;
73
+ const points = Array.from(text);
74
+ if (points.length <= max) return text;
75
+ return `${points.slice(0, Math.max(0, max - 1)).join("")}\u2026`;
76
+ }
77
+ function cleanVendorText(text, max = 300) {
78
+ if (typeof text !== "string") return void 0;
79
+ if (/^\s*</.test(text)) return void 0;
80
+ const line = text.replace(/[\u0000-\u001f\u007f]+/g, " ").replace(/\s+/g, " ").trim();
81
+ return line ? truncate(line, max) : void 0;
82
+ }
83
+ function formatNumber(value) {
84
+ return value.toLocaleString("en-US");
85
+ }
86
+
87
+ // src/core/output.ts
88
+ var OUTPUT_LIMIT_BYTES = 32 * 1024;
89
+ function jsonSize(value) {
90
+ return utf8Length(JSON.stringify(value) ?? "");
91
+ }
92
+ function cutStrings(value, max) {
93
+ if (typeof value === "string") return truncate(value, max);
94
+ if (Array.isArray(value)) return value.map((item) => cutStrings(item, max));
95
+ if (typeof value === "object" && value !== null) {
96
+ const out = {};
97
+ for (const [key, item] of Object.entries(value)) out[key] = cutStrings(item, max);
98
+ return out;
99
+ }
100
+ return value;
101
+ }
102
+ function shrinkToFit(value, limit = OUTPUT_LIMIT_BYTES) {
103
+ if (jsonSize(value) <= limit) return { value, truncated: false };
104
+ for (const max of [4e3, 2e3, 1e3, 500, 200, 80]) {
105
+ const cut = cutStrings(value, max);
106
+ if (jsonSize(cut) <= limit) return { value: cut, truncated: true };
107
+ }
108
+ return void 0;
109
+ }
110
+ function fitPage(input, limit = OUTPUT_LIMIT_BYTES) {
111
+ const build = (count) => {
112
+ const cut = count < input.items.length;
113
+ const result2 = { ...input.extra, [input.key]: input.items.slice(0, count) };
114
+ const next = cut ? input.resumeAt(count) : input.nextPage;
115
+ if (next) result2["nextCursor"] = next;
116
+ if (cut) result2["truncated"] = true;
117
+ return result2;
118
+ };
119
+ const all = build(input.items.length);
120
+ if (jsonSize(all) <= limit) return all;
121
+ let low = 1;
122
+ let high = input.items.length - 1;
123
+ while (low < high) {
124
+ const middle = Math.ceil((low + high) / 2);
125
+ if (jsonSize(build(middle)) <= limit) low = middle;
126
+ else high = middle - 1;
127
+ }
128
+ const best = build(low);
129
+ if (jsonSize(best) <= limit) return best;
130
+ const shrunk = shrinkToFit(best, limit);
131
+ if (shrunk) return { ...shrunk.value, truncated: true };
132
+ throw new ToolFailure("The result is too large to return, even one item at a time.");
133
+ }
134
+ function encodeCursor(tool, state) {
135
+ return base64UrlEncode(utf8Bytes(JSON.stringify({ t: tool, ...state })));
136
+ }
137
+ function decodeCursor(tool, cursor) {
138
+ if (cursor === void 0 || cursor === "") return null;
139
+ try {
140
+ const state = JSON.parse(utf8Decode(base64UrlDecode(cursor)));
141
+ if (typeof state === "object" && state !== null && state.t === tool) {
142
+ return state;
143
+ }
144
+ } catch {
145
+ }
146
+ throw new ToolFailure(
147
+ "The cursor is not valid for this tool. Pass the nextCursor value of the previous result unchanged, or leave cursor out to start from the beginning."
148
+ );
149
+ }
150
+
151
+ // src/core/api-tools.ts
152
+ var ALL_METHODS = ["POST", "PUT", "PATCH", "DELETE"];
153
+ var TEXT_TYPES = /json|^text\/|xml|javascript|x-www-form-urlencoded|csv|yaml|graphql/i;
154
+ var NOTE_ROOM = 400;
155
+ var MAX_CUT_POINTS = 4e4;
156
+ function isQueryValue(value) {
157
+ return typeof value === "string" || typeof value === "boolean" || typeof value === "number" && Number.isFinite(value);
158
+ }
159
+ function nothingSent(sentence) {
160
+ return new ToolFailure(`${sentence} Nothing was sent.`);
161
+ }
162
+ function fitReply(reply) {
163
+ if (jsonSize(reply) <= OUTPUT_LIMIT_BYTES) return reply;
164
+ const shrunk = shrinkToFit(reply, OUTPUT_LIMIT_BYTES - NOTE_ROOM);
165
+ if (shrunk) {
166
+ return {
167
+ ...shrunk.value,
168
+ truncated: true,
169
+ note: "Long text values were cut to fit 32 KB: ask for fewer items or fields to see them whole."
170
+ };
171
+ }
172
+ const text = typeof reply["data"] === "string" ? reply["data"] : JSON.stringify(reply["data"]) ?? "";
173
+ const points = Array.from(text.length > MAX_CUT_POINTS ? text.slice(0, MAX_CUT_POINTS) : text);
174
+ if (/^[\ud800-\udbff]$/.test(points[points.length - 1] ?? "")) points.pop();
175
+ const cut = (count) => ({
176
+ status: reply["status"],
177
+ ...reply["headers"] ? { headers: reply["headers"] } : {},
178
+ truncated: true,
179
+ note: `The reply has ${formatNumber(utf8Length(text))} bytes and was cut to fit 32 KB: ask for fewer items (the API's paging or field parameters) to see it whole.`,
180
+ text: points.slice(0, count).join("")
181
+ });
182
+ let low = 0;
183
+ let high = points.length;
184
+ while (low < high) {
185
+ const middle = Math.ceil((low + high) / 2);
186
+ if (jsonSize(cut(middle)) <= OUTPUT_LIMIT_BYTES) low = middle;
187
+ else high = middle - 1;
188
+ }
189
+ return cut(low);
190
+ }
191
+ function shapeReply(response, headerNames) {
192
+ const reply = { status: response.status };
193
+ const headers = {};
194
+ for (const name2 of headerNames) {
195
+ const value = response.headers.get(name2);
196
+ if (value) headers[name2] = truncate(value, 2e3);
197
+ }
198
+ if (Object.keys(headers).length) reply["headers"] = headers;
199
+ const type = response.headers.get("content-type") ?? "";
200
+ if (type && !TEXT_TYPES.test(type)) {
201
+ reply["contentType"] = truncate(type, 200);
202
+ reply["note"] = "The reply is a binary file and is not shown.";
203
+ return reply;
204
+ }
205
+ if (response.data !== null && response.data !== void 0 && response.data !== "") reply["data"] = response.data;
206
+ return fitReply(reply);
207
+ }
208
+ function checkAccounts(rule, request, h) {
209
+ const label = rule.label ?? "account";
210
+ const allowed = allowedAccounts(h.ctx.accounts, rule.key);
211
+ if (allowed === null) return;
212
+ const namesNone = nothingSent(
213
+ `This request names none of the ${label}s chosen for this connection. ` + (allowed.length ? `It must name one of: ${allowed.join(", ")}.` : `No ${label} is chosen for it yet.`)
214
+ );
215
+ if (rule.ids) {
216
+ const ids = rule.ids(request).map(String);
217
+ if (!ids.length) throw namesNone;
218
+ requireAccounts(h.ctx.accounts, rule.key, ids, label);
219
+ return;
220
+ }
221
+ if (!request.segments.some((segment) => allowed.includes(segment))) throw namesNone;
222
+ }
223
+ function apiTools(options) {
224
+ const { label, basePath } = options;
225
+ const methods = options.methods?.length ? [...new Set(options.methods)] : ALL_METHODS;
226
+ const headerNames = ["link", "location", ...(options.responseHeaders ?? []).map((name2) => name2.toLowerCase())];
227
+ const base = basePath?.replace(/\/+$/, "");
228
+ const pathSchema = {
229
+ type: "string",
230
+ minLength: 1,
231
+ maxLength: 2e3,
232
+ pattern: "^(?!.*//)/[^?#]*$",
233
+ description: `The path${basePath ? `, starting with ${basePath}` : ""}. Query parameters go in query, not in the path.`
234
+ };
235
+ const querySchema = {
236
+ type: "object",
237
+ description: 'Query parameters, e.g. {"page": 2, "fields": "id,name"}. A list repeats the parameter: {"id": [1, 2]} sends id=1&id=2.'
238
+ };
239
+ const originSchema = options.originArgument ? { origin: { type: "string", pattern: "^https://", maxLength: 300, description: options.originArgument } } : {};
240
+ async function run(method, args, h) {
241
+ let origin = h.origins[0];
242
+ if (args.origin !== void 0) {
243
+ let wanted;
244
+ try {
245
+ wanted = new URL(args.origin).origin;
246
+ } catch {
247
+ }
248
+ if (!wanted || !h.origins.includes(wanted)) throw nothingSent(`origin must be one of: ${h.origins.join(", ")}.`);
249
+ origin = wanted;
250
+ }
251
+ const url = new URL(args.path, origin);
252
+ if (url.origin !== origin) throw nothingSent(`The path must stay on ${origin}.`);
253
+ const path = url.pathname;
254
+ if (base !== void 0 && path !== base && !path.startsWith(`${base}/`)) throw nothingSent(`The path must start with ${basePath}.`);
255
+ let segments;
256
+ try {
257
+ segments = path.split("/").slice(1).map((segment) => decodeURIComponent(segment));
258
+ } catch {
259
+ throw nothingSent("The path has a broken percent-escape (a % not followed by two hex digits).");
260
+ }
261
+ if (segments[segments.length - 1] === "") segments.pop();
262
+ const query = {};
263
+ const queryLists = {};
264
+ for (const [key, value] of Object.entries(args.query ?? {})) {
265
+ if (value === void 0 || value === null) continue;
266
+ const list = Array.isArray(value) ? value : [value];
267
+ if (!key || !list.every(isQueryValue)) throw nothingSent(`query.${key} must be text, a number, true or false, or a list of them.`);
268
+ query[key] = Array.isArray(value) ? list : value;
269
+ queryLists[key] = list.map(String);
270
+ }
271
+ const request = { method, origin, path, query };
272
+ if (method !== "GET") {
273
+ if (args.json !== void 0 && args.body !== void 0) throw nothingSent("Give json or body, not both.");
274
+ if (args.body !== void 0 && !args.content_type) throw nothingSent('content_type is required with body, e.g. "application/x-www-form-urlencoded".');
275
+ if (args.json !== void 0 && !args.content_type) {
276
+ request.json = args.json;
277
+ } else if (args.json !== void 0 || args.body !== void 0) {
278
+ request.body = utf8Bytes(args.body ?? JSON.stringify(args.json));
279
+ request.contentType = args.content_type;
280
+ }
281
+ request.write = true;
282
+ }
283
+ const info = { method, origin, path, segments, query: queryLists, ...args.json !== void 0 ? { json: args.json } : {} };
284
+ if (options.accounts) checkAccounts(options.accounts, info, h);
285
+ await options.guard?.(info, h);
286
+ const response = options.send ? await options.send(request, h) : await h.api(request);
287
+ return shapeReply(response, headerNames);
288
+ }
289
+ return [
290
+ {
291
+ name: "api_get",
292
+ kind: "read",
293
+ title: `Call the ${label} API (GET)`,
294
+ description: `${options.description} Sends one GET request with the connection's credentials and returns the HTTP status and the reply, JSON or text, cut to fit 32 KB (use the API's own paging and field parameters for long lists). It changes nothing.`,
295
+ inputSchema: {
296
+ type: "object",
297
+ properties: { path: pathSchema, query: querySchema, ...originSchema },
298
+ required: ["path"],
299
+ additionalProperties: false
300
+ },
301
+ run: (args, h) => run("GET", args, h)
302
+ },
303
+ {
304
+ name: "api_request",
305
+ kind: "write",
306
+ check: "api_get",
307
+ title: `Send a request to the ${label} API`,
308
+ description: `${options.description} Sends one ${methods.join(", ")} request with the connection's credentials, with a JSON body (json) or another body (body and content_type), and returns the HTTP status and the reply. It can create, change or delete data. It is never retried: when the outcome is unclear, check with api_get before sending it again.`,
309
+ inputSchema: {
310
+ type: "object",
311
+ properties: {
312
+ method: { type: "string", enum: methods, description: `The HTTP method: ${methods.join(", ")}.` },
313
+ path: pathSchema,
314
+ query: querySchema,
315
+ json: { type: "object", description: "A JSON object to send as the body (application/json unless content_type says otherwise)." },
316
+ body: { type: "string", maxLength: 1e6, description: 'Any other body, as text, with its content_type, e.g. a form: "name=a&tags=b".' },
317
+ content_type: {
318
+ type: "string",
319
+ pattern: "^[A-Za-z0-9!#$&^_.+-]+/[A-Za-z0-9!#$&^_.+-]+(\\s*;.*)?$",
320
+ maxLength: 200,
321
+ description: `The body's media type, e.g. "application/x-www-form-urlencoded"; required with body.`
322
+ },
323
+ ...originSchema
324
+ },
325
+ required: ["method", "path"],
326
+ additionalProperties: false
327
+ },
328
+ run: (args, h) => run(args.method, args, h)
329
+ }
330
+ ];
331
+ }
332
+
333
+ // src/core/credentials.ts
334
+ function requiredAlternatives(module2) {
335
+ return (module2.requiredCredentials ?? [module2.credentials]).map((list) => [...list]);
336
+ }
337
+ function unmetAlternatives(alternatives, has) {
338
+ const lacking = alternatives.map((list) => list.filter((name2) => !has(name2)));
339
+ if (lacking.some((list) => list.length === 0)) return [];
340
+ return lacking.filter((list, index) => !lacking.some((other, otherIndex) => otherIndex !== index && other.every((name2) => list.includes(name2)) && (other.length < list.length || otherIndex < index)));
341
+ }
342
+ function andList(items) {
343
+ if (items.length <= 2) return items.join(" and ");
344
+ return `${items.slice(0, -1).join(", ")} and ${items[items.length - 1]}`;
345
+ }
346
+ function orList(items) {
347
+ if (items.length <= 1) return items.join("");
348
+ return `${items.slice(0, -1).join(", ")}, or ${items[items.length - 1]}`;
349
+ }
350
+
351
+ // src/core/files.ts
352
+ var ATTACHMENT_URI = "attachment:///";
353
+ var MAX_NAME = 200;
354
+ function fileLimitOf(ctx) {
355
+ const maxBytes = ctx.files?.maxBytes;
356
+ return typeof maxBytes === "number" && Number.isSafeInteger(maxBytes) && maxBytes > 0 ? maxBytes : null;
357
+ }
358
+ function fileName(name2) {
359
+ const clean = String(name2).replace(/[\u0000-\u001f\u007f]/g, "").replace(/[\\/]/g, "_").trim();
360
+ const points = Array.from(clean);
361
+ if (points.length <= MAX_NAME) return clean || "file";
362
+ const extension = /\.[A-Za-z0-9]{1,10}$/.exec(clean)?.[0] ?? "";
363
+ return points.slice(0, MAX_NAME - extension.length).join("") + extension;
364
+ }
365
+ function fileType(mimeType) {
366
+ const type = String(mimeType).split(";")[0]?.trim().toLowerCase() ?? "";
367
+ return /^[a-z0-9][a-z0-9!#$&^_.+-]*\/[a-z0-9][a-z0-9!#$&^_.+-]*$/.test(type) ? type : "application/octet-stream";
368
+ }
369
+ function resourceBlock(file) {
370
+ return {
371
+ type: "resource",
372
+ resource: { uri: `${ATTACHMENT_URI}${encodeURIComponent(file.name)}`, mimeType: file.mimeType, blob: base64Encode(file.bytes) }
373
+ };
374
+ }
375
+
376
+ // src/core/http.ts
377
+ var MAX_API_RESPONSE_BYTES = 4 * 1024 * 1024;
378
+ var USER_AGENT = "agent-connectors";
379
+ var SAFE_METHODS = /* @__PURE__ */ new Set(["GET", "HEAD"]);
380
+ function errorCode(error) {
381
+ const code = error?.code;
382
+ return typeof code === "string" ? code : void 0;
383
+ }
384
+ function describe(error) {
385
+ const name2 = error?.name;
386
+ const code = errorCode(error);
387
+ if (code === "TIMEOUT" || name2 === "TimeoutError") return "the request timed out";
388
+ if (code === "ABORTED" || name2 === "AbortError") return "the request was cancelled";
389
+ if (code === "TOO_LARGE") return "the reply was too large";
390
+ return cleanVendorText(error?.message, 200) ?? "a network error";
391
+ }
392
+ function retryAfterSeconds(headers, now = Date.now()) {
393
+ const retryAfter = headers.get("retry-after");
394
+ if (retryAfter) {
395
+ const seconds = Number(retryAfter);
396
+ if (Number.isFinite(seconds) && seconds >= 0) return Math.ceil(seconds);
397
+ const date = Date.parse(retryAfter);
398
+ if (!Number.isNaN(date)) return Math.max(0, Math.ceil((date - now) / 1e3));
399
+ }
400
+ const reset = headers.get("ratelimit-reset") ?? headers.get("x-ratelimit-reset");
401
+ if (reset) {
402
+ const value = Number(reset);
403
+ if (Number.isFinite(value) && value >= 0) {
404
+ return value > 1e9 ? Math.max(0, Math.ceil(value - now / 1e3)) : Math.ceil(value);
405
+ }
406
+ }
407
+ return void 0;
408
+ }
409
+ function vendorCode(data) {
410
+ if (typeof data !== "object" || data === null) return void 0;
411
+ for (const key of ["error", "code"]) {
412
+ const value = data[key];
413
+ if (typeof value === "string" && /^[A-Za-z][A-Za-z0-9_.-]{1,63}$/.test(value)) return value;
414
+ }
415
+ return void 0;
416
+ }
417
+ function vendorMessage(data) {
418
+ if (typeof data === "string") return cleanVendorText(data);
419
+ if (typeof data !== "object" || data === null) return void 0;
420
+ const record = data;
421
+ for (const key of ["message", "error_description", "error", "detail", "title"]) {
422
+ const value = record[key];
423
+ if (typeof value === "string" && value.trim()) return cleanVendorText(value);
424
+ const nested = value?.message;
425
+ if (typeof nested === "string" && nested.trim()) return cleanVendorText(nested);
426
+ }
427
+ if (Array.isArray(record["errors"])) {
428
+ const messages = record["errors"].map((item) => typeof item === "string" ? item : item?.message).filter((item) => typeof item === "string" && item.trim() !== "");
429
+ if (messages.length) return cleanVendorText(messages.join("; "));
430
+ }
431
+ return void 0;
432
+ }
433
+ var TooLarge = class extends Error {
434
+ constructor(limit) {
435
+ super(`the reply is larger than ${formatNumber(limit)} bytes`);
436
+ this.limit = limit;
437
+ }
438
+ limit;
439
+ };
440
+ async function readCapped(response, maxBytes) {
441
+ const declared = Number(response.headers.get("content-length"));
442
+ if (Number.isFinite(declared) && declared > maxBytes) {
443
+ await response.body?.cancel().catch(() => {
444
+ });
445
+ throw new TooLarge(maxBytes);
446
+ }
447
+ if (!response.body) return new Uint8Array(0);
448
+ const reader = response.body.getReader();
449
+ const chunks = [];
450
+ let total = 0;
451
+ for (; ; ) {
452
+ const { done, value } = await reader.read();
453
+ if (done) break;
454
+ total += value.byteLength;
455
+ if (total > maxBytes) {
456
+ await reader.cancel().catch(() => {
457
+ });
458
+ throw new TooLarge(maxBytes);
459
+ }
460
+ chunks.push(value);
461
+ }
462
+ const bytes = new Uint8Array(total);
463
+ let offset = 0;
464
+ for (const chunk of chunks) {
465
+ bytes.set(chunk, offset);
466
+ offset += chunk.byteLength;
467
+ }
468
+ return bytes;
469
+ }
470
+ function parseBody(bytes, contentType) {
471
+ if (bytes.length === 0) return null;
472
+ const text = utf8Decode(bytes);
473
+ if (/json/i.test(contentType ?? "") || /^\s*[[{]/.test(text)) {
474
+ try {
475
+ return JSON.parse(text);
476
+ } catch {
477
+ }
478
+ }
479
+ return text;
480
+ }
481
+ function createHttp(env) {
482
+ const { label, ctx } = env;
483
+ const nothingChanged = env.readOnly ? "" : " Nothing was changed.";
484
+ const checkCredentials = env.credentialLabels.length ? `Check that the ${andList(env.credentialLabels)} ${env.credentialLabels.length > 1 ? "are" : "is"} correct and still active.` : `Check that the ${label} credentials are correct and still active.`;
485
+ function failureFor(status, headers, data, request) {
486
+ const message = vendorMessage(data);
487
+ const said2 = message ? `: ${message.replace(/[.!?。]+$/u, "")}` : "";
488
+ const retryAfter = retryAfterSeconds(headers);
489
+ const code = vendorCode(data);
490
+ const extra = { ...code ? { vendorCode: code } : {}, ...retryAfter !== void 0 ? { retryAfter } : {} };
491
+ const custom = request.errors?.[status];
492
+ const withCustom = (fallback) => custom ? `${custom.replace(/\.$/, "")} (HTTP ${status}).${message ? ` ${label} said: "${message}".` : ""}${nothingChanged}` : fallback;
493
+ if (status >= 500) {
494
+ if (request.write) {
495
+ return new OutcomeUnknown(`${label} answered HTTP ${status}${said2}, so it is not known whether the change was made.`);
496
+ }
497
+ return new ToolFailure(withCustom(`${label} had a server error (HTTP ${status})${said2}. Try again later.${nothingChanged}`), { status, ...extra });
498
+ }
499
+ if (status === 429) {
500
+ return new ToolFailure(
501
+ `${label} rate limit reached (HTTP 429).${nothingChanged} ` + (retryAfter !== void 0 ? `Retry after ${retryAfter} seconds.` : "Wait a while before retrying."),
502
+ { status, ...extra }
503
+ );
504
+ }
505
+ if (status === 401) {
506
+ return new ToolFailure(
507
+ withCustom(`${label} rejected the credentials (HTTP 401)${said2}. ${checkCredentials}${nothingChanged}`),
508
+ { status, ...extra }
509
+ );
510
+ }
511
+ if (status === 403) return new ToolFailure(withCustom(`${label} refused the request (HTTP 403)${said2}.${nothingChanged}`), { status, ...extra });
512
+ if (status === 404) return new ToolFailure(withCustom(`${label} found nothing there (HTTP 404)${said2}.${nothingChanged}`), { status, ...extra });
513
+ if (status >= 400) return new ToolFailure(withCustom(`${label} rejected the request (HTTP ${status})${said2}.${nothingChanged}`), { status, ...extra });
514
+ return new ToolFailure(`${label} answered with an unexpected HTTP ${status}.${nothingChanged}`, { status });
515
+ }
516
+ async function api(request) {
517
+ const method = request.method ?? "GET";
518
+ if (env.readOnly && !SAFE_METHODS.has(method) && !request.safe) {
519
+ throw new Error(`read-only tool sent ${method}`);
520
+ }
521
+ const origin = request.origin ?? env.origins[0];
522
+ if (!origin || !env.origins.includes(origin)) throw new Error("undeclared origin");
523
+ const url = new URL(request.path, origin);
524
+ if (url.origin !== origin || !request.path.startsWith("/")) throw new Error("path outside the origin");
525
+ for (const [key, value] of Object.entries(request.query ?? {})) {
526
+ if (value === void 0 || value === null) continue;
527
+ if (Array.isArray(value)) {
528
+ url.searchParams.delete(key);
529
+ for (const item of value) url.searchParams.append(key, String(item));
530
+ } else {
531
+ url.searchParams.set(key, String(value));
532
+ }
533
+ }
534
+ const headers = {
535
+ accept: "application/json",
536
+ "user-agent": USER_AGENT,
537
+ ...request.auth === false ? {} : env.authHeaders(),
538
+ ...request.headers
539
+ };
540
+ let body;
541
+ if (request.json !== void 0) {
542
+ body = JSON.stringify(request.json);
543
+ headers["content-type"] = "application/json";
544
+ } else if (request.body) {
545
+ body = request.body;
546
+ headers["content-type"] = request.contentType ?? "application/octet-stream";
547
+ }
548
+ const started = Date.now();
549
+ if (request.write) env.onWriteSent();
550
+ let response;
551
+ try {
552
+ response = await ctx.fetch(url.toString(), { method, headers, ...body !== void 0 ? { body } : {}, ...ctx.signal ? { signal: ctx.signal } : {} });
553
+ } catch (error) {
554
+ env.log(`${env.vendor} ${env.tool} ${method} failed ${Date.now() - started}ms`);
555
+ if (errorCode(error) === "URL_REFUSED") {
556
+ throw new ToolFailure(`The request to ${label} was blocked before it was sent (${describe(error)}).${nothingChanged}`);
557
+ }
558
+ if (request.write) {
559
+ throw new OutcomeUnknown(`${label} did not answer (${describe(error)}), so it is not known whether the change was made.`);
560
+ }
561
+ if (errorCode(error) === "TOO_LARGE") throw new ToolFailure(`The reply from ${label} is larger than this host can read.${nothingChanged}`);
562
+ throw new ToolFailure(`${label} could not be reached (${describe(error)}). Try again later.${nothingChanged}`);
563
+ }
564
+ env.log(`${env.vendor} ${env.tool} ${method} ${response.status} ${Date.now() - started}ms`);
565
+ let bytes;
566
+ try {
567
+ bytes = await readCapped(response, request.maxBytes ?? MAX_API_RESPONSE_BYTES);
568
+ } catch (error) {
569
+ if (request.write && (response.ok || response.status >= 500)) {
570
+ throw new OutcomeUnknown(`${label} answered HTTP ${response.status}, but the reply could not be read (${describe(error)}), so it is not known whether the change was made.`);
571
+ }
572
+ throw new ToolFailure(`${label} answered HTTP ${response.status}, but the reply could not be read (${describe(error)}).${response.ok ? "" : nothingChanged}`);
573
+ }
574
+ const data = request.binary && response.ok ? bytes : parseBody(bytes, response.headers.get("content-type"));
575
+ if (response.ok) return { status: response.status, headers: response.headers, data };
576
+ throw failureFor(response.status, response.headers, data, request);
577
+ }
578
+ async function media(rawUrl, options) {
579
+ const { what } = options;
580
+ let url;
581
+ try {
582
+ url = new URL(rawUrl);
583
+ } catch {
584
+ throw new ToolFailure(`The ${what} URL is not a valid URL.${nothingChanged}`);
585
+ }
586
+ if (url.protocol !== "https:") throw new ToolFailure(`The ${what} URL must start with https://.${nothingChanged}`);
587
+ const started = Date.now();
588
+ let response;
589
+ try {
590
+ response = await ctx.fetch(url.toString(), {
591
+ method: "GET",
592
+ headers: { accept: options.accept ?? "*/*", "user-agent": USER_AGENT },
593
+ ...ctx.signal ? { signal: ctx.signal } : {}
594
+ });
595
+ } catch (error) {
596
+ env.log(`${env.vendor} ${env.tool} media GET failed ${Date.now() - started}ms`);
597
+ if (errorCode(error) === "URL_REFUSED") {
598
+ throw new ToolFailure(`The ${what} URL was refused (${describe(error)}). Use a public https URL.${nothingChanged}`);
599
+ }
600
+ throw new ToolFailure(`The ${what} could not be downloaded (${describe(error)}).${nothingChanged}`);
601
+ }
602
+ env.log(`${env.vendor} ${env.tool} media GET ${response.status} ${Date.now() - started}ms`);
603
+ if (!response.ok) {
604
+ await response.body?.cancel().catch(() => {
605
+ });
606
+ throw new ToolFailure(`The ${what} URL answered HTTP ${response.status}.${nothingChanged}`);
607
+ }
608
+ try {
609
+ const bytes = await readCapped(response, options.maxBytes);
610
+ return { bytes, contentType: response.headers.get("content-type") };
611
+ } catch (error) {
612
+ if (error instanceof TooLarge) {
613
+ throw new ToolFailure(`The ${what} is larger than ${formatNumber(options.maxBytes)} bytes, the most ${label} accepts.${nothingChanged}`);
614
+ }
615
+ throw new ToolFailure(`The ${what} could not be downloaded (${describe(error)}).${nothingChanged}`);
616
+ }
617
+ }
618
+ return { api, media };
619
+ }
620
+
621
+ // src/core/origins.ts
622
+ function parseSiteUrl(value) {
623
+ const text = typeof value === "string" ? value.trim() : "";
624
+ if (!text) return { ok: false, problem: "is empty" };
625
+ let url;
626
+ try {
627
+ url = new URL(text.includes("://") ? text : `https://${text}`);
628
+ } catch {
629
+ return { ok: false, problem: "is not a valid address (expected one like https://example.com)" };
630
+ }
631
+ if (url.protocol !== "https:") return { ok: false, problem: `must be an https address, not ${url.protocol}//` };
632
+ if (url.username || url.password) return { ok: false, problem: "must not contain a user name or password" };
633
+ if (!url.hostname) return { ok: false, problem: "has no host name" };
634
+ return { ok: true, url, origin: url.origin };
635
+ }
636
+
637
+ // src/core/schema.ts
638
+ var patterns = /* @__PURE__ */ new Map();
639
+ function patternOf(source) {
640
+ let compiled = patterns.get(source);
641
+ if (!compiled) {
642
+ compiled = new RegExp(source, "u");
643
+ patterns.set(source, compiled);
644
+ }
645
+ return compiled;
646
+ }
647
+ function isPlainObject(value) {
648
+ return typeof value === "object" && value !== null && !Array.isArray(value);
649
+ }
650
+ function isHttpUrl(value) {
651
+ try {
652
+ const url = new URL(value);
653
+ return url.protocol === "https:" || url.protocol === "http:";
654
+ } catch {
655
+ return false;
656
+ }
657
+ }
658
+ function name(path) {
659
+ return `\`${path}\``;
660
+ }
661
+ function child(path, key) {
662
+ return path ? `${path}.${key}` : key;
663
+ }
664
+ function checkValue(schema, value, path, issues) {
665
+ switch (schema.type) {
666
+ case "object":
667
+ checkObject(schema, value, path, issues);
668
+ return;
669
+ case "array": {
670
+ if (!Array.isArray(value)) {
671
+ issues.push(`${name(path)} must be an array`);
672
+ return;
673
+ }
674
+ if (schema.minItems !== void 0 && value.length < schema.minItems) {
675
+ issues.push(`${name(path)} must have at least ${schema.minItems} item${schema.minItems === 1 ? "" : "s"}`);
676
+ }
677
+ if (schema.maxItems !== void 0 && value.length > schema.maxItems) {
678
+ issues.push(`${name(path)} must have at most ${schema.maxItems} item${schema.maxItems === 1 ? "" : "s"}`);
679
+ }
680
+ if (schema.uniqueItems && new Set(value.map((item) => JSON.stringify(item))).size !== value.length) {
681
+ issues.push(`${name(path)} must not repeat an item`);
682
+ }
683
+ if (schema.items) {
684
+ value.forEach((item, index) => checkValue(schema.items, item, `${path}[${index}]`, issues));
685
+ }
686
+ break;
687
+ }
688
+ case "string": {
689
+ if (typeof value !== "string") {
690
+ issues.push(`${name(path)} must be a string`);
691
+ return;
692
+ }
693
+ const length = Array.from(value).length;
694
+ if (schema.minLength !== void 0 && length < schema.minLength) {
695
+ issues.push(schema.minLength === 1 ? `${name(path)} must not be empty` : `${name(path)} must be at least ${schema.minLength} characters`);
696
+ }
697
+ if (schema.maxLength !== void 0 && length > schema.maxLength) {
698
+ issues.push(`${name(path)} must be at most ${schema.maxLength} characters (it has ${length})`);
699
+ }
700
+ if (schema.format === "uri" && !isHttpUrl(value)) {
701
+ issues.push(`${name(path)} must be an absolute http(s) URL`);
702
+ } else if (schema.pattern !== void 0 && !patternOf(schema.pattern).test(value)) {
703
+ issues.push(`${name(path)} does not have the expected format${schema.description ? ` (${schema.description})` : ""}`);
704
+ }
705
+ break;
706
+ }
707
+ case "integer":
708
+ case "number": {
709
+ if (typeof value !== "number" || !Number.isFinite(value) || schema.type === "integer" && !Number.isInteger(value)) {
710
+ issues.push(`${name(path)} must be ${schema.type === "integer" ? "an integer" : "a number"}`);
711
+ return;
712
+ }
713
+ if (schema.minimum !== void 0 && value < schema.minimum) {
714
+ issues.push(`${name(path)} must be at least ${schema.minimum}`);
715
+ }
716
+ if (schema.maximum !== void 0 && value > schema.maximum) {
717
+ issues.push(`${name(path)} must be at most ${schema.maximum}`);
718
+ }
719
+ break;
720
+ }
721
+ case "boolean":
722
+ if (typeof value !== "boolean") {
723
+ issues.push(`${name(path)} must be true or false`);
724
+ return;
725
+ }
726
+ break;
727
+ default:
728
+ break;
729
+ }
730
+ if (schema.enum && !schema.enum.includes(value)) {
731
+ issues.push(`${name(path)} must be one of ${schema.enum.map((option) => JSON.stringify(option)).join(", ")}`);
732
+ }
733
+ }
734
+ function checkObject(schema, value, path, issues) {
735
+ if (!isPlainObject(value)) {
736
+ issues.push(`${path ? name(path) : "the arguments"} must be an object`);
737
+ return;
738
+ }
739
+ const properties = schema.properties ?? {};
740
+ for (const key of schema.required ?? []) {
741
+ if (value[key] === void 0 || value[key] === null) issues.push(`${name(child(path, key))} is required`);
742
+ }
743
+ const unknown = [];
744
+ for (const [key, item] of Object.entries(value)) {
745
+ const property = properties[key];
746
+ if (!property) {
747
+ if (schema.additionalProperties === false) unknown.push(key);
748
+ continue;
749
+ }
750
+ if (item === void 0 || item === null) continue;
751
+ checkValue(property, item, child(path, key), issues);
752
+ }
753
+ if (unknown.length) {
754
+ const known = Object.keys(properties);
755
+ issues.push(`unknown ${path ? `field${unknown.length > 1 ? "s" : ""} in ${name(path)}` : `argument${unknown.length > 1 ? "s" : ""}`} ${unknown.map((key) => JSON.stringify(key)).join(", ")}` + (known.length ? ` (expected: ${known.join(", ")})` : ""));
756
+ }
757
+ }
758
+ function copyDefault(value) {
759
+ return typeof value === "object" && value !== null ? JSON.parse(JSON.stringify(value)) : value;
760
+ }
761
+ function validateArguments(schema, args) {
762
+ const input = args === void 0 || args === null ? {} : args;
763
+ if (!isPlainObject(input)) return { ok: false, issues: ["the arguments must be an object"] };
764
+ const value = { ...input };
765
+ if (!schema.properties?.["toolCallId"]) delete value["toolCallId"];
766
+ const issues = [];
767
+ checkObject(schema, value, "", issues);
768
+ if (issues.length) return { ok: false, issues };
769
+ for (const [key, property] of Object.entries(schema.properties ?? {})) {
770
+ if (value[key] === null) delete value[key];
771
+ if (value[key] === void 0 && property.default !== void 0) value[key] = copyDefault(property.default);
772
+ }
773
+ return { ok: true, value };
774
+ }
775
+
776
+ // src/core/upload-hosts.ts
777
+ var LABEL = /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/;
778
+ function uploadHostProblem(entry) {
779
+ if (typeof entry !== "string") return "must be a host name";
780
+ const name2 = entry.startsWith(".") ? entry.slice(1) : entry;
781
+ const labels = name2.split(".");
782
+ if (name2.length > 253 || !labels.every((label) => LABEL.test(label))) {
783
+ return "must be a lowercase host name like uploads.example.com, or one with a leading dot like .example.com for every host under it";
784
+ }
785
+ if (labels.length < 2) return "needs at least two labels, like example.com";
786
+ if (/^[0-9]+$/.test(labels[labels.length - 1])) return "must be a host name, not an IP address";
787
+ return void 0;
788
+ }
789
+
790
+ // src/core/connector.ts
791
+ var ANNOTATIONS = {
792
+ read: { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: true },
793
+ create: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: true },
794
+ update: { readOnlyHint: false, destructiveHint: true, idempotentHint: true, openWorldHint: true },
795
+ delete: { readOnlyHint: false, destructiveHint: true, idempotentHint: true, openWorldHint: true },
796
+ write: { readOnlyHint: false, destructiveHint: true, idempotentHint: false, openWorldHint: true }
797
+ };
798
+ var VENDOR_PATTERN = /^[a-z][a-z0-9-]{1,29}$/;
799
+ var TOOL_PATTERN = /^[a-z][a-z0-9_]{0,63}$/;
800
+ var CREDENTIAL_PATTERN = /^[a-z][a-z0-9_]{0,63}$/;
801
+ var PICKER_KEY_PATTERN = /^[a-z][a-z0-9_]{0,63}$/;
802
+ var DOT_PATH_PATTERN = /^[A-Za-z0-9_]+(?:\.[A-Za-z0-9_]+){0,5}$/;
803
+ var UNSAFE_PATH_NAMES = /* @__PURE__ */ new Set(["__proto__", "prototype", "constructor"]);
804
+ var PICKER_FIELDS = ["key", "label", "description", "multiple", "tool", "idField", "nameField", "legacyField"];
805
+ function deepFreeze(value) {
806
+ if (typeof value === "object" && value !== null && !Object.isFrozen(value)) {
807
+ Object.freeze(value);
808
+ for (const item of Object.values(value)) deepFreeze(item);
809
+ }
810
+ return value;
811
+ }
812
+ function assertDefinition(def) {
813
+ const problem = (message) => {
814
+ throw new Error(`connector "${def.vendor}": ${message}`);
815
+ };
816
+ if (!VENDOR_PATTERN.test(def.vendor)) problem("vendor must match ^[a-z][a-z0-9-]{1,29}$");
817
+ if (!def.label?.trim()) problem("label is required");
818
+ const originFields = def.originFields ?? [];
819
+ if (!def.origins.length && !originFields.length) problem("at least one origin or origin field is required");
820
+ for (const origin of def.origins) {
821
+ let url;
822
+ try {
823
+ url = new URL(origin);
824
+ } catch {
825
+ }
826
+ if (!url || url.protocol !== "https:" || url.origin !== origin) problem(`origin ${origin} must be an https origin like https://api.example.com`);
827
+ }
828
+ for (const name2 of def.credentials) {
829
+ if (!CREDENTIAL_PATTERN.test(name2)) problem(`credential ${name2} must match ^[a-z][a-z0-9_]*$`);
830
+ }
831
+ for (const [index, name2] of originFields.entries()) {
832
+ if (!def.credentials.includes(name2)) problem(`origin field ${name2} must be one of the credentials`);
833
+ if (originFields.indexOf(name2) !== index) problem(`origin field ${name2} is listed twice`);
834
+ }
835
+ const names = /* @__PURE__ */ new Set();
836
+ for (const tool of def.tools) {
837
+ if (!TOOL_PATTERN.test(tool.name)) problem(`tool ${tool.name} must match ^[a-z][a-z0-9_]{0,63}$`);
838
+ if (names.has(tool.name)) problem(`tool ${tool.name} is defined twice`);
839
+ names.add(tool.name);
840
+ if (!tool.title?.trim() || !tool.description?.trim()) problem(`tool ${tool.name} needs a title and a description`);
841
+ if (tool.description.length > 1024) problem(`tool ${tool.name} has a description over 1024 characters`);
842
+ if (!Object.hasOwn(ANNOTATIONS, tool.kind)) problem(`tool ${tool.name} has an unknown kind`);
843
+ if (tool.inputSchema.type !== "object" || tool.inputSchema.additionalProperties !== false) {
844
+ problem(`tool ${tool.name} needs an object input schema with additionalProperties: false`);
845
+ }
846
+ }
847
+ for (const tool of def.tools) {
848
+ if (tool.kind === "read") continue;
849
+ const check = def.tools.find((candidate) => candidate.name === tool.check);
850
+ if (!check || check.kind !== "read") problem(`write tool ${tool.name} needs check: the name of a read tool`);
851
+ }
852
+ assertUploadHosts(def, problem);
853
+ assertRequiredCredentials(def, problem);
854
+ assertAccountPickers(def, problem);
855
+ }
856
+ function assertUploadHosts(def, problem) {
857
+ const hosts = def.uploadHosts;
858
+ if (hosts === void 0) return;
859
+ if (!Array.isArray(hosts)) problem('uploadHosts must be a list of host names, e.g. [".blobstore.apple.com"]');
860
+ hosts.forEach((entry, index) => {
861
+ const wrong = uploadHostProblem(entry);
862
+ if (wrong) problem(`upload host ${JSON.stringify(entry)} ${wrong}`);
863
+ if (hosts.indexOf(entry) !== index) problem(`upload host ${String(entry)} is listed twice`);
864
+ });
865
+ }
866
+ function assertRequiredCredentials(def, problem) {
867
+ const required = def.requiredCredentials;
868
+ if (required === void 0) return;
869
+ if (!Array.isArray(required) || !required.length) {
870
+ problem('requiredCredentials must be a list of credential lists, e.g. [["access_token"], ["api_key"]]');
871
+ }
872
+ required.forEach((list, index) => {
873
+ const which = `requiredCredentials[${index}]`;
874
+ if (!Array.isArray(list) || !list.length) problem(`${which} must list at least one credential`);
875
+ list.forEach((name2, position) => {
876
+ if (typeof name2 !== "string" || !def.credentials.includes(name2)) problem(`${which}: ${String(name2)} is not one of the credentials`);
877
+ if (list.indexOf(name2) !== position) problem(`${which} lists ${name2} twice`);
878
+ });
879
+ });
880
+ const lists = required;
881
+ lists.forEach((list, index) => {
882
+ const covered = lists.findIndex((other, otherIndex) => otherIndex !== index && other.every((name2) => list.includes(name2)) && (other.length < list.length || otherIndex < index));
883
+ if (covered !== -1) problem(`requiredCredentials[${index}] contains all of requiredCredentials[${covered}], so it is never needed`);
884
+ if (!def.origins.length && !list.some((name2) => def.originFields?.includes(name2))) {
885
+ problem(`requiredCredentials[${index}] needs an origin field: the module has no fixed origin, so a call made with only these credentials could reach nothing`);
886
+ }
887
+ });
888
+ }
889
+ function isDotPath(value) {
890
+ return typeof value === "string" && DOT_PATH_PATTERN.test(value) && !value.split(".").some((name2) => UNSAFE_PATH_NAMES.has(name2));
891
+ }
892
+ function assertAccountPickers(def, problem) {
893
+ const pickers = def.accountPickers;
894
+ if (pickers === void 0) return;
895
+ if (!Array.isArray(pickers)) problem("accountPickers must be a list");
896
+ const keys = /* @__PURE__ */ new Set();
897
+ for (const item of pickers) {
898
+ if (typeof item !== "object" || item === null || Array.isArray(item)) problem("each account picker must be an object");
899
+ const picker = item;
900
+ const key = picker["key"];
901
+ if (typeof key !== "string" || !PICKER_KEY_PATTERN.test(key)) problem(`account picker ${JSON.stringify(key)}: key must match ^[a-z][a-z0-9_]{0,63}$`);
902
+ if (keys.has(key)) problem(`account picker ${key} is defined twice`);
903
+ keys.add(key);
904
+ const fail = (message) => problem(`account picker ${key}: ${message}`);
905
+ const unknown = Object.keys(picker).filter((field) => !PICKER_FIELDS.includes(field));
906
+ if (unknown.length) fail(`unknown field${unknown.length > 1 ? "s" : ""} ${unknown.join(", ")} (expected: ${PICKER_FIELDS.join(", ")})`);
907
+ const { label, description, multiple, legacyField } = picker;
908
+ if (typeof label !== "string" || !label.trim()) fail("label is required");
909
+ if (description !== void 0 && (typeof description !== "string" || !description.trim() || description.length > 1024)) {
910
+ fail("description, when given, must be a text of 1 to 1024 characters");
911
+ }
912
+ if (typeof multiple !== "boolean") fail("multiple must be true or false");
913
+ const tool = def.tools.find((candidate) => candidate.name === picker["tool"]);
914
+ if (!tool || tool.kind !== "read") fail("tool must be the name of a read tool");
915
+ if (tool.inputSchema.required?.length) fail(`its tool ${tool.name} must take no required argument`);
916
+ for (const field of ["idField", "nameField"]) {
917
+ if (!isDotPath(picker[field])) fail(`${field} must be a dot path into each item the tool returns, like "id" or "account.name"`);
918
+ }
919
+ if (legacyField !== void 0 && (typeof legacyField !== "string" || !CREDENTIAL_PATTERN.test(legacyField))) {
920
+ fail("legacyField, when given, must match ^[a-z][a-z0-9_]{0,63}$");
921
+ }
922
+ }
923
+ }
924
+ function copyPicker(picker) {
925
+ return {
926
+ key: picker.key,
927
+ label: picker.label,
928
+ ...picker.description !== void 0 ? { description: picker.description } : {},
929
+ multiple: picker.multiple,
930
+ tool: picker.tool,
931
+ idField: picker.idField,
932
+ nameField: picker.nameField,
933
+ ...picker.legacyField !== void 0 ? { legacyField: picker.legacyField } : {}
934
+ };
935
+ }
936
+ function result(payload, isError, files = []) {
937
+ return {
938
+ content: [{ type: "text", text: JSON.stringify(payload) }, ...files.map(resourceBlock)],
939
+ ...isError ? { isError: true } : {}
940
+ };
941
+ }
942
+ function failure(message, details = {}) {
943
+ return result({ error: message, ...details }, true);
944
+ }
945
+ function trimmed(values) {
946
+ const out = {};
947
+ if (typeof values !== "object" || values === null) return out;
948
+ for (const [key, value] of Object.entries(values)) {
949
+ if (value === void 0 || value === null) continue;
950
+ const text = String(value).trim();
951
+ if (text) out[key] = text;
952
+ }
953
+ return out;
954
+ }
955
+ function defineConnector(def) {
956
+ assertDefinition(def);
957
+ const { label } = def;
958
+ const tools = new Map(def.tools.map((tool) => [tool.name, tool]));
959
+ const toolList = def.tools.map((tool) => tool.name).join(", ");
960
+ const credentialLabel = (name2) => def.credentialLabels?.[name2] ?? `${label} ${name2.replace(/_/g, " ")}`;
961
+ const required = requiredAlternatives(def);
962
+ const notConnected = (unmet) => {
963
+ const [first] = unmet;
964
+ if (unmet.length === 1 && first) {
965
+ return `${label} is not connected: the ${andList(first.map(credentialLabel))} ${first.length > 1 ? "are" : "is"} missing.`;
966
+ }
967
+ return `${label} is not connected: it needs ${orList(unmet.map((missing) => `the ${andList(missing.map(credentialLabel))}`))}.`;
968
+ };
969
+ const descriptors = def.tools.map((tool) => ({
970
+ name: tool.name,
971
+ title: tool.title,
972
+ description: tool.description,
973
+ inputSchema: JSON.parse(JSON.stringify(tool.inputSchema)),
974
+ annotations: { ...ANNOTATIONS[tool.kind] }
975
+ }));
976
+ async function call(toolName, args, ctx) {
977
+ const tool = typeof toolName === "string" ? tools.get(toolName) : void 0;
978
+ if (!tool) return failure(`Unknown tool ${JSON.stringify(String(toolName))}. ${label} tools: ${toolList}.`);
979
+ if (!ctx || typeof ctx.fetch !== "function") return failure(`${tool.name} cannot run: the host gave it no fetch function.`);
980
+ const log = (text) => {
981
+ try {
982
+ ctx.log?.(text);
983
+ } catch {
984
+ }
985
+ };
986
+ const given = trimmed(ctx.credentials);
987
+ const credentials = def.normalizeCredentials ? def.normalizeCredentials({ ...given }) : given;
988
+ const has = (name2) => Boolean(credentials[name2]);
989
+ const unmet = unmetAlternatives(required, has);
990
+ if (unmet.length) return failure(notConnected(unmet));
991
+ const complete = required.filter((list) => list.every(has));
992
+ const inUse = def.credentials.filter((name2) => complete.some((list) => list.includes(name2)));
993
+ const fieldOrigins = /* @__PURE__ */ new Map();
994
+ for (const name2 of def.originFields ?? []) {
995
+ if (!given[name2] && !inUse.includes(name2)) continue;
996
+ const site = parseSiteUrl(given[name2] ?? "");
997
+ if (!site.ok) return failure(`${label} is not connected correctly: the ${credentialLabel(name2)} ${site.problem}. Nothing was sent to ${label}.`);
998
+ fieldOrigins.set(name2, site.origin);
999
+ }
1000
+ const origins = [.../* @__PURE__ */ new Set([...def.origins, ...fieldOrigins.values()])];
1001
+ const parsed = validateArguments(tool.inputSchema, args);
1002
+ if (!parsed.ok) return failure(`Invalid arguments for ${tool.name}: ${parsed.issues.join("; ")}. Nothing was sent to ${label}.`);
1003
+ const frozenCredentials = Object.freeze({ ...credentials });
1004
+ let writeSent = false;
1005
+ const fileLimit = fileLimitOf(ctx);
1006
+ const files = [];
1007
+ let fileBytes = 0;
1008
+ const http = createHttp({
1009
+ vendor: def.vendor,
1010
+ label,
1011
+ tool: tool.name,
1012
+ readOnly: tool.kind === "read",
1013
+ origins,
1014
+ // A 401 names the credentials in use (for a module that needs none, the ones given).
1015
+ credentialLabels: (inUse.length ? inUse : def.credentials.filter(has)).map(credentialLabel),
1016
+ ctx,
1017
+ authHeaders: () => def.authHeaders?.(frozenCredentials) ?? {},
1018
+ log,
1019
+ onWriteSent: () => {
1020
+ writeSent = true;
1021
+ }
1022
+ });
1023
+ const helpers = {
1024
+ tool: tool.name,
1025
+ credentials: frozenCredentials,
1026
+ ctx,
1027
+ origins: Object.freeze([...origins]),
1028
+ originOf: (credential) => {
1029
+ const origin = fieldOrigins.get(credential);
1030
+ if (!origin) throw new Error(`${credential} gives no origin in this call`);
1031
+ return origin;
1032
+ },
1033
+ api: http.api,
1034
+ media: http.media,
1035
+ page: (input) => fitPage(input),
1036
+ cursor: (cursor) => decodeCursor(tool.name, cursor),
1037
+ makeCursor: (state) => encodeCursor(tool.name, state),
1038
+ fileLimit: () => fileLimit,
1039
+ file: ({ name: name2, mimeType, bytes }) => {
1040
+ if (fileLimit === null) throw new ToolFailure(`This host takes no files, so ${tool.name} cannot hand one back.`);
1041
+ const total = fileBytes + bytes.byteLength;
1042
+ if (total > fileLimit) {
1043
+ throw new ToolFailure(files.length ? `The files of this call have ${formatNumber(total)} bytes in all, more than the ${formatNumber(fileLimit)} bytes this host takes from one call.` : `The file has ${formatNumber(bytes.byteLength)} bytes, more than the ${formatNumber(fileLimit)} bytes this host takes.`);
1044
+ }
1045
+ fileBytes = total;
1046
+ const info = { name: fileName(name2), mimeType: fileType(mimeType), size: bytes.byteLength };
1047
+ files.push({ ...info, bytes });
1048
+ return { ...info };
1049
+ },
1050
+ log
1051
+ };
1052
+ try {
1053
+ const data = await tool.run(parsed.value, helpers);
1054
+ const fitted = shrinkToFit(data ?? {});
1055
+ if (!fitted) return failure(`The ${label} result was too large to return. Ask for fewer items.`);
1056
+ const payload = fitted.value;
1057
+ return result(fitted.truncated && typeof payload === "object" ? { ...payload, truncated: true } : payload, false, files);
1058
+ } catch (error) {
1059
+ if (error instanceof OutcomeUnknown) {
1060
+ return result({
1061
+ outcome: "unknown",
1062
+ check: tool.check,
1063
+ error: `${error.message} Call ${tool.check} to see whether it was, before trying again.`
1064
+ }, true);
1065
+ }
1066
+ if (error instanceof ToolFailure) return failure(error.message, error.details);
1067
+ log(`${def.vendor} ${tool.name} unexpected ${error?.name ?? "error"}`);
1068
+ if (writeSent) {
1069
+ return result({
1070
+ outcome: "unknown",
1071
+ check: tool.check,
1072
+ error: `${tool.name} stopped unexpectedly after the change was sent to ${label}. Call ${tool.check} to see whether it was made, before trying again.`
1073
+ }, true);
1074
+ }
1075
+ return failure(`${tool.name} failed unexpectedly.${tool.kind === "read" ? "" : " Nothing was changed."}`);
1076
+ }
1077
+ }
1078
+ return deepFreeze({
1079
+ vendor: def.vendor,
1080
+ origins: [...def.origins],
1081
+ originFields: [...def.originFields ?? []],
1082
+ uploadHosts: [...def.uploadHosts ?? []],
1083
+ credentials: [...def.credentials],
1084
+ requiredCredentials: required.map((list) => [...list]),
1085
+ accountPickers: (def.accountPickers ?? []).map(copyPicker),
1086
+ tools: descriptors,
1087
+ call
1088
+ });
1089
+ }
1090
+
1091
+ // src/core/jwt.ts
1092
+ var TOKEN_EARLY_MS = 5 * 60 * 1e3;
1093
+
1094
+ // src/vendors/tiktok/media.ts
1095
+ var VIDEO_TYPES = ["video/mp4", "video/quicktime", "video/webm"];
1096
+ function ascii(bytes, start, length) {
1097
+ return String.fromCharCode(...bytes.subarray(start, start + length));
1098
+ }
1099
+ function sniffVideo(bytes) {
1100
+ if (bytes.length >= 12 && ascii(bytes, 4, 4) === "ftyp") return ascii(bytes, 8, 4) === "qt " ? "video/quicktime" : "video/mp4";
1101
+ if (bytes.length >= 4 && bytes[0] === 26 && bytes[1] === 69 && bytes[2] === 223 && bytes[3] === 163) return "video/webm";
1102
+ return void 0;
1103
+ }
1104
+ var MB = 1024 * 1024;
1105
+ var MIN_CHUNK_BYTES = 5 * MB;
1106
+ var CHUNK_BYTES = 10 * MB;
1107
+ var MAX_VIDEO_BYTES = 4 * 1024 * MB;
1108
+ function planFor(size, chunkSize) {
1109
+ const count = Math.max(1, Math.floor(size / chunkSize));
1110
+ const ranges = [];
1111
+ for (let index = 0; index < count; index++) {
1112
+ const first = index * chunkSize;
1113
+ const last = index === count - 1 ? size - 1 : first + chunkSize - 1;
1114
+ ranges.push([first, last]);
1115
+ }
1116
+ return { chunkSize, count, ranges };
1117
+ }
1118
+ function chunkPlan(size) {
1119
+ return planFor(size, size <= CHUNK_BYTES ? size : CHUNK_BYTES);
1120
+ }
1121
+ function chunkAt(plan, offset) {
1122
+ if (!Number.isSafeInteger(offset) || offset < 0 || offset % plan.chunkSize !== 0) return -1;
1123
+ const index = offset / plan.chunkSize;
1124
+ return index < plan.count ? index : -1;
1125
+ }
1126
+
1127
+ // src/vendors/tiktok/source.ts
1128
+ var USER_AGENT2 = "agent-connectors";
1129
+ var ACCEPT_VIDEO = "video/mp4,video/quicktime,video/webm,application/octet-stream;q=0.8";
1130
+ var CONTENT_RANGE = /^bytes (\d{1,15})-(\d{1,15})\/(\d{1,15}|\*)$/i;
1131
+ var STRONG_ETAG = /^(?!W\/)[\x21-\x7e]{1,200}$/;
1132
+ var MAX_WHOLE_BYTES = 256 * 1024 * 1024;
1133
+ var SourceProblem = class extends Error {
1134
+ constructor(message) {
1135
+ super(message);
1136
+ this.name = "SourceProblem";
1137
+ }
1138
+ };
1139
+ var TooLong = class extends Error {
1140
+ };
1141
+ function errorCode2(error) {
1142
+ const code = error?.code;
1143
+ return typeof code === "string" ? code : void 0;
1144
+ }
1145
+ function describe2(error) {
1146
+ const name2 = error?.name;
1147
+ const code = errorCode2(error);
1148
+ if (code === "TIMEOUT" || name2 === "TimeoutError") return "the request timed out";
1149
+ if (code === "ABORTED" || name2 === "AbortError") return "the request was cancelled";
1150
+ if (code === "TOO_LARGE") return "the reply was too large";
1151
+ return cleanVendorText(error?.message, 200) ?? "a network error";
1152
+ }
1153
+ async function readUpTo(response, max) {
1154
+ const declared = Number(response.headers.get("content-length"));
1155
+ if (Number.isFinite(declared) && declared > max) {
1156
+ await response.body?.cancel().catch(() => {
1157
+ });
1158
+ throw new TooLong();
1159
+ }
1160
+ if (!response.body) return new Uint8Array(0);
1161
+ const reader = response.body.getReader();
1162
+ const chunks = [];
1163
+ let total = 0;
1164
+ for (; ; ) {
1165
+ const { done, value } = await reader.read();
1166
+ if (done) break;
1167
+ total += value.byteLength;
1168
+ if (total > max) {
1169
+ await reader.cancel().catch(() => {
1170
+ });
1171
+ throw new TooLong();
1172
+ }
1173
+ chunks.push(value);
1174
+ }
1175
+ const bytes = new Uint8Array(total);
1176
+ let at = 0;
1177
+ for (const chunk of chunks) {
1178
+ bytes.set(chunk, at);
1179
+ at += chunk.byteLength;
1180
+ }
1181
+ return bytes;
1182
+ }
1183
+ var HOST_LIMIT = "The host refused the download as too large for it: it downloads at most a set size (often 25 to 50 MB), and either it does not pass byte-range requests (the Range header) on or the server ignored them, so the whole file came instead of one chunk. Use a smaller video, a host that passes byte ranges on, or source PULL_FROM_URL from a domain or URL prefix verified in the TikTok app's URL properties, where TikTok downloads up to 4 GB itself.";
1184
+ function downloadProblem(error) {
1185
+ const code = errorCode2(error);
1186
+ if (code === "URL_REFUSED") return new SourceProblem(`The video URL was refused (${describe2(error)}). Use a public https URL.`);
1187
+ if (code === "TOO_LARGE") return new SourceProblem(HOST_LIMIT);
1188
+ return new SourceProblem(`The video could not be downloaded (${describe2(error)}).`);
1189
+ }
1190
+ async function readBody(response, max, whole) {
1191
+ try {
1192
+ return await readUpTo(response, max);
1193
+ } catch (error) {
1194
+ if (!(error instanceof TooLong)) throw downloadProblem(error);
1195
+ throw new SourceProblem(whole ? `The video URL sent the whole file instead of the part asked for, and it is larger than ${formatNumber(max)} bytes.` : "The video URL sent more than the part asked for.");
1196
+ }
1197
+ }
1198
+ async function readPart(h, videoUrl, first, last) {
1199
+ let url;
1200
+ try {
1201
+ url = new URL(videoUrl);
1202
+ } catch {
1203
+ throw new SourceProblem("The video URL is not a valid URL.");
1204
+ }
1205
+ if (url.protocol !== "https:") throw new SourceProblem("The video URL must start with https://.");
1206
+ const started = Date.now();
1207
+ let response;
1208
+ try {
1209
+ response = await h.ctx.fetch(url.toString(), {
1210
+ method: "GET",
1211
+ headers: { accept: ACCEPT_VIDEO, "user-agent": USER_AGENT2, range: `bytes=${first}-${last}` },
1212
+ ...h.ctx.signal ? { signal: h.ctx.signal } : {}
1213
+ });
1214
+ } catch (error) {
1215
+ h.log(`tiktok ${h.tool} media GET failed ${Date.now() - started}ms`);
1216
+ throw downloadProblem(error);
1217
+ }
1218
+ h.log(`tiktok ${h.tool} media GET ${response.status} ${Date.now() - started}ms`);
1219
+ const tag = response.headers.get("etag")?.trim();
1220
+ const etag = tag && STRONG_ETAG.test(tag) ? tag : void 0;
1221
+ if (response.status === 206) {
1222
+ const match = CONTENT_RANGE.exec(response.headers.get("content-range")?.trim() ?? "");
1223
+ const start = Number(match?.[1]);
1224
+ const end = Number(match?.[2]);
1225
+ const size = match?.[3];
1226
+ const total = Number(size);
1227
+ if (!match || size === void 0 || start !== first || end < start || end > last || size !== "*" && (end >= total || end !== last && end !== total - 1)) {
1228
+ await response.body?.cancel().catch(() => {
1229
+ });
1230
+ throw new SourceProblem("The video URL answered with another part of the file than the one asked for.");
1231
+ }
1232
+ if (size === "*") {
1233
+ await response.body?.cancel().catch(() => {
1234
+ });
1235
+ throw new SourceProblem("The video URL did not say how large the file is, which TikTok needs to know before the upload starts.");
1236
+ }
1237
+ const bytes = await readBody(response, end - start + 1, false);
1238
+ if (bytes.length !== end - start + 1) throw new SourceProblem("The download of the video ended early.");
1239
+ return { bytes, start, total, ...etag ? { etag } : {} };
1240
+ }
1241
+ if (response.status === 200) {
1242
+ const bytes = await readBody(response, MAX_WHOLE_BYTES, true);
1243
+ return { bytes, start: 0, total: bytes.length, ...etag ? { etag } : {} };
1244
+ }
1245
+ await response.body?.cancel().catch(() => {
1246
+ });
1247
+ if (response.status === 416) {
1248
+ throw new SourceProblem(first ? `The video URL has no bytes from ${formatNumber(first)} on (HTTP 416): the file is smaller than when the upload started.` : "The video URL has no bytes (HTTP 416): the file is empty.");
1249
+ }
1250
+ throw new SourceProblem(`The video URL answered HTTP ${response.status}.`);
1251
+ }
1252
+
1253
+ // src/vendors/tiktok/upload.ts
1254
+ var UPLOAD_ORIGINS = ["https://open-upload.tiktokapis.com", "https://upload.us.tiktokapis.com"];
1255
+ var CALL_BUDGET_MS = 35e3;
1256
+ var UPLOAD_LIFETIME_MS = 60 * 60 * 1e3;
1257
+ var PUBLISH_ID = /^[A-Za-z0-9._~-]{1,64}$/;
1258
+ var USER_AGENT3 = "agent-connectors";
1259
+ var MAX_REPLY_BYTES = 64 * 1024;
1260
+ var ENDED = /* @__PURE__ */ new Set(["PUBLISH_COMPLETE", "SEND_TO_USER_INBOX", "FAILED"]);
1261
+ var START_AGAIN = "The rest cannot be sent, and nothing was posted: post the video again without cursor.";
1262
+ var EXPIRED = "TikTok refused the chunk because the post's upload address expired (HTTP 403): it works for an hour after the post was started. " + START_AGAIN;
1263
+ var GONE = "TikTok has no upload for this post any more (HTTP 404): its upload address works for an hour after the post was started. If get_post_status does not show the post, post the video again without cursor.";
1264
+ function uploadAddress(value) {
1265
+ if (typeof value !== "string" || !value) return void 0;
1266
+ let url;
1267
+ try {
1268
+ url = new URL(value);
1269
+ } catch {
1270
+ return void 0;
1271
+ }
1272
+ if (!UPLOAD_ORIGINS.includes(url.origin) || url.username || url.password) return void 0;
1273
+ url.hash = "";
1274
+ return url.toString();
1275
+ }
1276
+ async function sourceKey(videoUrl) {
1277
+ let normal = videoUrl;
1278
+ try {
1279
+ normal = new URL(videoUrl).toString();
1280
+ } catch {
1281
+ }
1282
+ return (await sha256Hex(normal)).slice(0, 16);
1283
+ }
1284
+ function cursorState(state, offset) {
1285
+ return {
1286
+ s: state.uploadUrl,
1287
+ i: state.publishId,
1288
+ n: state.total,
1289
+ c: state.chunkSize,
1290
+ o: offset,
1291
+ y: state.type,
1292
+ u: state.source,
1293
+ m: state.inbox ? "i" : "d",
1294
+ a: Math.floor(state.startedAt / 1e3),
1295
+ ...state.etag ? { e: state.etag } : {}
1296
+ };
1297
+ }
1298
+ function stateFromCursor(raw) {
1299
+ const uploadUrl = uploadAddress(raw["s"]);
1300
+ const { i: publishId, n: total, c: chunkSize, o: offset, y: type, u: source, m: mode, a: started, e: etag } = raw;
1301
+ if (!uploadUrl || typeof publishId !== "string" || !PUBLISH_ID.test(publishId)) return void 0;
1302
+ if (typeof total !== "number" || !Number.isSafeInteger(total) || total < 1 || total > MAX_VIDEO_BYTES) return void 0;
1303
+ if (typeof chunkSize !== "number" || chunkSize !== chunkPlan(total).chunkSize) return void 0;
1304
+ if (typeof offset !== "number" || chunkAt(planFor(total, chunkSize), offset) === -1) return void 0;
1305
+ if (typeof type !== "string" || !VIDEO_TYPES.includes(type)) return void 0;
1306
+ if (typeof source !== "string" || !/^[0-9a-f]{16}$/.test(source)) return void 0;
1307
+ if (mode !== "d" && mode !== "i") return void 0;
1308
+ if (typeof started !== "number" || !Number.isSafeInteger(started) || started < 1) return void 0;
1309
+ if (etag !== void 0 && (typeof etag !== "string" || !STRONG_ETAG.test(etag))) return void 0;
1310
+ return {
1311
+ state: {
1312
+ uploadUrl,
1313
+ publishId,
1314
+ total,
1315
+ chunkSize,
1316
+ type,
1317
+ source,
1318
+ ...typeof etag === "string" ? { etag } : {},
1319
+ inbox: mode === "i",
1320
+ startedAt: started * 1e3
1321
+ },
1322
+ offset
1323
+ };
1324
+ }
1325
+ var sending = /* @__PURE__ */ new Set();
1326
+ async function exclusive(publishId, run) {
1327
+ if (sending.has(publishId)) {
1328
+ throw new ToolFailure("Another call is sending this video right now: wait for its result, then go on with its nextCursor. Nothing was sent.");
1329
+ }
1330
+ sending.add(publishId);
1331
+ try {
1332
+ return await run();
1333
+ } finally {
1334
+ sending.delete(publishId);
1335
+ }
1336
+ }
1337
+ function parseReply(bytes) {
1338
+ if (!bytes.length) return null;
1339
+ const text = utf8Decode(bytes);
1340
+ try {
1341
+ return JSON.parse(text);
1342
+ } catch {
1343
+ return text;
1344
+ }
1345
+ }
1346
+ function said(data) {
1347
+ const error = data?.error;
1348
+ const message = cleanVendorText(typeof error?.message === "string" && error.message ? error.message : void 0) ?? (typeof error?.code === "string" ? cleanVendorText(error.code) : void 0) ?? vendorMessage(data);
1349
+ return message ? `: ${message.replace(/[.!?]+$/u, "")}` : "";
1350
+ }
1351
+ async function putChunk(h, state, first, last, bytes) {
1352
+ const started = Date.now();
1353
+ let response;
1354
+ try {
1355
+ response = await h.ctx.fetch(state.uploadUrl, {
1356
+ method: "PUT",
1357
+ headers: {
1358
+ accept: "application/json",
1359
+ "user-agent": USER_AGENT3,
1360
+ "content-type": state.type,
1361
+ "content-range": `bytes ${first}-${last}/${state.total}`
1362
+ },
1363
+ body: bytes,
1364
+ ...h.ctx.signal ? { signal: h.ctx.signal } : {}
1365
+ });
1366
+ } catch (error) {
1367
+ h.log(`tiktok ${h.tool} PUT failed ${Date.now() - started}ms`);
1368
+ if (error?.code === "URL_REFUSED") {
1369
+ return { kind: "refused", resumable: false, message: `The upload to TikTok was blocked before it was sent (${describe2(error)}).` };
1370
+ }
1371
+ return { kind: "unclear", reason: describe2(error) };
1372
+ }
1373
+ h.log(`tiktok ${h.tool} PUT ${response.status} ${Date.now() - started}ms`);
1374
+ const { status } = response;
1375
+ let data = null;
1376
+ try {
1377
+ data = parseReply(await readUpTo(response, MAX_REPLY_BYTES));
1378
+ } catch {
1379
+ if (status >= 200 && status < 300 || status >= 500) return { kind: "unclear", reason: `HTTP ${status}, but the reply could not be read` };
1380
+ }
1381
+ if (status === 201) return { kind: "complete" };
1382
+ if (status >= 200 && status < 300) return { kind: "more" };
1383
+ if (status === 416) return { kind: "mismatch" };
1384
+ if (status >= 500) return { kind: "unclear", reason: `HTTP ${status}${said(data)}` };
1385
+ if (status === 429) {
1386
+ const retryAfter = retryAfterSeconds(response.headers);
1387
+ return {
1388
+ kind: "refused",
1389
+ resumable: true,
1390
+ status,
1391
+ message: `TikTok rate limit reached (HTTP 429). ${retryAfter !== void 0 ? `Retry after ${retryAfter} seconds.` : "Wait a while before going on."}`,
1392
+ ...retryAfter !== void 0 ? { retryAfter } : {}
1393
+ };
1394
+ }
1395
+ if (status === 403) return { kind: "refused", resumable: false, status, message: EXPIRED };
1396
+ if (status === 404) return { kind: "refused", resumable: false, status, message: GONE };
1397
+ if (status >= 400) {
1398
+ return { kind: "refused", resumable: false, status, message: `TikTok rejected a chunk of the video (HTTP ${status})${said(data)}. ${START_AGAIN}` };
1399
+ }
1400
+ return { kind: "unclear", reason: `an unexpected HTTP ${status}` };
1401
+ }
1402
+ function resumeHint(cursor) {
1403
+ return `Calling post_video again with the same video_url and cursor "${cursor}" is safe: it asks TikTok first, follows the post if TikTok has the whole video, and sends only what TikTok lacks; the cursor belongs to this one post, so it never makes a second one.`;
1404
+ }
1405
+ function changedSince(state, part) {
1406
+ if (part.total !== state.total) {
1407
+ return `The file at video_url is ${formatNumber(part.total)} bytes now, not the ${formatNumber(state.total)} it had when the upload started.`;
1408
+ }
1409
+ if (state.etag && part.etag && state.etag !== part.etag) return "The file at video_url changed since the upload started (its ETag is different).";
1410
+ return void 0;
1411
+ }
1412
+ async function chunkBytes(h, run, held, first, last) {
1413
+ const covers = (part2) => part2.start <= first && part2.start + part2.bytes.length > last;
1414
+ if (held && covers(held)) return { bytes: held.bytes.subarray(first - held.start, last + 1 - held.start), held };
1415
+ const prefix = held && held.start <= first && held.start + held.bytes.length > first ? held.bytes.subarray(first - held.start) : void 0;
1416
+ const from = first + (prefix?.length ?? 0);
1417
+ const part = await readPart(h, run.videoUrl, from, last);
1418
+ const changed = changedSince(run.state, part);
1419
+ if (changed) throw new ToolFailure(`${changed} ${START_AGAIN}`);
1420
+ if (covers(part)) return { bytes: part.bytes.subarray(first - part.start, last + 1 - part.start), held: part };
1421
+ if (!prefix || part.start !== from || part.start + part.bytes.length <= last) {
1422
+ throw new SourceProblem("The video URL answered with another part of the file than the one asked for.");
1423
+ }
1424
+ const bytes = new Uint8Array(last - first + 1);
1425
+ bytes.set(prefix, 0);
1426
+ bytes.set(part.bytes.subarray(0, last + 1 - from), prefix.length);
1427
+ return { bytes, held: { bytes, start: first, total: part.total, ...part.etag ? { etag: part.etag } : {} } };
1428
+ }
1429
+ async function where(h, run) {
1430
+ if (h.ctx.signal?.aborted) return void 0;
1431
+ try {
1432
+ return await run.readStatus();
1433
+ } catch (error) {
1434
+ if (error instanceof ToolFailure) return void 0;
1435
+ throw error;
1436
+ }
1437
+ }
1438
+ async function transfer(h, run) {
1439
+ const { state, started } = run;
1440
+ const plan = planFor(state.total, state.chunkSize);
1441
+ let { offset, held } = run;
1442
+ let chunkStarted = run.heldSince ?? Date.now();
1443
+ let lastMs = 0;
1444
+ let sent = 0;
1445
+ let finalSent = false;
1446
+ let resynced = false;
1447
+ try {
1448
+ for (; ; ) {
1449
+ const index = chunkAt(plan, offset);
1450
+ if (index === -1) throw new ToolFailure(`TikTok's upload of this video is at byte ${formatNumber(offset)}, where no chunk starts. ${START_AGAIN}`);
1451
+ if (sent > 0) {
1452
+ if (h.ctx.signal?.aborted) return { done: false, uploaded: offset, stopped: "The call was cancelled." };
1453
+ if (Date.now() - started + lastMs * 1.5 > CALL_BUDGET_MS) return { done: false, uploaded: offset };
1454
+ chunkStarted = Date.now();
1455
+ }
1456
+ const [first, last] = plan.ranges[index];
1457
+ let bytes;
1458
+ try {
1459
+ ({ bytes, held } = await chunkBytes(h, run, held, first, last));
1460
+ } catch (error) {
1461
+ if (error instanceof SourceProblem) return { done: false, uploaded: offset, stopped: `Reading the next chunk of the video failed. ${error.message}` };
1462
+ throw error;
1463
+ }
1464
+ const final = index === plan.count - 1;
1465
+ if (final) finalSent = true;
1466
+ const answer = await putChunk(h, state, first, last, bytes);
1467
+ sent += 1;
1468
+ lastMs = Date.now() - chunkStarted;
1469
+ if (answer.kind === "complete") return { done: true };
1470
+ if (answer.kind === "more" && !final) {
1471
+ offset = last + 1;
1472
+ continue;
1473
+ }
1474
+ if (answer.kind === "refused") {
1475
+ if (!answer.resumable) throw new ToolFailure(answer.message, answer.status !== void 0 ? { status: answer.status } : {});
1476
+ return { done: false, uploaded: offset, stopped: answer.message, ...answer.retryAfter !== void 0 ? { retryAfter: answer.retryAfter } : {} };
1477
+ }
1478
+ if (answer.kind === "mismatch") {
1479
+ const status2 = resynced ? void 0 : await where(h, run);
1480
+ if (status2 && (ENDED.has(status2.status) || status2.uploadedBytes === state.total)) return { done: true };
1481
+ const at = status2?.uploadedBytes;
1482
+ if (at !== void 0 && at !== first && chunkAt(plan, at) !== -1) {
1483
+ resynced = true;
1484
+ offset = at;
1485
+ continue;
1486
+ }
1487
+ const refusal = `TikTok refused the chunk of bytes ${formatNumber(first)} to ${formatNumber(last)} (HTTP 416): its upload of this video is not at that point, and its status did not say where it is.`;
1488
+ throw new ToolFailure(
1489
+ final ? `${refusal} TikTok may already have the whole video: if get_post_status with publish_id ${state.publishId} does not show the post, post the video again without cursor.` : `${refusal} ${START_AGAIN}`,
1490
+ { status: 416 }
1491
+ );
1492
+ }
1493
+ const reason = answer.kind === "unclear" ? answer.reason : "TikTok asked for more after the last chunk";
1494
+ const status = await where(h, run);
1495
+ if (status && (ENDED.has(status.status) || status.uploadedBytes === state.total)) return { done: true };
1496
+ if (status?.uploadedBytes === last + 1 && !final) {
1497
+ offset = last + 1;
1498
+ continue;
1499
+ }
1500
+ if (status?.uploadedBytes === first) {
1501
+ return { done: false, uploaded: first, stopped: `TikTok did not answer the last chunk sent clearly (${reason}), and does not have it: the next call sends it again.` };
1502
+ }
1503
+ if (final) {
1504
+ throw new OutcomeUnknown(
1505
+ `TikTok did not answer the last chunk of the video clearly (${reason}), so it is not known whether the post was started. ${resumeHint(run.cursor(first))}`
1506
+ );
1507
+ }
1508
+ return {
1509
+ done: false,
1510
+ uploaded: first,
1511
+ stopped: `TikTok did not answer the last chunk sent clearly (${reason}), and could not say how far the upload got: the next call asks again before it sends anything.`
1512
+ };
1513
+ }
1514
+ } catch (error) {
1515
+ if (error instanceof ToolFailure || error instanceof OutcomeUnknown || !finalSent) throw error;
1516
+ throw new OutcomeUnknown(`The upload stopped unexpectedly after its last chunk was sent to TikTok, so it is not known whether the post was started. ${resumeHint(run.cursor(offset))}`);
1517
+ }
1518
+ }
1519
+
1520
+ // src/vendors/tiktok/index.ts
1521
+ var PRIVACY_LEVELS = ["PUBLIC_TO_EVERYONE", "MUTUAL_FOLLOW_FRIENDS", "FOLLOWER_OF_CREATOR", "SELF_ONLY"];
1522
+ var POLL_SECONDS = 5;
1523
+ var STATUS_BUDGET_MS = 35e3;
1524
+ var MAX_WAIT_SECONDS = 30;
1525
+ var DONE = /* @__PURE__ */ new Set(["PUBLISH_COMPLETE", "FAILED", "SEND_TO_USER_INBOX"]);
1526
+ var PUBLISH_ID2 = "^[A-Za-z0-9._~-]{1,64}$";
1527
+ var PUBLISH_PATTERN = new RegExp(PUBLISH_ID2);
1528
+ var HTTPS_URL = { type: "string", format: "uri", pattern: "^https://", maxLength: 2e3 };
1529
+ var JSON_TYPE = "application/json; charset=UTF-8";
1530
+ var READ_TOOLS = /* @__PURE__ */ new Set(["get_creator_info", "get_profile", "get_post_status", "list_videos", "get_videos", "api_get"]);
1531
+ var VIDEO_FIELDS = [
1532
+ "id",
1533
+ "title",
1534
+ "video_description",
1535
+ "create_time",
1536
+ "share_url",
1537
+ "duration",
1538
+ "height",
1539
+ "width",
1540
+ "cover_image_url",
1541
+ "embed_link",
1542
+ "embed_html",
1543
+ "view_count",
1544
+ "like_count",
1545
+ "comment_count",
1546
+ "share_count",
1547
+ "is_aigc"
1548
+ ];
1549
+ var DEFAULT_VIDEO_FIELDS = ["id", "title", "video_description", "create_time", "share_url", "duration", "view_count", "like_count", "comment_count", "share_count"];
1550
+ var DIRECT_ONLY_VIDEO = ["caption", "privacy_level", "disable_comment", "disable_duet", "disable_stitch", "cover_timestamp_ms", "brand_content_toggle", "brand_organic_toggle", "is_aigc"];
1551
+ var DIRECT_ONLY_PHOTO = ["privacy_level", "disable_comment", "auto_add_music", "brand_content_toggle", "brand_organic_toggle"];
1552
+ var FAIL_REASONS = {
1553
+ file_format_check_failed: "TikTok does not support the file format",
1554
+ duration_check_failed: "the video is too short or too long for this creator",
1555
+ frame_rate_check_failed: "the frame rate is not supported (23 to 60 FPS)",
1556
+ picture_size_check_failed: "the picture size is not supported",
1557
+ internal: "TikTok had an internal error",
1558
+ video_pull_failed: "TikTok could not download the video from the URL within an hour",
1559
+ photo_pull_failed: "TikTok could not download a photo from its URL within an hour",
1560
+ publish_cancelled: "the upload was cancelled",
1561
+ auth_removed: "the creator removed the app's access while it was processing",
1562
+ spam_risk_too_many_posts: "the creator posted too many times through the API in 24 hours",
1563
+ spam_risk_user_banned_from_posting: "the creator is banned from posting",
1564
+ spam_risk_text: "TikTok flagged the text as risky",
1565
+ spam_risk: "TikTok flagged the post as risky"
1566
+ };
1567
+ var REFUSAL_CAUSES = "an app TikTok has not audited may post only with privacy_level SELF_ONLY to a private account; the creator may have reached the daily post limit, be barred from posting, or not allow that privacy level; the app may have reached its cap of active creators; the inbox takes at most 5 pending drafts a day";
1568
+ var POST_REFUSED = `TikTok refused the post (${REFUSAL_CAUSES})`;
1569
+ var PULL_REFUSED = `TikTok refused the post (with PULL_FROM_URL, TikTok downloads the video itself, only from a domain or URL prefix verified in the TikTok app's URL properties: use a URL on such a host, or source FILE_UPLOAD, which needs no verification; other causes: ${REFUSAL_CAUSES})`;
1570
+ var PHOTO_REFUSED = `TikTok refused the photo post (TikTok downloads photos itself, only from a domain or URL prefix verified in the TikTok app's URL properties: use photo URLs on such a host, such as the creator's own website, or make a video of the photos and post it with post_video, whose FILE_UPLOAD needs no verification; other causes: ${REFUSAL_CAUSES})`;
1571
+ var GO_ON = "call post_video again with the same video_url and cursor set to nextCursor, until done is true. Each call sends the next chunks: no chunk goes twice, and the cursor belongs to this one post, so no second post is made. Go on soon: the upload must be finished by uploadExpiresAt, an hour after the post was started (TikTok's limit).";
1572
+ var INBOX_REFUSED = "TikTok refused the inbox upload: MEDIA_UPLOAD needs the video.upload permission, which this connection may not have (sign in to TikTok again with it, or use DIRECT_POST), or the token is no longer valid";
1573
+ var VIDEO_LIST_REFUSED = "TikTok refused to read videos: the connection needs the video.list permission, or its token is no longer valid";
1574
+ function compact(value) {
1575
+ return Object.fromEntries(Object.entries(value).filter(([, item]) => item !== void 0 && item !== null));
1576
+ }
1577
+ function jsonBody(value) {
1578
+ return { body: utf8Bytes(JSON.stringify(value)), contentType: JSON_TYPE };
1579
+ }
1580
+ async function tiktok(h, request) {
1581
+ const response = await h.api(request);
1582
+ const error = response.data?.error;
1583
+ if (error && typeof error.code === "string" && error.code !== "ok") {
1584
+ const message = cleanVendorText(error.message);
1585
+ throw new ToolFailure(
1586
+ `TikTok refused the request (${error.code})${message ? `: ${message.replace(/[.!?]+$/, "")}` : ""}.${READ_TOOLS.has(h.tool) ? "" : " Nothing was changed."}`,
1587
+ { status: response.status, vendorCode: error.code }
1588
+ );
1589
+ }
1590
+ return response.data?.data ?? {};
1591
+ }
1592
+ async function creatorInfo(h) {
1593
+ const data = await tiktok(h, {
1594
+ method: "POST",
1595
+ path: "/v2/post/publish/creator_info/query/",
1596
+ headers: { "content-type": JSON_TYPE },
1597
+ safe: true
1598
+ });
1599
+ return {
1600
+ username: typeof data?.creator_username === "string" ? data.creator_username : void 0,
1601
+ nickname: typeof data?.creator_nickname === "string" ? data.creator_nickname : void 0,
1602
+ avatarUrl: typeof data?.creator_avatar_url === "string" ? data.creator_avatar_url : void 0,
1603
+ privacyLevelOptions: Array.isArray(data?.privacy_level_options) ? data.privacy_level_options.map(String) : [],
1604
+ commentDisabled: data?.comment_disabled === true,
1605
+ duetDisabled: data?.duet_disabled === true,
1606
+ stitchDisabled: data?.stitch_disabled === true,
1607
+ maxVideoPostDurationSec: typeof data?.max_video_post_duration_sec === "number" ? data.max_video_post_duration_sec : void 0
1608
+ };
1609
+ }
1610
+ async function fetchStatus(h, publishId) {
1611
+ const data = await tiktok(h, {
1612
+ method: "POST",
1613
+ path: "/v2/post/publish/status/fetch/",
1614
+ ...jsonBody({ publish_id: publishId }),
1615
+ safe: true,
1616
+ errors: { 400: "TikTok knows no such publish_id for this account" }
1617
+ });
1618
+ const ids = Array.isArray(data?.publicaly_available_post_id ?? data?.publicly_available_post_id) ? data?.publicaly_available_post_id ?? data?.publicly_available_post_id : [];
1619
+ const exact = ids.filter((id) => typeof id === "string" && /^[0-9]{1,30}$/.test(id) || Number.isSafeInteger(id)).map(String);
1620
+ return compact({
1621
+ status: typeof data?.status === "string" ? data.status : "UNKNOWN",
1622
+ failReason: typeof data?.fail_reason === "string" && data.fail_reason ? data.fail_reason : void 0,
1623
+ postIds: exact.length ? exact : void 0,
1624
+ postIdsInexact: exact.length < ids.length ? true : void 0,
1625
+ uploadedBytes: typeof data?.uploaded_bytes === "number" ? data.uploaded_bytes : void 0,
1626
+ downloadedBytes: typeof data?.downloaded_bytes === "number" ? data.downloaded_bytes : void 0
1627
+ });
1628
+ }
1629
+ function pause(ms, signal) {
1630
+ return new Promise((resolve) => {
1631
+ if (signal?.aborted) {
1632
+ resolve(false);
1633
+ return;
1634
+ }
1635
+ const onAbort = () => {
1636
+ clearTimeout(timer);
1637
+ resolve(false);
1638
+ };
1639
+ const timer = setTimeout(() => {
1640
+ signal?.removeEventListener("abort", onAbort);
1641
+ resolve(true);
1642
+ }, ms);
1643
+ signal?.addEventListener("abort", onAbort, { once: true });
1644
+ });
1645
+ }
1646
+ function explainFailure(reason) {
1647
+ return reason && FAIL_REASONS[reason] || (reason ? `TikTok reported ${reason}` : "TikTok gave no reason");
1648
+ }
1649
+ async function follow(h, publishId, waitSeconds, deadline, known) {
1650
+ let status = known ?? await fetchStatus(h, publishId);
1651
+ let waited = 0;
1652
+ while (!DONE.has(status.status) && waited < waitSeconds) {
1653
+ const step = Math.min(POLL_SECONDS, waitSeconds - waited);
1654
+ if (Date.now() + step * 1e3 > deadline) return { status, stopped: "time" };
1655
+ if (!await pause(step * 1e3, h.ctx.signal)) return { status, stopped: "cancelled" };
1656
+ waited += step;
1657
+ status = await fetchStatus(h, publishId);
1658
+ }
1659
+ return { status };
1660
+ }
1661
+ async function finish(h, publishId, waitSeconds, deadline, extra, notes = [], known) {
1662
+ let status;
1663
+ let note;
1664
+ if (Date.now() >= deadline && !known) {
1665
+ note = "Sending it took most of the call, so its status was not read.";
1666
+ } else {
1667
+ try {
1668
+ const followed = await follow(h, publishId, waitSeconds, deadline, known);
1669
+ status = followed.status;
1670
+ if (followed.stopped === "cancelled") note = "Stopped waiting because the call was cancelled.";
1671
+ } catch (error) {
1672
+ if (!(error instanceof ToolFailure)) throw error;
1673
+ note = `The post was sent, but its status could not be read (${error.message.replace(/ Nothing was changed\.$/, "")}).`;
1674
+ }
1675
+ }
1676
+ if (status?.status === "FAILED") {
1677
+ throw new ToolFailure(`TikTok did not publish it: ${explainFailure(status.failReason)} (publish_id ${publishId}). Nothing was posted.`, status.failReason ? { vendorCode: status.failReason } : {});
1678
+ }
1679
+ const state = status?.status ?? "UNKNOWN";
1680
+ const all = [...notes, ...note ? [note] : []];
1681
+ if (status?.postIdsInexact) all.push("TikTok's post id is too long to pass on exactly; the post is on the creator's profile.");
1682
+ if (!status) {
1683
+ all.push(`Call get_post_status with publish_id ${publishId} to see whether TikTok published it; do not post it again.`);
1684
+ } else if (!DONE.has(state)) {
1685
+ all.push(`TikTok is still processing it, which often takes a minute or more. Call get_post_status with publish_id ${publishId} (it can wait up to ${MAX_WAIT_SECONDS} seconds) to follow it; do not post it again.`);
1686
+ }
1687
+ return compact({
1688
+ publishId,
1689
+ status: state,
1690
+ published: state === "PUBLISH_COMPLETE",
1691
+ sentToInbox: state === "SEND_TO_USER_INBOX" ? true : void 0,
1692
+ postIds: status?.postIds,
1693
+ ...extra,
1694
+ note: all.length ? all.join(" ") : void 0
1695
+ });
1696
+ }
1697
+ function withoutPublishId(error, inbox) {
1698
+ const where2 = inbox ? "among the drafts TikTok sends to the creator's inbox" : "on the creator's TikTok profile";
1699
+ return new OutcomeUnknown(
1700
+ `${error.message} TikTok sent back no publish_id, so get_post_status has nothing to look up: before posting again, look for the post ${where2} in the TikTok app, where it can take a few minutes to appear.`
1701
+ );
1702
+ }
1703
+ function refuseInboxSettings(args, names, what) {
1704
+ const given = names.filter((name2) => args[name2] !== void 0);
1705
+ if (!given.length) return;
1706
+ throw new ToolFailure(
1707
+ `TikTok's inbox upload (MEDIA_UPLOAD) takes no ${given.join(", ")}: the creator sets ${what} in the TikTok app when they post the draft. Leave them out, or use DIRECT_POST. Nothing was posted.`
1708
+ );
1709
+ }
1710
+ function videoTime(value) {
1711
+ const seconds = typeof value === "number" ? value : typeof value === "string" && /^[0-9]{1,12}$/.test(value) ? Number(value) : NaN;
1712
+ return Number.isFinite(seconds) && seconds > 0 ? new Date(seconds * 1e3).toISOString() : void 0;
1713
+ }
1714
+ function trimVideo(video, fields) {
1715
+ const out = {};
1716
+ for (const field of fields) {
1717
+ const value = video?.[field];
1718
+ if (value === void 0 || value === null || value === "") continue;
1719
+ if (field === "create_time") {
1720
+ out["createdAt"] = videoTime(value);
1721
+ continue;
1722
+ }
1723
+ const name2 = field.replace(/_([a-z0-9])/g, (_match, char) => char.toUpperCase());
1724
+ out[name2] = typeof value === "string" ? truncate(value, field === "embed_html" ? 2e3 : 1e3) : value;
1725
+ }
1726
+ return compact(out);
1727
+ }
1728
+ var VIDEO_FIELDS_SCHEMA = {
1729
+ type: "array",
1730
+ uniqueItems: true,
1731
+ minItems: 1,
1732
+ maxItems: VIDEO_FIELDS.length,
1733
+ items: { type: "string", enum: [...VIDEO_FIELDS] },
1734
+ description: `The fields to read (default ${DEFAULT_VIDEO_FIELDS.join(", ")}).`
1735
+ };
1736
+ function checkPostSettings(creator, privacy, brandContent) {
1737
+ if (!privacy) {
1738
+ throw new ToolFailure(
1739
+ `privacy_level is required for a direct post: choose one of ${creator.privacyLevelOptions.join(", ") || "the options get_creator_info lists"}. Nothing was posted.`
1740
+ );
1741
+ }
1742
+ if (creator.privacyLevelOptions.length && !creator.privacyLevelOptions.includes(privacy)) {
1743
+ throw new ToolFailure(`This creator cannot post with privacy_level ${privacy}: choose one of ${creator.privacyLevelOptions.join(", ")}. Nothing was posted.`);
1744
+ }
1745
+ if (brandContent && privacy === "SELF_ONLY") {
1746
+ throw new ToolFailure("Branded content (brand_content_toggle) cannot be private: choose another privacy_level. Nothing was posted.");
1747
+ }
1748
+ return privacy;
1749
+ }
1750
+ function checkedUploadUrl(value) {
1751
+ let target;
1752
+ try {
1753
+ target = new URL(String(value));
1754
+ } catch {
1755
+ throw new ToolFailure("TikTok returned no valid upload address. Nothing was posted.");
1756
+ }
1757
+ const address = uploadAddress(value);
1758
+ if (!address) {
1759
+ throw new ToolFailure(`TikTok asked for the video to be uploaded to ${target.host}, an address this connector does not send files to. Nothing was posted.`);
1760
+ }
1761
+ return address;
1762
+ }
1763
+ function pending(outcome, state, cursor, extra, notes) {
1764
+ const first = outcome.stopped ? `Deal with what stopped says first${outcome.retryAfter !== void 0 ? ` (wait ${outcome.retryAfter} seconds)` : ""}, then ` : "To go on, ";
1765
+ return compact({
1766
+ done: false,
1767
+ publishId: state.publishId,
1768
+ uploadedBytes: outcome.uploaded,
1769
+ totalBytes: state.total,
1770
+ stopped: outcome.stopped,
1771
+ retryAfter: outcome.retryAfter,
1772
+ uploadExpiresAt: new Date(state.startedAt + UPLOAD_LIFETIME_MS).toISOString(),
1773
+ nextCursor: cursor,
1774
+ next: `${first}${GO_ON}`,
1775
+ ...extra,
1776
+ note: notes.length ? notes.join(" ") : void 0
1777
+ });
1778
+ }
1779
+ async function sendVideo(h, run, waitSeconds, extra, notes) {
1780
+ const { state } = run;
1781
+ const cursorAt = (offset) => h.makeCursor(cursorState(state, offset));
1782
+ const outcome = await transfer(h, { ...run, cursor: cursorAt, readStatus: () => fetchStatus(h, state.publishId) });
1783
+ if (!outcome.done) return pending(outcome, state, cursorAt(outcome.uploaded), extra, notes);
1784
+ return finish(h, state.publishId, waitSeconds, run.started + STATUS_BUDGET_MS, { done: true, ...extra, bytes: state.total }, notes);
1785
+ }
1786
+ async function goOn(h, args, carried, started) {
1787
+ const parsed = stateFromCursor(carried);
1788
+ if (!parsed) throw new ToolFailure("The cursor holds no upload: pass nextCursor unchanged, or leave cursor out to start a new post. Nothing was changed.");
1789
+ if (args.source === "PULL_FROM_URL") {
1790
+ throw new ToolFailure("A cursor goes on with a FILE_UPLOAD: leave source out, or set it to FILE_UPLOAD, when you pass cursor. Nothing was changed.");
1791
+ }
1792
+ const { state } = parsed;
1793
+ if (state.source !== await sourceKey(args.video_url)) {
1794
+ throw new ToolFailure("The cursor belongs to a post of another video_url: give the video_url it started with, or leave cursor out to start a new post. Nothing was changed.");
1795
+ }
1796
+ const extra = { mode: state.inbox ? "MEDIA_UPLOAD" : "DIRECT_POST", source: "FILE_UPLOAD", account: h.credentials["tiktokusername"] };
1797
+ return exclusive(state.publishId, async () => {
1798
+ let status;
1799
+ try {
1800
+ status = await fetchStatus(h, state.publishId);
1801
+ } catch (error) {
1802
+ if (error instanceof ToolFailure) throw new ToolFailure(`${error.message} Go on later with the same cursor.`, error.details);
1803
+ throw error;
1804
+ }
1805
+ if (DONE.has(status.status) || status.uploadedBytes === state.total) {
1806
+ return finish(h, state.publishId, args.wait_seconds, started + STATUS_BUDGET_MS, { done: true, ...extra, bytes: state.total }, [], status);
1807
+ }
1808
+ const told = status.uploadedBytes;
1809
+ const plan = planFor(state.total, state.chunkSize);
1810
+ const offset = told !== void 0 && told > parsed.offset && chunkAt(plan, told) !== -1 ? told : parsed.offset;
1811
+ return sendVideo(h, { state, videoUrl: args.video_url, offset, started }, args.wait_seconds, extra, []);
1812
+ });
1813
+ }
1814
+ var PRIVACY_SCHEMA = {
1815
+ type: "string",
1816
+ enum: [...PRIVACY_LEVELS],
1817
+ description: "Who sees the post, required for a direct post: one of the privacy_level_options get_creator_info returns (an app TikTok has not audited may only use SELF_ONLY)."
1818
+ };
1819
+ var MODE_SCHEMA = {
1820
+ type: "string",
1821
+ enum: ["DIRECT_POST", "MEDIA_UPLOAD"],
1822
+ default: "DIRECT_POST",
1823
+ description: "DIRECT_POST (default) publishes it; MEDIA_UPLOAD sends it to the creator's TikTok inbox as a draft that the creator finishes and posts in the app, with their own caption and settings (needs the video.upload permission, which a connection may not have)."
1824
+ };
1825
+ var WAIT_SCHEMA = {
1826
+ type: "integer",
1827
+ minimum: 0,
1828
+ maximum: MAX_WAIT_SECONDS,
1829
+ default: 20,
1830
+ description: `Seconds to wait for TikTok to finish, checking every 5 seconds (default 20, at most ${MAX_WAIT_SECONDS}, 0 to return at once); the wait also ends 35 seconds into the call. TikTok often takes a minute or more: if it is still processing, follow it with get_post_status and the publish_id. The post goes on either way.`
1831
+ };
1832
+ var connector = defineConnector({
1833
+ vendor: "tiktok",
1834
+ label: "TikTok",
1835
+ origins: ["https://open.tiktokapis.com", ...UPLOAD_ORIGINS],
1836
+ credentials: ["access_token", "tiktokusername", "openid"],
1837
+ requiredCredentials: [["access_token"]],
1838
+ credentialLabels: {
1839
+ access_token: "TikTok access token",
1840
+ tiktokusername: "TikTok account name",
1841
+ openid: "TikTok open ID"
1842
+ },
1843
+ authHeaders: (credentials) => ({ authorization: `Bearer ${credentials["access_token"]}` }),
1844
+ tools: [
1845
+ {
1846
+ name: "get_creator_info",
1847
+ kind: "read",
1848
+ title: "Get the TikTok creator's posting options",
1849
+ description: "Returns what the connected creator can post right now: their name, the privacy levels they may choose, whether comments, duets and stitches are turned off on their account, and the longest video they may post. TikTok asks for this before every post; post_video and post_photos check it themselves.",
1850
+ inputSchema: { type: "object", properties: {}, additionalProperties: false },
1851
+ async run(_args, h) {
1852
+ const creator = await creatorInfo(h);
1853
+ return compact({ ...creator, account: creator.username ?? h.credentials["tiktokusername"] });
1854
+ }
1855
+ },
1856
+ {
1857
+ name: "get_profile",
1858
+ kind: "read",
1859
+ title: "Get the TikTok profile",
1860
+ description: "Returns the connected TikTok account: open id, union id, display name and avatar. Profile and stats fields (bio, follower and video counts) need the user.info.profile and user.info.stats permissions.",
1861
+ inputSchema: {
1862
+ type: "object",
1863
+ properties: {
1864
+ fields: {
1865
+ type: "array",
1866
+ uniqueItems: true,
1867
+ maxItems: 14,
1868
+ items: {
1869
+ type: "string",
1870
+ enum: ["open_id", "union_id", "avatar_url", "display_name", "username", "bio_description", "profile_deep_link", "is_verified", "follower_count", "following_count", "likes_count", "video_count", "avatar_url_100", "avatar_large_url"]
1871
+ },
1872
+ description: "The fields to read (default open_id, union_id, avatar_url, display_name)."
1873
+ }
1874
+ },
1875
+ additionalProperties: false
1876
+ },
1877
+ async run(args, h) {
1878
+ const fields = args.fields?.length ? args.fields : ["open_id", "union_id", "avatar_url", "display_name"];
1879
+ const data = await tiktok(h, { path: "/v2/user/info/", query: { fields: fields.join(",") } });
1880
+ const user = data?.user && typeof data.user === "object" ? data.user : {};
1881
+ const camel = (name2) => name2.replace(/_([a-z0-9])/g, (_match, char) => char.toUpperCase());
1882
+ const profile = {};
1883
+ for (const field of fields) if (user[field] !== void 0 && user[field] !== null && user[field] !== "") profile[camel(field)] = user[field];
1884
+ if (profile["openId"] === void 0 && h.credentials["openid"]) profile["openId"] = h.credentials["openid"];
1885
+ if (profile["displayName"] === void 0 && h.credentials["tiktokusername"]) profile["displayName"] = h.credentials["tiktokusername"];
1886
+ return profile;
1887
+ }
1888
+ },
1889
+ {
1890
+ name: "post_video",
1891
+ kind: "create",
1892
+ check: "get_post_status",
1893
+ title: "Post a video to TikTok",
1894
+ description: "Posts one video (MP4, MOV or WebM, up to 4 GB) to the connected TikTok account from a public https URL. FILE_UPLOAD (default) sends it to TikTok in 10 MB chunks, each read from the URL by byte range just before it goes, for about 35 seconds a call: while done is false, call again with the same video_url and cursor set to nextCursor, until done is true, within an hour of the first call. A host that does not pass byte ranges on gets the whole file, which must then fit its download limit. PULL_FROM_URL lets TikTok download it itself, only from a domain or URL prefix verified in the TikTok app's URL properties. Checks the creator's posting options first, then waits a little for TikTok to finish and returns the publish_id to follow with get_post_status. Caption up to 2,200 characters with #hashtags and @mentions (links are not clickable). One video per post: join clips beforehand.",
1895
+ inputSchema: {
1896
+ type: "object",
1897
+ properties: {
1898
+ video_url: { ...HTTPS_URL, description: "A public https URL of the video (MP4 recommended, H.264, 23 to 60 FPS)." },
1899
+ source: {
1900
+ type: "string",
1901
+ enum: ["FILE_UPLOAD", "PULL_FROM_URL"],
1902
+ default: "FILE_UPLOAD",
1903
+ description: "FILE_UPLOAD (default; sent in chunks, across calls with cursor when one call is not enough) or PULL_FROM_URL (only from a domain or URL prefix verified for the TikTok app)."
1904
+ },
1905
+ post_mode: MODE_SCHEMA,
1906
+ caption: { type: "string", maxLength: 2200, description: "The caption, up to 2,200 characters, with hashtags and mentions (DIRECT_POST only)." },
1907
+ privacy_level: PRIVACY_SCHEMA,
1908
+ disable_comment: { type: "boolean", description: "true turns comments off for this video." },
1909
+ disable_duet: { type: "boolean", description: "true turns duets off for this video." },
1910
+ disable_stitch: { type: "boolean", description: "true turns stitches off for this video." },
1911
+ cover_timestamp_ms: { type: "integer", minimum: 0, description: "The frame used as the cover, in milliseconds from the start (default the first frame)." },
1912
+ brand_content_toggle: { type: "boolean", description: "true when the video is a paid partnership promoting a third-party business." },
1913
+ brand_organic_toggle: { type: "boolean", description: "true when the video promotes the creator's own business." },
1914
+ is_aigc: { type: "boolean", description: "true labels the video as AI-generated." },
1915
+ wait_seconds: WAIT_SCHEMA,
1916
+ cursor: {
1917
+ type: "string",
1918
+ maxLength: 4096,
1919
+ description: "nextCursor from the previous result, while done is false: goes on with that FILE_UPLOAD where TikTok stopped. Give the same video_url with it (the caption and settings were sent when the post started and are not sent again). Leave out to start a post."
1920
+ }
1921
+ },
1922
+ required: ["video_url"],
1923
+ additionalProperties: false
1924
+ },
1925
+ async run(args, h) {
1926
+ const started = Date.now();
1927
+ const deadline = started + STATUS_BUDGET_MS;
1928
+ const carried = h.cursor(args.cursor);
1929
+ if (carried) return goOn(h, args, carried, started);
1930
+ const direct = args.post_mode === "DIRECT_POST";
1931
+ if (!direct) refuseInboxSettings(args, DIRECT_ONLY_VIDEO, "the caption and every post setting");
1932
+ let creator;
1933
+ let privacy;
1934
+ const turnedOff = [];
1935
+ if (direct) {
1936
+ creator = await creatorInfo(h);
1937
+ privacy = checkPostSettings(creator, args.privacy_level, args.brand_content_toggle);
1938
+ if (creator.commentDisabled && args.disable_comment === false) turnedOff.push("comments");
1939
+ if (creator.duetDisabled && args.disable_duet === false) turnedOff.push("duets");
1940
+ if (creator.stitchDisabled && args.disable_stitch === false) turnedOff.push("stitches");
1941
+ }
1942
+ const notes = turnedOff.length ? [`The creator has ${turnedOff.join(", ")} turned off for every post, so they stay off.`] : [];
1943
+ const extra = { mode: args.post_mode, source: args.source, account: creator?.username ?? h.credentials["tiktokusername"], privacyLevel: privacy };
1944
+ const postInfo = direct ? compact({
1945
+ title: args.caption,
1946
+ privacy_level: privacy,
1947
+ disable_comment: creator?.commentDisabled ? true : args.disable_comment,
1948
+ disable_duet: creator?.duetDisabled ? true : args.disable_duet,
1949
+ disable_stitch: creator?.stitchDisabled ? true : args.disable_stitch,
1950
+ video_cover_timestamp_ms: args.cover_timestamp_ms,
1951
+ brand_content_toggle: args.brand_content_toggle,
1952
+ brand_organic_toggle: args.brand_organic_toggle,
1953
+ is_aigc: args.is_aigc
1954
+ }) : void 0;
1955
+ const init = (sourceInfo, refused, write) => tiktok(h, {
1956
+ method: "POST",
1957
+ path: direct ? "/v2/post/publish/video/init/" : "/v2/post/publish/inbox/video/init/",
1958
+ ...jsonBody(postInfo ? { post_info: postInfo, source_info: sourceInfo } : { source_info: sourceInfo }),
1959
+ write,
1960
+ errors: direct ? { 403: refused } : { 401: INBOX_REFUSED, 403: refused }
1961
+ });
1962
+ if (args.source === "PULL_FROM_URL") {
1963
+ let data2;
1964
+ try {
1965
+ data2 = await init({ source: "PULL_FROM_URL", video_url: args.video_url }, PULL_REFUSED, true);
1966
+ } catch (error) {
1967
+ if (error instanceof OutcomeUnknown) throw withoutPublishId(error, !direct);
1968
+ throw error;
1969
+ }
1970
+ const publishId2 = typeof data2?.publish_id === "string" ? data2.publish_id : void 0;
1971
+ if (!publishId2) throw new ToolFailure("TikTok accepted the request but sent back no publish_id. Check the TikTok app before posting again.");
1972
+ return finish(h, publishId2, args.wait_seconds, deadline, { done: true, ...extra }, notes);
1973
+ }
1974
+ const readStarted = Date.now();
1975
+ let first;
1976
+ try {
1977
+ first = await readPart(h, args.video_url, 0, CHUNK_BYTES - 1);
1978
+ } catch (error) {
1979
+ if (error instanceof SourceProblem) throw new ToolFailure(`${error.message} Nothing was posted.`);
1980
+ throw error;
1981
+ }
1982
+ const type = sniffVideo(first.bytes);
1983
+ if (!type) throw new ToolFailure("The video URL did not return an MP4, MOV or WebM video. Nothing was posted.");
1984
+ if (first.total > MAX_VIDEO_BYTES) {
1985
+ throw new ToolFailure(`The video is ${formatNumber(first.total)} bytes; TikTok takes files up to 4 GB (${formatNumber(MAX_VIDEO_BYTES)} bytes). Nothing was posted.`);
1986
+ }
1987
+ const plan = chunkPlan(first.total);
1988
+ const data = await init({ source: "FILE_UPLOAD", video_size: first.total, chunk_size: plan.chunkSize, total_chunk_count: plan.count }, POST_REFUSED, false);
1989
+ const publishId = typeof data?.publish_id === "string" && PUBLISH_PATTERN.test(data.publish_id) ? data.publish_id : void 0;
1990
+ if (!publishId) throw new ToolFailure("TikTok sent back no usable publish_id. Nothing was posted.");
1991
+ const state = {
1992
+ uploadUrl: checkedUploadUrl(data?.upload_url),
1993
+ publishId,
1994
+ total: first.total,
1995
+ chunkSize: plan.chunkSize,
1996
+ type,
1997
+ source: await sourceKey(args.video_url),
1998
+ ...first.etag ? { etag: first.etag } : {},
1999
+ inbox: !direct,
2000
+ startedAt: Date.now()
2001
+ };
2002
+ return exclusive(publishId, () => sendVideo(h, { state, videoUrl: args.video_url, offset: 0, started, held: first, heldSince: readStarted }, args.wait_seconds, extra, notes));
2003
+ }
2004
+ },
2005
+ {
2006
+ name: "post_photos",
2007
+ kind: "create",
2008
+ check: "get_post_status",
2009
+ title: "Post photos to TikTok",
2010
+ description: "Posts a photo post (a carousel of 1 to 35 photos) to the connected TikTok account. TikTok has no upload for photos: it downloads them itself, only from a domain or URL prefix verified in the TikTok app's URL properties, and refuses photo URLs on any other host. Use photo URLs on such a host, such as the creator's own website; without one, make a video of the photos and post it with post_video, whose FILE_UPLOAD needs no verification. JPEG or WebP, up to 1080p and 20 MB each. Title up to 90 characters, description up to 4,000 with #hashtags (links are not clickable). Checks the creator's posting options first, then waits a little for TikTok to finish and returns the publish_id to follow with get_post_status.",
2011
+ inputSchema: {
2012
+ type: "object",
2013
+ properties: {
2014
+ image_urls: {
2015
+ type: "array",
2016
+ minItems: 1,
2017
+ maxItems: 35,
2018
+ items: HTTPS_URL,
2019
+ description: "Public https URLs of the photos, in order, on a domain or URL prefix verified for the TikTok app."
2020
+ },
2021
+ post_mode: MODE_SCHEMA,
2022
+ title: { type: "string", maxLength: 90, description: "A short title, up to 90 characters." },
2023
+ description: { type: "string", maxLength: 4e3, description: "The post text, up to 4,000 characters, with hashtags." },
2024
+ privacy_level: PRIVACY_SCHEMA,
2025
+ cover_index: { type: "integer", minimum: 0, maximum: 34, default: 0, description: "The photo used as the cover, counted from 0 (default the first)." },
2026
+ disable_comment: { type: "boolean", description: "true turns comments off for this post (DIRECT_POST only)." },
2027
+ auto_add_music: { type: "boolean", description: "Let TikTok add music (DIRECT_POST only; default true)." },
2028
+ brand_content_toggle: { type: "boolean", description: "true when the post is a paid partnership promoting a third-party business (DIRECT_POST only)." },
2029
+ brand_organic_toggle: { type: "boolean", description: "true when the post promotes the creator's own business (DIRECT_POST only)." },
2030
+ is_aigc: { type: "boolean", description: "true labels the post as AI-generated." },
2031
+ wait_seconds: WAIT_SCHEMA
2032
+ },
2033
+ required: ["image_urls"],
2034
+ additionalProperties: false
2035
+ },
2036
+ async run(args, h) {
2037
+ if (args.cover_index >= args.image_urls.length) {
2038
+ throw new ToolFailure(`cover_index ${args.cover_index} points past the last photo (there are ${args.image_urls.length}). Nothing was posted.`);
2039
+ }
2040
+ const deadline = Date.now() + STATUS_BUDGET_MS;
2041
+ const direct = args.post_mode === "DIRECT_POST";
2042
+ if (!direct) refuseInboxSettings(args, DIRECT_ONLY_PHOTO, "privacy, comments, music and the branded-content labels");
2043
+ let creator;
2044
+ let privacy;
2045
+ if (direct) {
2046
+ creator = await creatorInfo(h);
2047
+ privacy = checkPostSettings(creator, args.privacy_level, args.brand_content_toggle);
2048
+ }
2049
+ let data;
2050
+ try {
2051
+ data = await tiktok(h, {
2052
+ method: "POST",
2053
+ path: "/v2/post/publish/content/init/",
2054
+ ...jsonBody(compact({
2055
+ media_type: "PHOTO",
2056
+ post_mode: args.post_mode,
2057
+ post_info: compact({
2058
+ title: args.title,
2059
+ description: args.description,
2060
+ privacy_level: privacy,
2061
+ disable_comment: direct ? creator?.commentDisabled ? true : args.disable_comment : void 0,
2062
+ auto_add_music: direct ? args.auto_add_music ?? true : void 0,
2063
+ brand_content_toggle: direct ? args.brand_content_toggle : void 0,
2064
+ brand_organic_toggle: direct ? args.brand_organic_toggle : void 0
2065
+ }),
2066
+ source_info: { source: "PULL_FROM_URL", photo_cover_index: args.cover_index, photo_images: args.image_urls },
2067
+ is_aigc: args.is_aigc
2068
+ })),
2069
+ write: true,
2070
+ errors: direct ? { 403: PHOTO_REFUSED } : { 401: INBOX_REFUSED, 403: PHOTO_REFUSED }
2071
+ });
2072
+ } catch (error) {
2073
+ if (error instanceof OutcomeUnknown) throw withoutPublishId(error, !direct);
2074
+ throw error;
2075
+ }
2076
+ const publishId = typeof data?.publish_id === "string" ? data.publish_id : void 0;
2077
+ if (!publishId) throw new ToolFailure("TikTok accepted the request but sent back no publish_id. Check the TikTok app before posting again.");
2078
+ return finish(h, publishId, args.wait_seconds, deadline, {
2079
+ mode: args.post_mode,
2080
+ photos: args.image_urls.length,
2081
+ account: creator?.username ?? h.credentials["tiktokusername"],
2082
+ privacyLevel: privacy
2083
+ });
2084
+ }
2085
+ },
2086
+ {
2087
+ name: "get_post_status",
2088
+ kind: "read",
2089
+ title: "Get a TikTok post's status",
2090
+ description: `Returns where a TikTok post stands by its publish_id: PROCESSING_UPLOAD, PROCESSING_DOWNLOAD, SEND_TO_USER_INBOX, PUBLISH_COMPLETE or FAILED (with the reason), and the public post ids once it is public and moderated. With wait_seconds it checks every 5 seconds until TikTok is done or the time is up (at most ${MAX_WAIT_SECONDS} seconds).`,
2091
+ inputSchema: {
2092
+ type: "object",
2093
+ properties: {
2094
+ publish_id: { type: "string", pattern: PUBLISH_ID2, description: "The publish_id post_video or post_photos returned." },
2095
+ wait_seconds: {
2096
+ type: "integer",
2097
+ minimum: 0,
2098
+ maximum: MAX_WAIT_SECONDS,
2099
+ default: 0,
2100
+ description: `Seconds to wait for TikTok to finish, checking every 5 seconds (default 0: one read; at most ${MAX_WAIT_SECONDS}).`
2101
+ }
2102
+ },
2103
+ required: ["publish_id"],
2104
+ additionalProperties: false
2105
+ },
2106
+ async run(args, h) {
2107
+ const { status, stopped } = await follow(h, args.publish_id, args.wait_seconds, Date.now() + STATUS_BUDGET_MS);
2108
+ const notes = [];
2109
+ if (status.postIdsInexact) notes.push("TikTok's post id is too long to pass on exactly; the post is on the creator's profile.");
2110
+ if (stopped === "cancelled") notes.push("Stopped waiting because the call was cancelled.");
2111
+ if (!DONE.has(status.status) && status.status !== "UNKNOWN") notes.push("TikTok is still processing it: check again in a little while; do not post it again.");
2112
+ return compact({
2113
+ publishId: args.publish_id,
2114
+ ...status,
2115
+ note: notes.length ? notes.join(" ") : void 0,
2116
+ failReasonText: status.status === "FAILED" ? explainFailure(status.failReason) : void 0,
2117
+ published: status.status === "PUBLISH_COMPLETE"
2118
+ });
2119
+ }
2120
+ },
2121
+ {
2122
+ name: "list_videos",
2123
+ kind: "read",
2124
+ title: "List the TikTok creator's videos",
2125
+ description: "Lists the connected creator's public TikTok videos, newest first: id, title, description, time, link, length, and view, like, comment and share counts (choose others with fields). Private posts are not listed. Needs the video.list permission. Pass nextCursor back as cursor for older ones.",
2126
+ inputSchema: {
2127
+ type: "object",
2128
+ properties: {
2129
+ fields: VIDEO_FIELDS_SCHEMA,
2130
+ max_count: { type: "integer", minimum: 1, maximum: 20, default: 10, description: "Videos per page, 1 to 20 (default 10)." },
2131
+ cursor: { type: "string", description: "nextCursor from the previous result." }
2132
+ },
2133
+ additionalProperties: false
2134
+ },
2135
+ async run(args, h) {
2136
+ const state = h.cursor(args.cursor);
2137
+ const before = typeof state?.["c"] === "number" ? state["c"] : void 0;
2138
+ const skip = typeof state?.["o"] === "number" ? state["o"] : 0;
2139
+ const max = typeof state?.["n"] === "number" ? state["n"] : args.max_count;
2140
+ const fields = typeof state?.["f"] === "string" ? state["f"].split(",") : [.../* @__PURE__ */ new Set(["id", ...args.fields?.length ? args.fields : DEFAULT_VIDEO_FIELDS])];
2141
+ const data = await tiktok(h, {
2142
+ method: "POST",
2143
+ path: "/v2/video/list/",
2144
+ query: { fields: fields.join(",") },
2145
+ ...jsonBody(compact({ max_count: max, cursor: before })),
2146
+ safe: true,
2147
+ errors: { 401: VIDEO_LIST_REFUSED }
2148
+ });
2149
+ const videos = Array.isArray(data?.videos) ? data.videos : [];
2150
+ const cursor = typeof data?.cursor === "number" ? data.cursor : typeof data?.cursor === "string" && /^[0-9]{1,15}$/.test(data.cursor) ? Number(data.cursor) : void 0;
2151
+ const next = data?.has_more === true && cursor !== void 0 && cursor !== before ? cursor : void 0;
2152
+ const f = fields.join(",");
2153
+ return h.page({
2154
+ key: "videos",
2155
+ items: videos.map((video) => trimVideo(video, fields)).slice(skip),
2156
+ resumeAt: (index) => h.makeCursor({ ...before !== void 0 ? { c: before } : {}, o: skip + index, n: max, f }),
2157
+ ...next !== void 0 ? { nextPage: h.makeCursor({ c: next, o: 0, n: max, f }) } : {}
2158
+ });
2159
+ }
2160
+ },
2161
+ {
2162
+ name: "get_videos",
2163
+ kind: "read",
2164
+ title: "Get TikTok videos by id",
2165
+ description: "Returns up to 20 of the connected creator's videos by their ids, such as the post ids get_post_status returns: title, description, time, link, length, and view, like, comment and share counts (choose others with fields). Ids that are not the creator's come back as missing. Needs the video.list permission.",
2166
+ inputSchema: {
2167
+ type: "object",
2168
+ properties: {
2169
+ video_ids: { type: "array", minItems: 1, maxItems: 20, uniqueItems: true, items: { type: "string", pattern: "^[0-9]{1,30}$" }, description: "The video ids." },
2170
+ fields: VIDEO_FIELDS_SCHEMA
2171
+ },
2172
+ required: ["video_ids"],
2173
+ additionalProperties: false
2174
+ },
2175
+ async run(args, h) {
2176
+ const fields = [.../* @__PURE__ */ new Set(["id", ...args.fields?.length ? args.fields : DEFAULT_VIDEO_FIELDS])];
2177
+ const data = await tiktok(h, {
2178
+ method: "POST",
2179
+ path: "/v2/video/query/",
2180
+ query: { fields: fields.join(",") },
2181
+ ...jsonBody({ filters: { video_ids: args.video_ids } }),
2182
+ safe: true,
2183
+ errors: { 401: VIDEO_LIST_REFUSED }
2184
+ });
2185
+ const videos = Array.isArray(data?.videos) ? data.videos : [];
2186
+ const found = new Set(videos.map((video) => String(video?.id)));
2187
+ const missing = args.video_ids.filter((id) => !found.has(id));
2188
+ return compact({ videos: videos.map((video) => trimVideo(video, fields)), missing: missing.length ? missing : void 0 });
2189
+ }
2190
+ },
2191
+ ...apiTools({
2192
+ label: "TikTok",
2193
+ description: "The TikTok API v2 at https://open.tiktokapis.com/v2/, with the connection's token: paths start with /v2/, such as /v2/user/info/ (GET, with fields in query). api_request sends POST requests, which TikTok uses for its writes; the reads TikTok takes by POST have their own tools (get_creator_info, get_post_status, list_videos, get_videos). Reference: https://developers.tiktok.com/doc/overview.",
2194
+ basePath: "/v2/",
2195
+ methods: ["POST"]
2196
+ })
2197
+ ]
2198
+ });
2199
+ module.exports = connector;