@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.
- package/CHANGELOG.md +29 -0
- package/README.md +1131 -34
- package/dist/cli.js +15 -12
- package/dist/core/credentials.d.ts +21 -0
- package/dist/core/credentials.js +45 -0
- package/dist/core/origins.d.ts +18 -0
- package/dist/core/origins.js +40 -0
- package/dist/core/upload-hosts.d.ts +15 -0
- package/dist/core/upload-hosts.js +43 -0
- package/dist/host/describe.d.ts +10 -0
- package/dist/host/describe.js +38 -0
- package/dist/host/env.d.ts +25 -2
- package/dist/host/env.js +24 -7
- package/dist/host/guarded-fetch.d.ts +36 -9
- package/dist/host/guarded-fetch.js +175 -52
- package/dist/host/index.d.ts +8 -5
- package/dist/host/index.js +12 -1
- package/dist/host/load.js +31 -1
- package/dist/host/server.d.ts +13 -2
- package/dist/host/server.js +15 -2
- package/dist/types.d.ts +96 -5
- package/dist/vendors/adapty.js +1303 -0
- package/dist/vendors/adjust.js +1372 -0
- package/dist/vendors/apollo.js +2499 -0
- package/dist/vendors/apple-appstore.js +2798 -0
- package/dist/vendors/beehiiv.js +1965 -0
- package/dist/vendors/blogger.js +1687 -0
- package/dist/vendors/bluesky.js +850 -127
- package/dist/vendors/brevo.js +2195 -0
- package/dist/vendors/calendarific.js +1116 -0
- package/dist/vendors/devto.js +685 -92
- package/dist/vendors/facebook-pages.js +2185 -0
- package/dist/vendors/firebase.js +1333 -0
- package/dist/vendors/ga4.js +1585 -0
- package/dist/vendors/gmail.js +1962 -0
- package/dist/vendors/google-ads.js +2201 -0
- package/dist/vendors/google-business.js +1621 -0
- package/dist/vendors/google-calendar.js +1936 -0
- package/dist/vendors/google-drive.js +2654 -0
- package/dist/vendors/google-merchant-center.js +1742 -0
- package/dist/vendors/google-play.js +1856 -0
- package/dist/vendors/google-search-console.js +1572 -0
- package/dist/vendors/hashnode.js +1722 -0
- package/dist/vendors/instagram.js +2249 -0
- package/dist/vendors/kaggle.js +2043 -0
- package/dist/vendors/keepa.js +2087 -0
- package/dist/vendors/linkedin.js +1588 -0
- package/dist/vendors/mailchimp.js +2402 -0
- package/dist/vendors/mastodon.js +1836 -0
- package/dist/vendors/meta-ads.js +2375 -0
- package/dist/vendors/notion.js +1950 -0
- package/dist/vendors/pinterest.js +1744 -0
- package/dist/vendors/qiita.js +1552 -0
- package/dist/vendors/reddit.js +1791 -0
- package/dist/vendors/revenuecat.js +1593 -0
- package/dist/vendors/roasit.js +1460 -0
- package/dist/vendors/sendgrid.js +2188 -0
- package/dist/vendors/serper.js +901 -179
- package/dist/vendors/shopify.js +2511 -0
- package/dist/vendors/threads.js +1869 -0
- package/dist/vendors/tiktok.js +2199 -0
- package/dist/vendors/tumblr.js +1793 -0
- package/dist/vendors/twitter.js +1650 -0
- package/dist/vendors/woocommerce.js +2258 -0
- package/dist/vendors/wordpress.js +1904 -0
- package/dist/vendors/youtube.js +2542 -0
- package/package.json +1 -1
|
@@ -0,0 +1,2542 @@
|
|
|
1
|
+
/* youtube connector module (MIT License). Built from src/vendors/youtube; 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(text2) {
|
|
41
|
+
return encoder.encode(text2);
|
|
42
|
+
}
|
|
43
|
+
function utf8Length(text2) {
|
|
44
|
+
return encoder.encode(text2).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(text2) {
|
|
60
|
+
if (!/^[A-Za-z0-9_-]*$/.test(text2)) throw new Error("not base64url");
|
|
61
|
+
const padded = text2.replace(/-/g, "+").replace(/_/g, "/") + "===".slice((text2.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(text2) {
|
|
68
|
+
const digest = new Uint8Array(await crypto.subtle.digest("SHA-256", utf8Bytes(text2)));
|
|
69
|
+
return Array.from(digest, (byte) => byte.toString(16).padStart(2, "0")).join("");
|
|
70
|
+
}
|
|
71
|
+
function truncate(text2, max) {
|
|
72
|
+
if (text2.length <= max) return text2;
|
|
73
|
+
const points = Array.from(text2);
|
|
74
|
+
if (points.length <= max) return text2;
|
|
75
|
+
return `${points.slice(0, Math.max(0, max - 1)).join("")}\u2026`;
|
|
76
|
+
}
|
|
77
|
+
function cleanVendorText(text2, max = 300) {
|
|
78
|
+
if (typeof text2 !== "string") return void 0;
|
|
79
|
+
if (/^\s*</.test(text2)) return void 0;
|
|
80
|
+
const line = text2.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 = (count2) => {
|
|
112
|
+
const cut = count2 < input.items.length;
|
|
113
|
+
const result2 = { ...input.extra, [input.key]: input.items.slice(0, count2) };
|
|
114
|
+
const next = cut ? input.resumeAt(count2) : 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 text2 = typeof reply["data"] === "string" ? reply["data"] : JSON.stringify(reply["data"]) ?? "";
|
|
173
|
+
const points = Array.from(text2.length > MAX_CUT_POINTS ? text2.slice(0, MAX_CUT_POINTS) : text2);
|
|
174
|
+
if (/^[\ud800-\udbff]$/.test(points[points.length - 1] ?? "")) points.pop();
|
|
175
|
+
const cut = (count2) => ({
|
|
176
|
+
status: reply["status"],
|
|
177
|
+
...reply["headers"] ? { headers: reply["headers"] } : {},
|
|
178
|
+
truncated: true,
|
|
179
|
+
note: `The reply has ${formatNumber(utf8Length(text2))} 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, count2).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 text2 = utf8Decode(bytes);
|
|
473
|
+
if (/json/i.test(contentType ?? "") || /^\s*[[{]/.test(text2)) {
|
|
474
|
+
try {
|
|
475
|
+
return JSON.parse(text2);
|
|
476
|
+
} catch {
|
|
477
|
+
}
|
|
478
|
+
}
|
|
479
|
+
return text2;
|
|
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 said = 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}${said}, so it is not known whether the change was made.`);
|
|
496
|
+
}
|
|
497
|
+
return new ToolFailure(withCustom(`${label} had a server error (HTTP ${status})${said}. 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)${said}. ${checkCredentials}${nothingChanged}`),
|
|
508
|
+
{ status, ...extra }
|
|
509
|
+
);
|
|
510
|
+
}
|
|
511
|
+
if (status === 403) return new ToolFailure(withCustom(`${label} refused the request (HTTP 403)${said}.${nothingChanged}`), { status, ...extra });
|
|
512
|
+
if (status === 404) return new ToolFailure(withCustom(`${label} found nothing there (HTTP 404)${said}.${nothingChanged}`), { status, ...extra });
|
|
513
|
+
if (status >= 400) return new ToolFailure(withCustom(`${label} rejected the request (HTTP ${status})${said}.${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 text2 = typeof value === "string" ? value.trim() : "";
|
|
624
|
+
if (!text2) return { ok: false, problem: "is empty" };
|
|
625
|
+
let url;
|
|
626
|
+
try {
|
|
627
|
+
url = new URL(text2.includes("://") ? text2 : `https://${text2}`);
|
|
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 text2 = String(value).trim();
|
|
951
|
+
if (text2) out[key] = text2;
|
|
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 = (text2) => {
|
|
981
|
+
try {
|
|
982
|
+
ctx.log?.(text2);
|
|
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/youtube/google.ts
|
|
1095
|
+
function plain(text2) {
|
|
1096
|
+
return text2.replace(/<\/?[A-Za-z][^<>]{0,300}>/g, "");
|
|
1097
|
+
}
|
|
1098
|
+
async function googleApi(h, request) {
|
|
1099
|
+
try {
|
|
1100
|
+
return await h.api(request);
|
|
1101
|
+
} catch (error) {
|
|
1102
|
+
if (error instanceof ToolFailure) {
|
|
1103
|
+
const message = plain(error.message);
|
|
1104
|
+
throw message === error.message ? error : new ToolFailure(message, error.details);
|
|
1105
|
+
}
|
|
1106
|
+
if (error instanceof OutcomeUnknown) {
|
|
1107
|
+
const message = plain(error.message);
|
|
1108
|
+
throw message === error.message ? error : new OutcomeUnknown(message);
|
|
1109
|
+
}
|
|
1110
|
+
throw error;
|
|
1111
|
+
}
|
|
1112
|
+
}
|
|
1113
|
+
function compact(value) {
|
|
1114
|
+
return Object.fromEntries(Object.entries(value).filter(([, item]) => item !== void 0 && item !== null && item !== ""));
|
|
1115
|
+
}
|
|
1116
|
+
function count(value) {
|
|
1117
|
+
const number = typeof value === "string" && value.trim() ? Number(value) : value;
|
|
1118
|
+
return typeof number === "number" && Number.isFinite(number) ? number : void 0;
|
|
1119
|
+
}
|
|
1120
|
+
function cursorNumber(state, key, fallback, min, max) {
|
|
1121
|
+
const value = state?.[key];
|
|
1122
|
+
return typeof value === "number" && Number.isInteger(value) && value >= min && value <= max ? value : fallback;
|
|
1123
|
+
}
|
|
1124
|
+
function utcTime(value, name2) {
|
|
1125
|
+
const time = Date.parse(value);
|
|
1126
|
+
if (!Number.isFinite(time)) {
|
|
1127
|
+
throw new ToolFailure(`${name2} is not a valid time: give one like 2026-12-01T09:00:00Z. Nothing was sent.`);
|
|
1128
|
+
}
|
|
1129
|
+
return new Date(time).toISOString().replace(/\.\d{3}Z$/, "Z");
|
|
1130
|
+
}
|
|
1131
|
+
|
|
1132
|
+
// src/vendors/youtube/channel.ts
|
|
1133
|
+
var OWN_TTL_MS = 10 * 60 * 1e3;
|
|
1134
|
+
var MAX_CACHED = 64;
|
|
1135
|
+
var ownChannels = /* @__PURE__ */ new Map();
|
|
1136
|
+
async function ownChannel(h) {
|
|
1137
|
+
const key = await sha256Hex(h.credentials["access_token"] ?? "");
|
|
1138
|
+
const cached = ownChannels.get(key);
|
|
1139
|
+
if (cached && cached.expiresAt > Date.now()) return cached.id;
|
|
1140
|
+
ownChannels.delete(key);
|
|
1141
|
+
const { data } = await googleApi(h, { path: "/youtube/v3/channels", query: { part: "id", mine: true } });
|
|
1142
|
+
const id = data?.items?.[0]?.id;
|
|
1143
|
+
if (typeof id !== "string" || !id) {
|
|
1144
|
+
throw new ToolFailure("The connected Google account has no YouTube channel: create one on YouTube, then connect again.");
|
|
1145
|
+
}
|
|
1146
|
+
const now = Date.now();
|
|
1147
|
+
for (const [other, entry] of ownChannels) if (entry.expiresAt <= now) ownChannels.delete(other);
|
|
1148
|
+
while (ownChannels.size >= MAX_CACHED) {
|
|
1149
|
+
const oldest = ownChannels.keys().next().value;
|
|
1150
|
+
if (oldest === void 0) break;
|
|
1151
|
+
ownChannels.delete(oldest);
|
|
1152
|
+
}
|
|
1153
|
+
ownChannels.set(key, { id, expiresAt: now + OWN_TTL_MS });
|
|
1154
|
+
return id;
|
|
1155
|
+
}
|
|
1156
|
+
async function requireOwnChannel(h) {
|
|
1157
|
+
if (allowedAccounts(h.ctx.accounts, "channels") === null) return;
|
|
1158
|
+
requireAccounts(h.ctx.accounts, "channels", await ownChannel(h), "channel");
|
|
1159
|
+
}
|
|
1160
|
+
async function resolveChannel(h, channelId) {
|
|
1161
|
+
if (channelId) {
|
|
1162
|
+
requireAccounts(h.ctx.accounts, "channels", channelId, "channel");
|
|
1163
|
+
return channelId;
|
|
1164
|
+
}
|
|
1165
|
+
const allowed = allowedAccounts(h.ctx.accounts, "channels");
|
|
1166
|
+
if (allowed !== null) {
|
|
1167
|
+
if (allowed.length === 1) return allowed[0];
|
|
1168
|
+
if (!allowed.length) throw new ToolFailure("No YouTube channel is chosen for this connection yet. Nothing was sent.");
|
|
1169
|
+
throw new ToolFailure(`Several channels are chosen for this connection (${allowed.join(", ")}): give channel_id. Nothing was sent.`);
|
|
1170
|
+
}
|
|
1171
|
+
return ownChannel(h);
|
|
1172
|
+
}
|
|
1173
|
+
|
|
1174
|
+
// src/vendors/youtube/media.ts
|
|
1175
|
+
function ascii(bytes, start, length) {
|
|
1176
|
+
return String.fromCharCode(...bytes.subarray(start, start + length));
|
|
1177
|
+
}
|
|
1178
|
+
function sniffVideo(bytes) {
|
|
1179
|
+
if (bytes.length >= 12) {
|
|
1180
|
+
const box = ascii(bytes, 4, 4);
|
|
1181
|
+
if (box === "ftyp") {
|
|
1182
|
+
const brand = ascii(bytes, 8, 4);
|
|
1183
|
+
if (brand === "qt ") return "video/quicktime";
|
|
1184
|
+
if (brand.startsWith("3g")) return "video/3gpp";
|
|
1185
|
+
return "video/mp4";
|
|
1186
|
+
}
|
|
1187
|
+
if (["moov", "mdat", "wide", "free", "skip"].includes(box)) return "video/quicktime";
|
|
1188
|
+
if (ascii(bytes, 0, 4) === "RIFF" && ascii(bytes, 8, 4) === "AVI ") return "video/x-msvideo";
|
|
1189
|
+
}
|
|
1190
|
+
if (bytes.length >= 4 && bytes[0] === 26 && bytes[1] === 69 && bytes[2] === 223 && bytes[3] === 163) return "video/webm";
|
|
1191
|
+
if (bytes.length >= 3 && ascii(bytes, 0, 3) === "FLV") return "video/x-flv";
|
|
1192
|
+
if (bytes.length >= 16 && [48, 38, 178, 117, 142, 102, 207, 17].every((value, index) => bytes[index] === value)) return "video/x-ms-wmv";
|
|
1193
|
+
if (bytes.length >= 4 && bytes[0] === 0 && bytes[1] === 0 && bytes[2] === 1 && bytes[3] === 186) return "video/mpeg";
|
|
1194
|
+
if (bytes.length > 376 && bytes[0] === 71 && bytes[188] === 71 && bytes[376] === 71) return "video/mp2t";
|
|
1195
|
+
return void 0;
|
|
1196
|
+
}
|
|
1197
|
+
function sniffImage(bytes) {
|
|
1198
|
+
if (bytes.length >= 3 && bytes[0] === 255 && bytes[1] === 216 && bytes[2] === 255) return "image/jpeg";
|
|
1199
|
+
if (bytes.length >= 8 && [137, 80, 78, 71, 13, 10, 26, 10].every((value, index) => bytes[index] === value)) return "image/png";
|
|
1200
|
+
return void 0;
|
|
1201
|
+
}
|
|
1202
|
+
function durationSeconds(value) {
|
|
1203
|
+
if (typeof value !== "string") return void 0;
|
|
1204
|
+
const match = /^P(?:(\d+)W)?(?:(\d+)D)?(?:T(?:(\d+)H)?(?:(\d+)M)?(?:(\d+(?:\.\d+)?)S)?)?$/.exec(value);
|
|
1205
|
+
if (!match) return void 0;
|
|
1206
|
+
const [, weeks, days, hours, minutes, seconds] = match;
|
|
1207
|
+
return Math.round(Number(weeks ?? 0) * 604800 + Number(days ?? 0) * 86400 + Number(hours ?? 0) * 3600 + Number(minutes ?? 0) * 60 + Number(seconds ?? 0));
|
|
1208
|
+
}
|
|
1209
|
+
|
|
1210
|
+
// src/vendors/youtube/upload.ts
|
|
1211
|
+
var API = "https://www.googleapis.com";
|
|
1212
|
+
var MIB = 1024 * 1024;
|
|
1213
|
+
var PART_UNIT = 256 * 1024;
|
|
1214
|
+
var DEFAULT_PART_MB = 8;
|
|
1215
|
+
var MAX_PART_MB = 24;
|
|
1216
|
+
var MAX_VIDEO_BYTES = 256 * 1024 * MIB;
|
|
1217
|
+
var MAX_WHOLE_BYTES = 256 * MIB;
|
|
1218
|
+
var CALL_BUDGET_MS = 35e3;
|
|
1219
|
+
var MAX_REPLY_BYTES = 4 * MIB;
|
|
1220
|
+
var USER_AGENT2 = "agent-connectors";
|
|
1221
|
+
var ACCEPT_VIDEO = "video/*,application/octet-stream;q=0.8";
|
|
1222
|
+
var VIDEO_TYPES = /* @__PURE__ */ new Set([
|
|
1223
|
+
"video/mp4",
|
|
1224
|
+
"video/quicktime",
|
|
1225
|
+
"video/3gpp",
|
|
1226
|
+
"video/x-msvideo",
|
|
1227
|
+
"video/webm",
|
|
1228
|
+
"video/x-flv",
|
|
1229
|
+
"video/x-ms-wmv",
|
|
1230
|
+
"video/mpeg",
|
|
1231
|
+
"video/mp2t"
|
|
1232
|
+
]);
|
|
1233
|
+
var CONTENT_RANGE = /^bytes (\d{1,15})-(\d{1,15})\/(\d{1,15}|\*)$/i;
|
|
1234
|
+
var RECEIVED_RANGE = /^bytes=0-(\d{1,15})$/i;
|
|
1235
|
+
var STRONG_ETAG = /^(?!W\/)[\x21-\x7e]{1,200}$/;
|
|
1236
|
+
var GONE = "YouTube no longer has this upload: an upload that is not finished in time expires (or the cursor comes from another sign-in). If list_videos does not show the video, start the upload again without cursor.";
|
|
1237
|
+
var START_AGAIN = "The rest cannot be sent: upload the file again without cursor (YouTube drops the unfinished upload by itself).";
|
|
1238
|
+
function uploadAddress(location) {
|
|
1239
|
+
if (!location) return void 0;
|
|
1240
|
+
let url;
|
|
1241
|
+
try {
|
|
1242
|
+
url = new URL(location);
|
|
1243
|
+
} catch {
|
|
1244
|
+
return void 0;
|
|
1245
|
+
}
|
|
1246
|
+
if (url.origin !== API || url.username || url.password || url.pathname !== "/upload/youtube/v3/videos" || !url.searchParams.get("upload_id")) {
|
|
1247
|
+
return void 0;
|
|
1248
|
+
}
|
|
1249
|
+
url.hash = "";
|
|
1250
|
+
return url.toString();
|
|
1251
|
+
}
|
|
1252
|
+
async function sourceKey(videoUrl) {
|
|
1253
|
+
let normal = videoUrl;
|
|
1254
|
+
try {
|
|
1255
|
+
normal = new URL(videoUrl).toString();
|
|
1256
|
+
} catch {
|
|
1257
|
+
}
|
|
1258
|
+
return (await sha256Hex(normal)).slice(0, 16);
|
|
1259
|
+
}
|
|
1260
|
+
function cursorState(state) {
|
|
1261
|
+
return { s: state.session, n: state.total, p: state.part, y: state.type, u: state.source, ...state.etag ? { e: state.etag } : {} };
|
|
1262
|
+
}
|
|
1263
|
+
function stateFromCursor(raw) {
|
|
1264
|
+
const session = typeof raw["s"] === "string" ? uploadAddress(raw["s"]) : void 0;
|
|
1265
|
+
const total = raw["n"];
|
|
1266
|
+
const part = raw["p"];
|
|
1267
|
+
const type = raw["y"];
|
|
1268
|
+
const source = raw["u"];
|
|
1269
|
+
const etag = raw["e"];
|
|
1270
|
+
if (!session) return void 0;
|
|
1271
|
+
if (typeof total !== "number" || !Number.isSafeInteger(total) || total < 1 || total > MAX_VIDEO_BYTES) return void 0;
|
|
1272
|
+
if (typeof part !== "number" || !Number.isSafeInteger(part) || part < PART_UNIT || part > MAX_PART_MB * MIB || part % PART_UNIT !== 0) return void 0;
|
|
1273
|
+
if (typeof type !== "string" || !VIDEO_TYPES.has(type)) return void 0;
|
|
1274
|
+
if (typeof source !== "string" || !/^[0-9a-f]{16}$/.test(source)) return void 0;
|
|
1275
|
+
if (etag !== void 0 && (typeof etag !== "string" || !STRONG_ETAG.test(etag))) return void 0;
|
|
1276
|
+
return { session, total, part, type, source, ...typeof etag === "string" ? { etag } : {} };
|
|
1277
|
+
}
|
|
1278
|
+
var SourceProblem = class extends Error {
|
|
1279
|
+
constructor(message) {
|
|
1280
|
+
super(message);
|
|
1281
|
+
this.name = "SourceProblem";
|
|
1282
|
+
}
|
|
1283
|
+
};
|
|
1284
|
+
var TooLong = class extends Error {
|
|
1285
|
+
};
|
|
1286
|
+
function errorCode2(error) {
|
|
1287
|
+
const code = error?.code;
|
|
1288
|
+
return typeof code === "string" ? code : void 0;
|
|
1289
|
+
}
|
|
1290
|
+
function describe2(error) {
|
|
1291
|
+
const name2 = error?.name;
|
|
1292
|
+
const code = errorCode2(error);
|
|
1293
|
+
if (code === "TIMEOUT" || name2 === "TimeoutError") return "the request timed out";
|
|
1294
|
+
if (code === "ABORTED" || name2 === "AbortError") return "the request was cancelled";
|
|
1295
|
+
if (code === "TOO_LARGE") return "the reply was too large";
|
|
1296
|
+
return cleanVendorText(error?.message, 200) ?? "a network error";
|
|
1297
|
+
}
|
|
1298
|
+
async function readUpTo(response, max) {
|
|
1299
|
+
const declared = Number(response.headers.get("content-length"));
|
|
1300
|
+
if (Number.isFinite(declared) && declared > max) {
|
|
1301
|
+
await response.body?.cancel().catch(() => {
|
|
1302
|
+
});
|
|
1303
|
+
throw new TooLong();
|
|
1304
|
+
}
|
|
1305
|
+
if (!response.body) return new Uint8Array(0);
|
|
1306
|
+
const reader = response.body.getReader();
|
|
1307
|
+
const chunks = [];
|
|
1308
|
+
let total = 0;
|
|
1309
|
+
for (; ; ) {
|
|
1310
|
+
const { done, value } = await reader.read();
|
|
1311
|
+
if (done) break;
|
|
1312
|
+
total += value.byteLength;
|
|
1313
|
+
if (total > max) {
|
|
1314
|
+
await reader.cancel().catch(() => {
|
|
1315
|
+
});
|
|
1316
|
+
throw new TooLong();
|
|
1317
|
+
}
|
|
1318
|
+
chunks.push(value);
|
|
1319
|
+
}
|
|
1320
|
+
const bytes = new Uint8Array(total);
|
|
1321
|
+
let at = 0;
|
|
1322
|
+
for (const chunk of chunks) {
|
|
1323
|
+
bytes.set(chunk, at);
|
|
1324
|
+
at += chunk.byteLength;
|
|
1325
|
+
}
|
|
1326
|
+
return bytes;
|
|
1327
|
+
}
|
|
1328
|
+
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 part, or its limit is below part_mb. Use a smaller video, a host that passes byte ranges on, or a smaller part_mb.";
|
|
1329
|
+
function downloadProblem(error) {
|
|
1330
|
+
const code = errorCode2(error);
|
|
1331
|
+
if (code === "URL_REFUSED") return new SourceProblem(`The video URL was refused (${describe2(error)}). Use a public https URL.`);
|
|
1332
|
+
if (code === "TOO_LARGE") return new SourceProblem(HOST_LIMIT);
|
|
1333
|
+
return new SourceProblem(`The video could not be downloaded (${describe2(error)}).`);
|
|
1334
|
+
}
|
|
1335
|
+
async function readBody(response, max, whole) {
|
|
1336
|
+
try {
|
|
1337
|
+
return await readUpTo(response, max);
|
|
1338
|
+
} catch (error) {
|
|
1339
|
+
if (!(error instanceof TooLong)) throw downloadProblem(error);
|
|
1340
|
+
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.");
|
|
1341
|
+
}
|
|
1342
|
+
}
|
|
1343
|
+
async function readPart(h, videoUrl, first, last) {
|
|
1344
|
+
let url;
|
|
1345
|
+
try {
|
|
1346
|
+
url = new URL(videoUrl);
|
|
1347
|
+
} catch {
|
|
1348
|
+
throw new SourceProblem("The video URL is not a valid URL.");
|
|
1349
|
+
}
|
|
1350
|
+
if (url.protocol !== "https:") throw new SourceProblem("The video URL must start with https://.");
|
|
1351
|
+
const started = Date.now();
|
|
1352
|
+
let response;
|
|
1353
|
+
try {
|
|
1354
|
+
response = await h.ctx.fetch(url.toString(), {
|
|
1355
|
+
method: "GET",
|
|
1356
|
+
headers: { accept: ACCEPT_VIDEO, "user-agent": USER_AGENT2, range: `bytes=${first}-${last}` },
|
|
1357
|
+
...h.ctx.signal ? { signal: h.ctx.signal } : {}
|
|
1358
|
+
});
|
|
1359
|
+
} catch (error) {
|
|
1360
|
+
h.log(`youtube ${h.tool} media GET failed ${Date.now() - started}ms`);
|
|
1361
|
+
throw downloadProblem(error);
|
|
1362
|
+
}
|
|
1363
|
+
h.log(`youtube ${h.tool} media GET ${response.status} ${Date.now() - started}ms`);
|
|
1364
|
+
const tag = response.headers.get("etag")?.trim();
|
|
1365
|
+
const etag = tag && STRONG_ETAG.test(tag) ? tag : void 0;
|
|
1366
|
+
if (response.status === 206) {
|
|
1367
|
+
const match = CONTENT_RANGE.exec(response.headers.get("content-range")?.trim() ?? "");
|
|
1368
|
+
const start = Number(match?.[1]);
|
|
1369
|
+
const end = Number(match?.[2]);
|
|
1370
|
+
const size = match?.[3];
|
|
1371
|
+
const total = Number(size);
|
|
1372
|
+
if (!match || size === void 0 || start !== first || end < start || end > last || size !== "*" && (end >= total || end !== last && end !== total - 1)) {
|
|
1373
|
+
await response.body?.cancel().catch(() => {
|
|
1374
|
+
});
|
|
1375
|
+
throw new SourceProblem("The video URL answered with another part of the file than the one asked for.");
|
|
1376
|
+
}
|
|
1377
|
+
if (size === "*") {
|
|
1378
|
+
await response.body?.cancel().catch(() => {
|
|
1379
|
+
});
|
|
1380
|
+
throw new SourceProblem("The video URL did not say how large the file is, which YouTube needs to know.");
|
|
1381
|
+
}
|
|
1382
|
+
const bytes = await readBody(response, end - start + 1, false);
|
|
1383
|
+
if (bytes.length !== end - start + 1) throw new SourceProblem("The download of the video ended early.");
|
|
1384
|
+
return { bytes, start, total, ...etag ? { etag } : {} };
|
|
1385
|
+
}
|
|
1386
|
+
if (response.status === 200) {
|
|
1387
|
+
const bytes = await readBody(response, MAX_WHOLE_BYTES, true);
|
|
1388
|
+
return { bytes, start: 0, total: bytes.length, ...etag ? { etag } : {} };
|
|
1389
|
+
}
|
|
1390
|
+
await response.body?.cancel().catch(() => {
|
|
1391
|
+
});
|
|
1392
|
+
if (response.status === 416) {
|
|
1393
|
+
throw new SourceProblem(`The video URL has no bytes from ${formatNumber(first)} on (HTTP 416): the file is ${first ? "smaller than when the upload started" : "empty"}.`);
|
|
1394
|
+
}
|
|
1395
|
+
throw new SourceProblem(`The video URL answered HTTP ${response.status}.`);
|
|
1396
|
+
}
|
|
1397
|
+
function changedSince(state, part) {
|
|
1398
|
+
if (part.total !== state.total) {
|
|
1399
|
+
return `The file at video_url is ${formatNumber(part.total)} bytes now, not the ${formatNumber(state.total)} it had when the upload started.`;
|
|
1400
|
+
}
|
|
1401
|
+
if (state.etag && part.etag && state.etag !== part.etag) return "The file at video_url changed since the upload started (its ETag is different).";
|
|
1402
|
+
return void 0;
|
|
1403
|
+
}
|
|
1404
|
+
function parseReply(bytes) {
|
|
1405
|
+
if (!bytes.length) return null;
|
|
1406
|
+
const text2 = utf8Decode(bytes);
|
|
1407
|
+
try {
|
|
1408
|
+
return JSON.parse(text2);
|
|
1409
|
+
} catch {
|
|
1410
|
+
return text2;
|
|
1411
|
+
}
|
|
1412
|
+
}
|
|
1413
|
+
async function toSession(h, session, contentRange, body, type) {
|
|
1414
|
+
const started = Date.now();
|
|
1415
|
+
let response;
|
|
1416
|
+
try {
|
|
1417
|
+
response = await h.ctx.fetch(session, {
|
|
1418
|
+
method: "PUT",
|
|
1419
|
+
headers: {
|
|
1420
|
+
accept: "application/json",
|
|
1421
|
+
"user-agent": USER_AGENT2,
|
|
1422
|
+
authorization: `Bearer ${h.credentials["access_token"] ?? ""}`,
|
|
1423
|
+
"content-range": contentRange,
|
|
1424
|
+
...type ? { "content-type": type } : {}
|
|
1425
|
+
},
|
|
1426
|
+
body,
|
|
1427
|
+
...h.ctx.signal ? { signal: h.ctx.signal } : {}
|
|
1428
|
+
});
|
|
1429
|
+
} catch (error) {
|
|
1430
|
+
h.log(`youtube ${h.tool} PUT failed ${Date.now() - started}ms`);
|
|
1431
|
+
if (errorCode2(error) === "URL_REFUSED") {
|
|
1432
|
+
return { kind: "refused", gone: false, message: `The request to YouTube was blocked before it was sent (${describe2(error)}).` };
|
|
1433
|
+
}
|
|
1434
|
+
return { kind: "unclear", reason: describe2(error) };
|
|
1435
|
+
}
|
|
1436
|
+
h.log(`youtube ${h.tool} PUT ${response.status} ${Date.now() - started}ms`);
|
|
1437
|
+
const { status } = response;
|
|
1438
|
+
if (status === 308) {
|
|
1439
|
+
await response.body?.cancel().catch(() => {
|
|
1440
|
+
});
|
|
1441
|
+
const range = response.headers.get("range")?.trim();
|
|
1442
|
+
if (!range) return { kind: "more", received: 0 };
|
|
1443
|
+
const match = RECEIVED_RANGE.exec(range);
|
|
1444
|
+
return match ? { kind: "more", received: Number(match[1]) + 1 } : { kind: "unclear", reason: "a byte range that could not be read" };
|
|
1445
|
+
}
|
|
1446
|
+
let data = null;
|
|
1447
|
+
try {
|
|
1448
|
+
data = parseReply(await readUpTo(response, MAX_REPLY_BYTES));
|
|
1449
|
+
} catch {
|
|
1450
|
+
if (status === 200 || status === 201 || status >= 500) return { kind: "unclear", reason: `HTTP ${status}, but the reply could not be read` };
|
|
1451
|
+
}
|
|
1452
|
+
if (status === 200 || status === 201) {
|
|
1453
|
+
return typeof data?.id === "string" ? { kind: "done", video: data } : { kind: "unclear", reason: `HTTP ${status} without the video` };
|
|
1454
|
+
}
|
|
1455
|
+
const message = vendorMessage(data);
|
|
1456
|
+
const said = message ? `: ${plain(message).replace(/[.!?。]+$/u, "")}` : "";
|
|
1457
|
+
if (status >= 500) return { kind: "unclear", reason: `HTTP ${status}${said}` };
|
|
1458
|
+
if (status === 404 || status === 410) return { kind: "refused", status, gone: true, message: GONE };
|
|
1459
|
+
if (status === 429) {
|
|
1460
|
+
const retryAfter = retryAfterSeconds(response.headers);
|
|
1461
|
+
return {
|
|
1462
|
+
kind: "refused",
|
|
1463
|
+
status,
|
|
1464
|
+
gone: false,
|
|
1465
|
+
message: `YouTube rate limit reached (HTTP 429). ${retryAfter !== void 0 ? `Retry after ${retryAfter} seconds.` : "Wait a while before going on."}`,
|
|
1466
|
+
...retryAfter !== void 0 ? { retryAfter } : {}
|
|
1467
|
+
};
|
|
1468
|
+
}
|
|
1469
|
+
if (status === 401) {
|
|
1470
|
+
return { kind: "refused", status, gone: false, message: `YouTube rejected the credentials (HTTP 401)${said}. Check that the YouTube access token is correct and still active.` };
|
|
1471
|
+
}
|
|
1472
|
+
if (status === 403) return { kind: "refused", status, gone: false, message: `YouTube refused the upload (HTTP 403)${said}.` };
|
|
1473
|
+
return { kind: "refused", status, gone: false, message: `YouTube rejected the upload request (HTTP ${status})${said}.` };
|
|
1474
|
+
}
|
|
1475
|
+
function askSession(h, state) {
|
|
1476
|
+
return toSession(h, state.session, `bytes */${state.total}`, new Uint8Array(0));
|
|
1477
|
+
}
|
|
1478
|
+
function sendPart(h, state, offset, bytes) {
|
|
1479
|
+
return toSession(h, state.session, `bytes ${offset}-${offset + bytes.length - 1}/${state.total}`, bytes, state.type);
|
|
1480
|
+
}
|
|
1481
|
+
var sending = /* @__PURE__ */ new Set();
|
|
1482
|
+
async function exclusive(state, run) {
|
|
1483
|
+
if (sending.has(state.session)) {
|
|
1484
|
+
throw new ToolFailure("Another call is sending this upload right now: wait for its result, then go on with the cursor. Nothing was sent.");
|
|
1485
|
+
}
|
|
1486
|
+
sending.add(state.session);
|
|
1487
|
+
try {
|
|
1488
|
+
return await run();
|
|
1489
|
+
} finally {
|
|
1490
|
+
sending.delete(state.session);
|
|
1491
|
+
}
|
|
1492
|
+
}
|
|
1493
|
+
function resumeHint(cursor) {
|
|
1494
|
+
return `Calling upload_video again with the same arguments and cursor "${cursor}" is safe: it asks YouTube first, returns the video if it was made, and sends only the bytes YouTube does not have.`;
|
|
1495
|
+
}
|
|
1496
|
+
async function settle(h, run, offset, final, reason) {
|
|
1497
|
+
const { state } = run;
|
|
1498
|
+
if (!h.ctx.signal?.aborted) {
|
|
1499
|
+
const status = await askSession(h, state);
|
|
1500
|
+
if (status.kind === "done") return { done: true, video: status.video };
|
|
1501
|
+
if (status.kind === "more" && status.received < state.total) {
|
|
1502
|
+
return {
|
|
1503
|
+
done: false,
|
|
1504
|
+
uploaded: status.received,
|
|
1505
|
+
stopped: `YouTube did not answer the last part clearly (${reason}); it has ${formatNumber(status.received)} of the ${formatNumber(state.total)} bytes.`
|
|
1506
|
+
};
|
|
1507
|
+
}
|
|
1508
|
+
if (status.kind === "refused" && status.gone) throw new ToolFailure(GONE);
|
|
1509
|
+
}
|
|
1510
|
+
if (final) {
|
|
1511
|
+
throw new OutcomeUnknown(`YouTube did not answer the last part of the upload (${reason}), so it is not known whether the video was made. ${resumeHint(run.cursor)}`);
|
|
1512
|
+
}
|
|
1513
|
+
return {
|
|
1514
|
+
done: false,
|
|
1515
|
+
uploaded: offset,
|
|
1516
|
+
stopped: `YouTube did not answer the last part clearly (${reason}), and could not say how far the upload got: the next call asks again before it sends anything.`
|
|
1517
|
+
};
|
|
1518
|
+
}
|
|
1519
|
+
async function transfer(h, run) {
|
|
1520
|
+
const { state, videoUrl, started } = run;
|
|
1521
|
+
let { offset, held } = run;
|
|
1522
|
+
let partStarted = run.heldSince ?? Date.now();
|
|
1523
|
+
let lastMs = 0;
|
|
1524
|
+
let sent = 0;
|
|
1525
|
+
let finalSent = false;
|
|
1526
|
+
try {
|
|
1527
|
+
for (; ; ) {
|
|
1528
|
+
if (sent > 0) {
|
|
1529
|
+
if (h.ctx.signal?.aborted) return { done: false, uploaded: offset, stopped: "The call was cancelled." };
|
|
1530
|
+
if (Date.now() - started + lastMs * 1.5 > CALL_BUDGET_MS) return { done: false, uploaded: offset };
|
|
1531
|
+
partStarted = Date.now();
|
|
1532
|
+
}
|
|
1533
|
+
const end = Math.min(offset + state.part, state.total);
|
|
1534
|
+
if (!held || held.start > offset || held.start + held.bytes.length < end) {
|
|
1535
|
+
try {
|
|
1536
|
+
held = await readPart(h, videoUrl, offset, end - 1);
|
|
1537
|
+
} catch (error) {
|
|
1538
|
+
if (error instanceof SourceProblem) return { done: false, uploaded: offset, stopped: `Reading the next part of the video failed. ${error.message}` };
|
|
1539
|
+
throw error;
|
|
1540
|
+
}
|
|
1541
|
+
const changed = changedSince(state, held);
|
|
1542
|
+
if (changed) throw new ToolFailure(`${changed} ${START_AGAIN}`);
|
|
1543
|
+
}
|
|
1544
|
+
const final = end === state.total;
|
|
1545
|
+
if (final) finalSent = true;
|
|
1546
|
+
const answer = await sendPart(h, state, offset, held.bytes.subarray(offset - held.start, end - held.start));
|
|
1547
|
+
sent += 1;
|
|
1548
|
+
lastMs = Date.now() - partStarted;
|
|
1549
|
+
if (answer.kind === "done") return { done: true, video: answer.video };
|
|
1550
|
+
if (answer.kind === "unclear") return await settle(h, run, offset, final, answer.reason);
|
|
1551
|
+
if (answer.kind === "refused") {
|
|
1552
|
+
if (answer.gone) throw new ToolFailure(GONE);
|
|
1553
|
+
return { done: false, uploaded: offset, stopped: answer.message, ...answer.retryAfter !== void 0 ? { retryAfter: answer.retryAfter } : {} };
|
|
1554
|
+
}
|
|
1555
|
+
if (answer.received >= state.total) return await settle(h, run, offset, final, "every byte in, but no video back");
|
|
1556
|
+
if (answer.received <= offset) return { done: false, uploaded: answer.received, stopped: "YouTube took none of the last part, so the next call sends it again." };
|
|
1557
|
+
offset = answer.received;
|
|
1558
|
+
}
|
|
1559
|
+
} catch (error) {
|
|
1560
|
+
if (error instanceof ToolFailure || error instanceof OutcomeUnknown || !finalSent) throw error;
|
|
1561
|
+
throw new OutcomeUnknown(`The upload stopped unexpectedly after its last part was sent to YouTube, so it is not known whether the video was made. ${resumeHint(run.cursor)}`);
|
|
1562
|
+
}
|
|
1563
|
+
}
|
|
1564
|
+
|
|
1565
|
+
// src/vendors/youtube/index.ts
|
|
1566
|
+
var API2 = "https://www.googleapis.com";
|
|
1567
|
+
var ANALYTICS = "https://youtubeanalytics.googleapis.com";
|
|
1568
|
+
var MIB2 = 1024 * 1024;
|
|
1569
|
+
var MAX_OFFSET = 1e5;
|
|
1570
|
+
var MAX_THUMBNAIL_BYTES = 2 * 1024 * 1024;
|
|
1571
|
+
var VIDEO_PARTS = "snippet,statistics,contentDetails,status";
|
|
1572
|
+
var UPLOAD_NOTE = "YouTube processes the video for a few minutes. A vertical or square video of 3 minutes or less becomes a Short (https://youtube.com/shorts/VIDEO_ID). If get_videos later shows it private although public or unlisted was asked, YouTube locked it: videos uploaded through a Google Cloud project that has not passed the YouTube API audit stay private (audit form: https://support.google.com/youtube/contact/yt_api_form). Do not upload it again.";
|
|
1573
|
+
var CHANNEL_ID = {
|
|
1574
|
+
type: "string",
|
|
1575
|
+
pattern: "^UC[A-Za-z0-9_-]{22}$",
|
|
1576
|
+
description: "The channel id (UC...), from list_channels. Leave out for the chosen channel, or the connected one."
|
|
1577
|
+
};
|
|
1578
|
+
var VIDEO_ID = { type: "string", pattern: "^[A-Za-z0-9_-]{11}$", description: "The video id, from list_videos." };
|
|
1579
|
+
var PLAYLIST_ID = { type: "string", pattern: "^[A-Za-z0-9_-]{2,64}$", description: "The playlist id, from list_playlists." };
|
|
1580
|
+
var CURSOR = { type: "string", description: "nextCursor from the previous result (send the same filters with it)." };
|
|
1581
|
+
var PAGE_SIZE = { type: "integer", minimum: 1, maximum: 50, default: 25, description: "Items per page, 1 to 50 (default 25)." };
|
|
1582
|
+
var DATE = { type: "string", pattern: "^\\d{4}-\\d{2}-\\d{2}$" };
|
|
1583
|
+
var TIME = "^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}(:\\d{2}(\\.\\d{1,9})?)?(Z|[+-]\\d{2}:\\d{2})$";
|
|
1584
|
+
var LANGUAGE = { type: "string", pattern: "^[A-Za-z]{2,3}(-[A-Za-z0-9]{2,8})*$" };
|
|
1585
|
+
var PRIVACY = ["public", "unlisted", "private"];
|
|
1586
|
+
var METADATA_FIELDS = {
|
|
1587
|
+
title: { type: "string", minLength: 1, maxLength: 100, description: "The title: up to 100 characters, no < or >." },
|
|
1588
|
+
description: { type: "string", maxLength: 5e3, description: "The description: up to 5,000 bytes, no < or >." },
|
|
1589
|
+
tags: {
|
|
1590
|
+
type: "array",
|
|
1591
|
+
items: { type: "string", minLength: 1, maxLength: 100 },
|
|
1592
|
+
maxItems: 100,
|
|
1593
|
+
description: "Tags; all of them together at most 500 characters (a tag with a space counts its quotes)."
|
|
1594
|
+
},
|
|
1595
|
+
category_id: {
|
|
1596
|
+
type: "string",
|
|
1597
|
+
pattern: "^[0-9]{1,3}$",
|
|
1598
|
+
description: "The category: 1 Film and Animation, 10 Music, 17 Sports, 20 Gaming, 22 People and Blogs, 24 Entertainment, 27 Education, 28 Science and Technology."
|
|
1599
|
+
},
|
|
1600
|
+
default_language: { ...LANGUAGE, description: 'The language of the title and description, such as "en" or "tr".' },
|
|
1601
|
+
default_audio_language: { ...LANGUAGE, description: "The spoken language of the video." }
|
|
1602
|
+
};
|
|
1603
|
+
var STATUS_FIELDS = {
|
|
1604
|
+
privacy_status: { type: "string", enum: PRIVACY, description: 'public (anyone; "publish" means this), unlisted (anyone with the link) or private.' },
|
|
1605
|
+
publish_at: { type: "string", pattern: TIME, description: "A scheduled release, as a future RFC 3339 time such as 2026-12-01T07:00:00Z: needs privacy_status private, and YouTube makes the video public then." },
|
|
1606
|
+
made_for_kids: { type: "boolean", description: "Whether the video is made for kids (YouTube's audience setting)." },
|
|
1607
|
+
contains_synthetic_media: { type: "boolean", description: "true when the video shows AI-generated realistic people or scenes: YouTube labels it as altered or synthetic content." },
|
|
1608
|
+
embeddable: { type: "boolean", description: "Whether other sites may embed the video." },
|
|
1609
|
+
public_stats_viewable: { type: "boolean", description: "Whether the like count and other statistics are public." },
|
|
1610
|
+
license: { type: "string", enum: ["youtube", "creativeCommon"], description: "The license: youtube (standard) or creativeCommon." }
|
|
1611
|
+
};
|
|
1612
|
+
function text(value, max) {
|
|
1613
|
+
return typeof value === "string" && value.trim() ? truncate(value.trim(), max) : void 0;
|
|
1614
|
+
}
|
|
1615
|
+
function thumbnailOf(snippet) {
|
|
1616
|
+
const thumbnails = snippet?.thumbnails ?? {};
|
|
1617
|
+
for (const size of ["maxres", "standard", "high", "medium", "default"]) {
|
|
1618
|
+
if (typeof thumbnails[size]?.url === "string") return thumbnails[size].url;
|
|
1619
|
+
}
|
|
1620
|
+
return void 0;
|
|
1621
|
+
}
|
|
1622
|
+
function trimVideoSummary(video) {
|
|
1623
|
+
const snippet = video?.snippet ?? {};
|
|
1624
|
+
const status = video?.status ?? {};
|
|
1625
|
+
const stats = video?.statistics ?? {};
|
|
1626
|
+
const details = video?.contentDetails ?? {};
|
|
1627
|
+
return compact({
|
|
1628
|
+
id: video?.id,
|
|
1629
|
+
title: text(snippet.title, 200),
|
|
1630
|
+
published_at: snippet.publishedAt,
|
|
1631
|
+
privacy_status: status.privacyStatus,
|
|
1632
|
+
publish_at: status.publishAt,
|
|
1633
|
+
upload_status: status.uploadStatus && status.uploadStatus !== "processed" ? status.uploadStatus : void 0,
|
|
1634
|
+
duration: details.duration,
|
|
1635
|
+
duration_seconds: durationSeconds(details.duration),
|
|
1636
|
+
views: count(stats.viewCount),
|
|
1637
|
+
likes: count(stats.likeCount),
|
|
1638
|
+
comments: count(stats.commentCount),
|
|
1639
|
+
made_for_kids: status.madeForKids,
|
|
1640
|
+
url: typeof video?.id === "string" ? `https://youtu.be/${video.id}` : void 0
|
|
1641
|
+
});
|
|
1642
|
+
}
|
|
1643
|
+
function trimVideo(video) {
|
|
1644
|
+
const snippet = video?.snippet ?? {};
|
|
1645
|
+
const status = video?.status ?? {};
|
|
1646
|
+
const details = video?.contentDetails ?? {};
|
|
1647
|
+
return compact({
|
|
1648
|
+
...trimVideoSummary(video),
|
|
1649
|
+
description: text(snippet.description, 5e3),
|
|
1650
|
+
tags: Array.isArray(snippet.tags) ? snippet.tags.map((tag) => String(tag)) : void 0,
|
|
1651
|
+
category_id: snippet.categoryId,
|
|
1652
|
+
default_language: snippet.defaultLanguage,
|
|
1653
|
+
default_audio_language: snippet.defaultAudioLanguage,
|
|
1654
|
+
channel_id: snippet.channelId,
|
|
1655
|
+
channel_title: text(snippet.channelTitle, 200),
|
|
1656
|
+
upload_status: status.uploadStatus,
|
|
1657
|
+
failure_reason: status.failureReason,
|
|
1658
|
+
rejection_reason: status.rejectionReason,
|
|
1659
|
+
license: status.license,
|
|
1660
|
+
embeddable: status.embeddable,
|
|
1661
|
+
public_stats_viewable: status.publicStatsViewable,
|
|
1662
|
+
self_declared_made_for_kids: status.selfDeclaredMadeForKids,
|
|
1663
|
+
contains_synthetic_media: status.containsSyntheticMedia,
|
|
1664
|
+
definition: details.definition,
|
|
1665
|
+
caption: details.caption === "true" ? true : details.caption === "false" ? false : void 0,
|
|
1666
|
+
thumbnail: thumbnailOf(snippet),
|
|
1667
|
+
studio_url: typeof video?.id === "string" ? `https://studio.youtube.com/video/${video.id}/edit` : void 0
|
|
1668
|
+
});
|
|
1669
|
+
}
|
|
1670
|
+
function trimChannel(channel, full) {
|
|
1671
|
+
const snippet = channel?.snippet ?? {};
|
|
1672
|
+
const stats = channel?.statistics ?? {};
|
|
1673
|
+
return compact({
|
|
1674
|
+
id: channel?.id,
|
|
1675
|
+
title: text(snippet.title, 200),
|
|
1676
|
+
handle: snippet.customUrl,
|
|
1677
|
+
subscribers: stats.hiddenSubscriberCount ? void 0 : count(stats.subscriberCount),
|
|
1678
|
+
views: count(stats.viewCount),
|
|
1679
|
+
videos: count(stats.videoCount),
|
|
1680
|
+
uploads_playlist_id: channel?.contentDetails?.relatedPlaylists?.uploads,
|
|
1681
|
+
url: typeof channel?.id === "string" ? `https://www.youtube.com/channel/${channel.id}` : void 0,
|
|
1682
|
+
...full ? {
|
|
1683
|
+
description: text(snippet.description, 2e3),
|
|
1684
|
+
published_at: snippet.publishedAt,
|
|
1685
|
+
country: snippet.country,
|
|
1686
|
+
default_language: snippet.defaultLanguage,
|
|
1687
|
+
keywords: text(channel?.brandingSettings?.channel?.keywords, 500),
|
|
1688
|
+
privacy_status: channel?.status?.privacyStatus,
|
|
1689
|
+
made_for_kids: channel?.status?.madeForKids,
|
|
1690
|
+
long_uploads: channel?.status?.longUploadsStatus,
|
|
1691
|
+
thumbnail: thumbnailOf(snippet)
|
|
1692
|
+
} : {}
|
|
1693
|
+
});
|
|
1694
|
+
}
|
|
1695
|
+
function trimPlaylist(playlist) {
|
|
1696
|
+
return compact({
|
|
1697
|
+
id: playlist?.id,
|
|
1698
|
+
title: text(playlist?.snippet?.title, 200),
|
|
1699
|
+
description: text(playlist?.snippet?.description, 300),
|
|
1700
|
+
privacy_status: playlist?.status?.privacyStatus,
|
|
1701
|
+
item_count: playlist?.contentDetails?.itemCount,
|
|
1702
|
+
published_at: playlist?.snippet?.publishedAt,
|
|
1703
|
+
url: typeof playlist?.id === "string" ? `https://www.youtube.com/playlist?list=${playlist.id}` : void 0
|
|
1704
|
+
});
|
|
1705
|
+
}
|
|
1706
|
+
function checkMetadata(args) {
|
|
1707
|
+
for (const [name2, value] of [["title", args.title], ["description", args.description]]) {
|
|
1708
|
+
if (value !== void 0 && /[<>]/.test(value)) throw new ToolFailure(`The ${name2} may not contain < or >: YouTube refuses them. Nothing was changed.`);
|
|
1709
|
+
}
|
|
1710
|
+
if (args.description !== void 0 && utf8Length(args.description) > 5e3) {
|
|
1711
|
+
throw new ToolFailure(`The description is ${formatNumber(utf8Length(args.description))} bytes; YouTube allows 5,000. Nothing was changed.`);
|
|
1712
|
+
}
|
|
1713
|
+
if (args.tags) {
|
|
1714
|
+
if (args.tags.some((tag) => /[<>]/.test(tag))) throw new ToolFailure("A tag may not contain < or >. Nothing was changed.");
|
|
1715
|
+
const total = args.tags.reduce((sum, tag) => sum + Array.from(tag).length + (/\s/.test(tag) ? 2 : 0), 0) + Math.max(0, args.tags.length - 1);
|
|
1716
|
+
if (total > 500) throw new ToolFailure(`The tags come to ${total} characters; YouTube allows 500 in all (a tag with a space counts its quotes). Nothing was changed.`);
|
|
1717
|
+
}
|
|
1718
|
+
}
|
|
1719
|
+
function futureTime(value) {
|
|
1720
|
+
const time = utcTime(value, "publish_at");
|
|
1721
|
+
if (Date.parse(time) <= Date.now()) throw new ToolFailure("publish_at must be in the future. Nothing was changed.");
|
|
1722
|
+
return time;
|
|
1723
|
+
}
|
|
1724
|
+
async function readVideo(h, videoId, parts) {
|
|
1725
|
+
const { data } = await googleApi(h, { path: "/youtube/v3/videos", query: { part: parts, id: videoId } });
|
|
1726
|
+
const video = Array.isArray(data?.items) ? data.items[0] : void 0;
|
|
1727
|
+
if (!video) throw new ToolFailure(`YouTube found no video ${videoId} that this account can see.`);
|
|
1728
|
+
return video;
|
|
1729
|
+
}
|
|
1730
|
+
async function videoDetails(h, ids) {
|
|
1731
|
+
const byId = /* @__PURE__ */ new Map();
|
|
1732
|
+
if (!ids.length) return byId;
|
|
1733
|
+
const { data } = await googleApi(h, { path: "/youtube/v3/videos", query: { part: VIDEO_PARTS, id: ids.join(",") } });
|
|
1734
|
+
for (const video of Array.isArray(data?.items) ? data.items : []) if (typeof video?.id === "string") byId.set(video.id, video);
|
|
1735
|
+
return byId;
|
|
1736
|
+
}
|
|
1737
|
+
async function uploadsPage(h, state, channelId, size) {
|
|
1738
|
+
const carried = typeof state?.["u"] === "string" ? state["u"] : void 0;
|
|
1739
|
+
let uploads = carried === `UU${channelId.slice(2)}` ? carried : void 0;
|
|
1740
|
+
if (!uploads) {
|
|
1741
|
+
const { data: data2 } = await googleApi(h, { path: "/youtube/v3/channels", query: { part: "contentDetails", id: channelId } });
|
|
1742
|
+
uploads = data2?.items?.[0]?.contentDetails?.relatedPlaylists?.uploads;
|
|
1743
|
+
if (typeof uploads !== "string" || !uploads) throw new ToolFailure(`YouTube found no channel ${channelId} or no uploads list for it.`);
|
|
1744
|
+
}
|
|
1745
|
+
const pageToken = carried === uploads && typeof state?.["p"] === "string" ? state["p"] : void 0;
|
|
1746
|
+
const { data } = await googleApi(h, {
|
|
1747
|
+
path: "/youtube/v3/playlistItems",
|
|
1748
|
+
query: { part: "contentDetails", playlistId: uploads, maxResults: size, pageToken },
|
|
1749
|
+
errors: { 404: "YouTube found no uploads list for this channel" }
|
|
1750
|
+
});
|
|
1751
|
+
const ids = (Array.isArray(data?.items) ? data.items : []).map((item) => item?.contentDetails?.videoId).filter((id) => typeof id === "string");
|
|
1752
|
+
const details = await videoDetails(h, ids);
|
|
1753
|
+
return {
|
|
1754
|
+
uploads,
|
|
1755
|
+
pageToken,
|
|
1756
|
+
videos: ids.map((id) => details.get(id)).filter((video) => video !== void 0),
|
|
1757
|
+
nextToken: typeof data?.nextPageToken === "string" && data.nextPageToken ? data.nextPageToken : void 0
|
|
1758
|
+
};
|
|
1759
|
+
}
|
|
1760
|
+
var GO_ON = "call upload_video again with the same arguments and cursor set to nextCursor, until done is true. Each call asks YouTube how far it got and sends only the rest: no byte goes twice and no second video is made. Go on soon: YouTube drops an upload that is not finished in time.";
|
|
1761
|
+
function uploadResult(outcome, state, cursor) {
|
|
1762
|
+
if (!outcome.done) {
|
|
1763
|
+
const first = outcome.stopped ? `Deal with what stopped says first${outcome.retryAfter !== void 0 ? ` (wait ${outcome.retryAfter} seconds)` : ""}, then ` : "To go on, ";
|
|
1764
|
+
return compact({
|
|
1765
|
+
done: false,
|
|
1766
|
+
bytes_uploaded: outcome.uploaded,
|
|
1767
|
+
bytes_total: state.total,
|
|
1768
|
+
stopped: outcome.stopped,
|
|
1769
|
+
retryAfter: outcome.retryAfter,
|
|
1770
|
+
nextCursor: cursor,
|
|
1771
|
+
next: `${first}${GO_ON}`
|
|
1772
|
+
});
|
|
1773
|
+
}
|
|
1774
|
+
const video = trimVideo(outcome.video);
|
|
1775
|
+
return compact({
|
|
1776
|
+
done: true,
|
|
1777
|
+
id: video["id"],
|
|
1778
|
+
url: video["url"],
|
|
1779
|
+
studio_url: video["studio_url"],
|
|
1780
|
+
title: video["title"],
|
|
1781
|
+
channel_id: video["channel_id"],
|
|
1782
|
+
privacy_status: video["privacy_status"],
|
|
1783
|
+
publish_at: video["publish_at"],
|
|
1784
|
+
upload_status: video["upload_status"],
|
|
1785
|
+
bytes: state.total,
|
|
1786
|
+
content_type: state.type,
|
|
1787
|
+
note: UPLOAD_NOTE
|
|
1788
|
+
});
|
|
1789
|
+
}
|
|
1790
|
+
async function goOn(h, state, videoUrl, started) {
|
|
1791
|
+
const cursor = h.makeCursor(cursorState(state));
|
|
1792
|
+
const status = await askSession(h, state);
|
|
1793
|
+
if (status.kind === "done") return uploadResult({ done: true, video: status.video }, state, cursor);
|
|
1794
|
+
if (status.kind === "refused") {
|
|
1795
|
+
const details = {
|
|
1796
|
+
...status.status !== void 0 ? { status: status.status } : {},
|
|
1797
|
+
...status.retryAfter !== void 0 ? { retryAfter: status.retryAfter } : {}
|
|
1798
|
+
};
|
|
1799
|
+
throw new ToolFailure(status.gone ? GONE : `${status.message} Nothing was sent: go on later with the same cursor.`, details);
|
|
1800
|
+
}
|
|
1801
|
+
if (status.kind === "unclear" || status.received >= state.total) {
|
|
1802
|
+
const why = status.kind === "unclear" ? status.reason : "every byte in, but no video";
|
|
1803
|
+
throw new ToolFailure(`YouTube could not say how far the upload got (${why}). Nothing was sent: go on later with the same cursor.`);
|
|
1804
|
+
}
|
|
1805
|
+
return uploadResult(await transfer(h, { state, videoUrl, offset: status.received, started, cursor }), state, cursor);
|
|
1806
|
+
}
|
|
1807
|
+
var REPORTS = {
|
|
1808
|
+
top_videos: { metrics: ["views", "estimatedMinutesWatched", "averageViewDuration", "averageViewPercentage"], dimensions: ["video"], sort: "-views", maxResults: 25 },
|
|
1809
|
+
daily: { metrics: ["views", "estimatedMinutesWatched", "averageViewDuration", "subscribersGained", "subscribersLost", "likes", "comments", "shares"], dimensions: ["day"], sort: "day" },
|
|
1810
|
+
retention: { metrics: ["audienceWatchRatio", "relativeRetentionPerformance"], dimensions: ["elapsedVideoTimeRatio"], needsVideo: true },
|
|
1811
|
+
traffic_sources: { metrics: ["views", "estimatedMinutesWatched"], dimensions: ["insightTrafficSourceType"], sort: "-views" },
|
|
1812
|
+
countries: { metrics: ["views", "estimatedMinutesWatched", "averageViewDuration"], dimensions: ["country"], sort: "-views", maxResults: 25 },
|
|
1813
|
+
devices: { metrics: ["views", "estimatedMinutesWatched"], dimensions: ["deviceType"], sort: "-views" },
|
|
1814
|
+
demographics: { metrics: ["viewerPercentage"], dimensions: ["ageGroup", "gender"], sort: "gender,ageGroup" }
|
|
1815
|
+
};
|
|
1816
|
+
var AD_FORMATS = {
|
|
1817
|
+
any: { words: "any length" },
|
|
1818
|
+
bumper: { max: 6, words: "at most 6 seconds" },
|
|
1819
|
+
non_skippable: { max: 15, words: "at most 15 seconds" },
|
|
1820
|
+
skippable: { min: 12, max: 180, words: "12 seconds to 3 minutes" }
|
|
1821
|
+
};
|
|
1822
|
+
function day(offsetDays) {
|
|
1823
|
+
return new Date(Date.now() - offsetDays * 864e5).toISOString().slice(0, 10);
|
|
1824
|
+
}
|
|
1825
|
+
async function guard(request, h) {
|
|
1826
|
+
const base = request.origin === ANALYTICS ? "/v2/" : "/youtube/v3/";
|
|
1827
|
+
if (!request.path.startsWith(base)) throw new ToolFailure(`Paths on ${request.origin} start with ${base}. Nothing was sent.`);
|
|
1828
|
+
for (const name2 of ["onBehalfOfContentOwner", "onBehalfOfContentOwnerChannel", "forContentOwner"]) {
|
|
1829
|
+
if (request.query[name2]?.length) throw new ToolFailure("Requests on behalf of a content owner are not available here. Nothing was sent.");
|
|
1830
|
+
}
|
|
1831
|
+
if (h.ctx.accounts === null) return;
|
|
1832
|
+
const named = /* @__PURE__ */ new Set();
|
|
1833
|
+
for (const name2 of ["channelId", "allThreadsRelatedToChannelId"]) for (const value of request.query[name2] ?? []) named.add(value);
|
|
1834
|
+
if (request.origin !== ANALYTICS && request.segments[2] === "channels") {
|
|
1835
|
+
for (const value of request.query["id"] ?? []) for (const id of value.split(",")) if (id.trim()) named.add(id.trim());
|
|
1836
|
+
}
|
|
1837
|
+
if (request.origin === ANALYTICS) {
|
|
1838
|
+
for (const value of request.query["ids"] ?? []) {
|
|
1839
|
+
const match = /^channel==(.+)$/.exec(value);
|
|
1840
|
+
if (!match) throw new ToolFailure("Analytics requests here take ids=channel==CHANNEL_ID (or channel==MINE). Nothing was sent.");
|
|
1841
|
+
if (match[1] !== "MINE") named.add(match[1]);
|
|
1842
|
+
}
|
|
1843
|
+
}
|
|
1844
|
+
if (named.size) requireAccounts(h.ctx.accounts, "channels", [...named], "channel");
|
|
1845
|
+
await requireOwnChannel(h);
|
|
1846
|
+
}
|
|
1847
|
+
var connector = defineConnector({
|
|
1848
|
+
vendor: "youtube",
|
|
1849
|
+
label: "YouTube",
|
|
1850
|
+
origins: [API2, ANALYTICS],
|
|
1851
|
+
credentials: ["access_token"],
|
|
1852
|
+
credentialLabels: { access_token: "YouTube access token" },
|
|
1853
|
+
accountPickers: [
|
|
1854
|
+
{
|
|
1855
|
+
key: "channels",
|
|
1856
|
+
label: "YouTube channels",
|
|
1857
|
+
description: "The channels the agent may work on.",
|
|
1858
|
+
multiple: true,
|
|
1859
|
+
tool: "list_channels",
|
|
1860
|
+
idField: "id",
|
|
1861
|
+
nameField: "title",
|
|
1862
|
+
legacyField: "channelid"
|
|
1863
|
+
}
|
|
1864
|
+
],
|
|
1865
|
+
authHeaders: (credentials) => ({ authorization: `Bearer ${credentials["access_token"]}` }),
|
|
1866
|
+
tools: [
|
|
1867
|
+
{
|
|
1868
|
+
name: "list_channels",
|
|
1869
|
+
kind: "read",
|
|
1870
|
+
title: "List YouTube channels",
|
|
1871
|
+
description: "Lists the YouTube channels of the connected Google account (only the chosen ones when a choice was made), with id, title, handle, subscriber, view and video counts and the uploads playlist id.",
|
|
1872
|
+
inputSchema: { type: "object", properties: { cursor: { type: "string", description: "nextCursor from the previous result." } }, additionalProperties: false },
|
|
1873
|
+
async run(args, h) {
|
|
1874
|
+
const state = h.cursor(args.cursor);
|
|
1875
|
+
const pageToken = typeof state?.["p"] === "string" ? state["p"] : void 0;
|
|
1876
|
+
const skip = cursorNumber(state, "o", 0, 0, MAX_OFFSET);
|
|
1877
|
+
const { data } = await googleApi(h, {
|
|
1878
|
+
path: "/youtube/v3/channels",
|
|
1879
|
+
query: { part: "snippet,statistics,contentDetails", mine: true, maxResults: 50, pageToken }
|
|
1880
|
+
});
|
|
1881
|
+
const allowed = allowedAccounts(h.ctx.accounts, "channels");
|
|
1882
|
+
const channels = (Array.isArray(data?.items) ? data.items : []).map((channel) => trimChannel(channel, false)).filter((channel) => allowed === null || allowed.includes(String(channel["id"])));
|
|
1883
|
+
return h.page({
|
|
1884
|
+
key: "channels",
|
|
1885
|
+
items: channels.slice(skip),
|
|
1886
|
+
resumeAt: (index) => h.makeCursor({ ...pageToken ? { p: pageToken } : {}, o: skip + index }),
|
|
1887
|
+
...typeof data?.nextPageToken === "string" && data.nextPageToken ? { nextPage: h.makeCursor({ p: data.nextPageToken, o: 0 }) } : {}
|
|
1888
|
+
});
|
|
1889
|
+
}
|
|
1890
|
+
},
|
|
1891
|
+
{
|
|
1892
|
+
name: "get_channel",
|
|
1893
|
+
kind: "read",
|
|
1894
|
+
title: "Get a YouTube channel",
|
|
1895
|
+
description: "A channel's details and statistics: title, handle, description, country, subscribers, views, videos, keywords, uploads playlist id, audience setting and upload limits.",
|
|
1896
|
+
inputSchema: { type: "object", properties: { channel_id: CHANNEL_ID }, additionalProperties: false },
|
|
1897
|
+
async run(args, h) {
|
|
1898
|
+
const channelId = await resolveChannel(h, args.channel_id);
|
|
1899
|
+
const { data } = await googleApi(h, {
|
|
1900
|
+
path: "/youtube/v3/channels",
|
|
1901
|
+
query: { part: "snippet,statistics,contentDetails,brandingSettings,status", id: channelId }
|
|
1902
|
+
});
|
|
1903
|
+
const channel = Array.isArray(data?.items) ? data.items[0] : void 0;
|
|
1904
|
+
if (!channel) throw new ToolFailure(`YouTube found no channel ${channelId}.`);
|
|
1905
|
+
return trimChannel(channel, true);
|
|
1906
|
+
}
|
|
1907
|
+
},
|
|
1908
|
+
{
|
|
1909
|
+
name: "list_videos",
|
|
1910
|
+
kind: "read",
|
|
1911
|
+
title: "List YouTube channel videos",
|
|
1912
|
+
description: "Lists a channel's uploads, newest first, with each video's id, title, publish time, visibility (and scheduled time), duration, views, likes, comments, audience setting and link. Pass nextCursor back as cursor for older videos.",
|
|
1913
|
+
inputSchema: { type: "object", properties: { channel_id: CHANNEL_ID, page_size: PAGE_SIZE, cursor: CURSOR }, additionalProperties: false },
|
|
1914
|
+
async run(args, h) {
|
|
1915
|
+
const state = h.cursor(args.cursor);
|
|
1916
|
+
const skip = cursorNumber(state, "o", 0, 0, MAX_OFFSET);
|
|
1917
|
+
const size = cursorNumber(state, "n", args.page_size, 1, 50);
|
|
1918
|
+
const channelId = await resolveChannel(h, args.channel_id);
|
|
1919
|
+
const page = await uploadsPage(h, state, channelId, size);
|
|
1920
|
+
return h.page({
|
|
1921
|
+
key: "videos",
|
|
1922
|
+
items: page.videos.map(trimVideoSummary).slice(skip),
|
|
1923
|
+
extra: { channel_id: channelId },
|
|
1924
|
+
resumeAt: (index) => h.makeCursor({ u: page.uploads, ...page.pageToken ? { p: page.pageToken } : {}, o: skip + index, n: size }),
|
|
1925
|
+
...page.nextToken ? { nextPage: h.makeCursor({ u: page.uploads, p: page.nextToken, o: 0, n: size }) } : {}
|
|
1926
|
+
});
|
|
1927
|
+
}
|
|
1928
|
+
},
|
|
1929
|
+
{
|
|
1930
|
+
name: "get_videos",
|
|
1931
|
+
kind: "read",
|
|
1932
|
+
title: "Get YouTube videos",
|
|
1933
|
+
description: "Reads up to 50 videos by id: title, description, tags, category, languages, channel, visibility and scheduled time, upload and processing state, license, embedding, audience setting, synthetic-media label, duration, definition, captions, views, likes, comments and thumbnail. Ids YouTube does not know (or that are private to another account) are listed in not_found.",
|
|
1934
|
+
inputSchema: {
|
|
1935
|
+
type: "object",
|
|
1936
|
+
properties: {
|
|
1937
|
+
video_ids: { type: "array", items: { type: "string", pattern: "^[A-Za-z0-9_-]{11}$" }, minItems: 1, maxItems: 50, uniqueItems: true, description: "Video ids." },
|
|
1938
|
+
cursor: { type: "string", description: "nextCursor from the previous result (with the same video_ids)." }
|
|
1939
|
+
},
|
|
1940
|
+
required: ["video_ids"],
|
|
1941
|
+
additionalProperties: false
|
|
1942
|
+
},
|
|
1943
|
+
async run(args, h) {
|
|
1944
|
+
const state = h.cursor(args.cursor);
|
|
1945
|
+
const skip = cursorNumber(state, "o", 0, 0, MAX_OFFSET);
|
|
1946
|
+
await requireOwnChannel(h);
|
|
1947
|
+
const details = await videoDetails(h, args.video_ids);
|
|
1948
|
+
const found = args.video_ids.filter((id) => details.has(id));
|
|
1949
|
+
const missing = args.video_ids.filter((id) => !details.has(id));
|
|
1950
|
+
return h.page({
|
|
1951
|
+
key: "videos",
|
|
1952
|
+
items: found.map((id) => trimVideo(details.get(id))).slice(skip),
|
|
1953
|
+
...missing.length ? { extra: { not_found: missing } } : {},
|
|
1954
|
+
resumeAt: (index) => h.makeCursor({ o: skip + index })
|
|
1955
|
+
});
|
|
1956
|
+
}
|
|
1957
|
+
},
|
|
1958
|
+
{
|
|
1959
|
+
name: "search_videos",
|
|
1960
|
+
kind: "read",
|
|
1961
|
+
title: "Search the videos of a YouTube channel",
|
|
1962
|
+
description: "Searches a channel's public videos by words, sorted by relevance, date, views, rating or title, optionally in a time range. Each search costs 100 units of the daily YouTube quota (10,000 by default): prefer list_videos to browse. Pass nextCursor back as cursor for more.",
|
|
1963
|
+
inputSchema: {
|
|
1964
|
+
type: "object",
|
|
1965
|
+
properties: {
|
|
1966
|
+
channel_id: CHANNEL_ID,
|
|
1967
|
+
query: { type: "string", minLength: 1, maxLength: 500, description: "The words to search for. Leave out to list by order." },
|
|
1968
|
+
order: { type: "string", enum: ["relevance", "date", "viewCount", "rating", "title"], default: "relevance", description: "The order (default relevance)." },
|
|
1969
|
+
published_after: { type: "string", pattern: TIME, description: "Only videos published at or after this RFC 3339 time." },
|
|
1970
|
+
published_before: { type: "string", pattern: TIME, description: "Only videos published before this RFC 3339 time." },
|
|
1971
|
+
max_results: PAGE_SIZE,
|
|
1972
|
+
cursor: CURSOR
|
|
1973
|
+
},
|
|
1974
|
+
additionalProperties: false
|
|
1975
|
+
},
|
|
1976
|
+
async run(args, h) {
|
|
1977
|
+
const state = h.cursor(args.cursor);
|
|
1978
|
+
const pageToken = typeof state?.["p"] === "string" ? state["p"] : void 0;
|
|
1979
|
+
const skip = cursorNumber(state, "o", 0, 0, MAX_OFFSET);
|
|
1980
|
+
const size = cursorNumber(state, "n", args.max_results, 1, 50);
|
|
1981
|
+
const channelId = await resolveChannel(h, args.channel_id);
|
|
1982
|
+
const { data } = await googleApi(h, {
|
|
1983
|
+
path: "/youtube/v3/search",
|
|
1984
|
+
query: {
|
|
1985
|
+
part: "snippet",
|
|
1986
|
+
type: "video",
|
|
1987
|
+
channelId,
|
|
1988
|
+
q: args.query,
|
|
1989
|
+
order: args.order,
|
|
1990
|
+
publishedAfter: args.published_after ? utcTime(args.published_after, "published_after") : void 0,
|
|
1991
|
+
publishedBefore: args.published_before ? utcTime(args.published_before, "published_before") : void 0,
|
|
1992
|
+
maxResults: size,
|
|
1993
|
+
pageToken
|
|
1994
|
+
}
|
|
1995
|
+
});
|
|
1996
|
+
const videos = (Array.isArray(data?.items) ? data.items : []).map((item) => compact({
|
|
1997
|
+
id: item?.id?.videoId,
|
|
1998
|
+
title: text(item?.snippet?.title, 200),
|
|
1999
|
+
description: text(item?.snippet?.description, 300),
|
|
2000
|
+
published_at: item?.snippet?.publishedAt,
|
|
2001
|
+
url: typeof item?.id?.videoId === "string" ? `https://youtu.be/${item.id.videoId}` : void 0
|
|
2002
|
+
}));
|
|
2003
|
+
return h.page({
|
|
2004
|
+
key: "videos",
|
|
2005
|
+
items: videos.slice(skip),
|
|
2006
|
+
extra: compact({ channel_id: channelId, total_results: data?.pageInfo?.totalResults }),
|
|
2007
|
+
resumeAt: (index) => h.makeCursor({ ...pageToken ? { p: pageToken } : {}, o: skip + index, n: size }),
|
|
2008
|
+
...typeof data?.nextPageToken === "string" && data.nextPageToken ? { nextPage: h.makeCursor({ p: data.nextPageToken, o: 0, n: size }) } : {}
|
|
2009
|
+
});
|
|
2010
|
+
}
|
|
2011
|
+
},
|
|
2012
|
+
{
|
|
2013
|
+
name: "upload_video",
|
|
2014
|
+
kind: "create",
|
|
2015
|
+
check: "list_videos",
|
|
2016
|
+
title: "Upload a video to YouTube",
|
|
2017
|
+
description: "Uploads a video (regular or Short) from a public https URL to the connected channel, with its title, description, tags, category, languages, visibility or scheduled release, audience setting and synthetic-media label. A vertical or square video of 3 minutes or less becomes a Short. It goes through YouTube's resumable upload in parts, each read from the URL by byte range just before it is sent, for about 35 seconds a call: while done is false, call again with the same arguments and cursor set to nextCursor, until done is true and the video id and link come back. A host that does not pass byte ranges on gets the whole file, which must then fit its download limit (often 25 to 50 MB). Upload each video once: when the outcome is unclear, look for it with list_videos first.",
|
|
2018
|
+
inputSchema: {
|
|
2019
|
+
type: "object",
|
|
2020
|
+
properties: {
|
|
2021
|
+
video_url: { type: "string", format: "uri", pattern: "^https://", maxLength: 2e3, description: "A public https URL of the video file (MP4, MOV, WebM, AVI, FLV, WMV, MPEG or 3GP)." },
|
|
2022
|
+
...METADATA_FIELDS,
|
|
2023
|
+
category_id: { ...METADATA_FIELDS["category_id"], default: "22" },
|
|
2024
|
+
...STATUS_FIELDS,
|
|
2025
|
+
made_for_kids: { ...STATUS_FIELDS["made_for_kids"], default: false },
|
|
2026
|
+
embeddable: { ...STATUS_FIELDS["embeddable"], default: true },
|
|
2027
|
+
public_stats_viewable: { ...STATUS_FIELDS["public_stats_viewable"], default: true },
|
|
2028
|
+
license: { ...STATUS_FIELDS["license"], default: "youtube" },
|
|
2029
|
+
notify_subscribers: { type: "boolean", default: true, description: "Tell subscribers about the new video (default true)." },
|
|
2030
|
+
part_mb: {
|
|
2031
|
+
type: "integer",
|
|
2032
|
+
minimum: 1,
|
|
2033
|
+
maximum: MAX_PART_MB,
|
|
2034
|
+
default: DEFAULT_PART_MB,
|
|
2035
|
+
description: `The size of each part in MiB, 1 to ${MAX_PART_MB} (default ${DEFAULT_PART_MB}); an upload keeps the size it started with. Lower it when a part is refused as too large for the host or takes too long.`
|
|
2036
|
+
},
|
|
2037
|
+
cursor: {
|
|
2038
|
+
type: "string",
|
|
2039
|
+
maxLength: 4096,
|
|
2040
|
+
description: "nextCursor from the previous result, while done is false: goes on with that upload where YouTube stopped. Give the same video_url with it (the other details are not sent again). Leave out to start an upload."
|
|
2041
|
+
}
|
|
2042
|
+
},
|
|
2043
|
+
required: ["video_url", "title", "privacy_status", "contains_synthetic_media"],
|
|
2044
|
+
additionalProperties: false
|
|
2045
|
+
},
|
|
2046
|
+
async run(args, h) {
|
|
2047
|
+
const started = Date.now();
|
|
2048
|
+
const carried = h.cursor(args.cursor);
|
|
2049
|
+
if (carried) {
|
|
2050
|
+
const state2 = stateFromCursor(carried);
|
|
2051
|
+
if (!state2) throw new ToolFailure("The cursor holds no upload: pass nextCursor unchanged, or leave cursor out to start a new upload. Nothing was changed.");
|
|
2052
|
+
if (state2.source !== await sourceKey(args.video_url)) {
|
|
2053
|
+
throw new ToolFailure("The cursor belongs to an upload of another video_url: give the video_url it started with, or leave cursor out to start a new upload. Nothing was changed.");
|
|
2054
|
+
}
|
|
2055
|
+
await requireOwnChannel(h);
|
|
2056
|
+
return exclusive(state2, () => goOn(h, state2, args.video_url, started));
|
|
2057
|
+
}
|
|
2058
|
+
checkMetadata(args);
|
|
2059
|
+
let publishAt;
|
|
2060
|
+
if (args.publish_at !== void 0) {
|
|
2061
|
+
if (args.privacy_status !== "private") throw new ToolFailure("publish_at needs privacy_status private: YouTube makes the video public at that time. Nothing was changed.");
|
|
2062
|
+
publishAt = futureTime(args.publish_at);
|
|
2063
|
+
}
|
|
2064
|
+
await requireOwnChannel(h);
|
|
2065
|
+
const part = args.part_mb * MIB2;
|
|
2066
|
+
const readStarted = Date.now();
|
|
2067
|
+
let first;
|
|
2068
|
+
try {
|
|
2069
|
+
first = await readPart(h, args.video_url, 0, part - 1);
|
|
2070
|
+
} catch (error) {
|
|
2071
|
+
if (error instanceof SourceProblem) throw new ToolFailure(`${error.message} Nothing was changed.`);
|
|
2072
|
+
throw error;
|
|
2073
|
+
}
|
|
2074
|
+
const type = sniffVideo(first.bytes);
|
|
2075
|
+
if (!type) throw new ToolFailure("The video URL did not return a video file YouTube takes (MP4, MOV, WebM, AVI, FLV, WMV, MPEG or 3GP). Nothing was changed.");
|
|
2076
|
+
if (first.total > MAX_VIDEO_BYTES) {
|
|
2077
|
+
throw new ToolFailure(`The video is ${formatNumber(first.total)} bytes; YouTube takes files up to 256 GB. Nothing was changed.`);
|
|
2078
|
+
}
|
|
2079
|
+
const snippet = compact({
|
|
2080
|
+
title: args.title,
|
|
2081
|
+
description: args.description,
|
|
2082
|
+
tags: args.tags,
|
|
2083
|
+
categoryId: args.category_id,
|
|
2084
|
+
defaultLanguage: args.default_language,
|
|
2085
|
+
defaultAudioLanguage: args.default_audio_language
|
|
2086
|
+
});
|
|
2087
|
+
const status = compact({
|
|
2088
|
+
privacyStatus: args.privacy_status,
|
|
2089
|
+
publishAt,
|
|
2090
|
+
embeddable: args.embeddable,
|
|
2091
|
+
publicStatsViewable: args.public_stats_viewable,
|
|
2092
|
+
license: args.license,
|
|
2093
|
+
selfDeclaredMadeForKids: args.made_for_kids,
|
|
2094
|
+
containsSyntheticMedia: args.contains_synthetic_media
|
|
2095
|
+
});
|
|
2096
|
+
const session = await googleApi(h, {
|
|
2097
|
+
method: "POST",
|
|
2098
|
+
path: "/upload/youtube/v3/videos",
|
|
2099
|
+
query: { uploadType: "resumable", part: "snippet,status", notifySubscribers: args.notify_subscribers },
|
|
2100
|
+
headers: { "x-upload-content-type": type, "x-upload-content-length": String(first.total) },
|
|
2101
|
+
json: { snippet, status },
|
|
2102
|
+
errors: { 400: "YouTube did not accept the video details", 403: "YouTube refused the upload" }
|
|
2103
|
+
});
|
|
2104
|
+
const address = uploadAddress(session.headers.get("location"));
|
|
2105
|
+
if (!address) throw new ToolFailure("YouTube opened no upload address for the video. Nothing was changed.");
|
|
2106
|
+
const state = {
|
|
2107
|
+
session: address,
|
|
2108
|
+
total: first.total,
|
|
2109
|
+
part,
|
|
2110
|
+
type,
|
|
2111
|
+
source: await sourceKey(args.video_url),
|
|
2112
|
+
...first.etag ? { etag: first.etag } : {}
|
|
2113
|
+
};
|
|
2114
|
+
const cursor = h.makeCursor(cursorState(state));
|
|
2115
|
+
const outcome = await exclusive(state, () => transfer(h, { state, videoUrl: args.video_url, offset: 0, started, cursor, held: first, heldSince: readStarted }));
|
|
2116
|
+
return uploadResult(outcome, state, cursor);
|
|
2117
|
+
}
|
|
2118
|
+
},
|
|
2119
|
+
{
|
|
2120
|
+
name: "update_video",
|
|
2121
|
+
kind: "update",
|
|
2122
|
+
check: "get_videos",
|
|
2123
|
+
title: "Update a YouTube video",
|
|
2124
|
+
description: "Changes a video's title, description, tags, category, languages, visibility or scheduled release, audience setting, synthetic-media label, embedding, public statistics or license: only the fields given change (the others are read and sent back as they are, since YouTube resets what an update leaves out). privacy_status public publishes a private or unlisted video; private with publish_at schedules it. Returns the video as saved.",
|
|
2125
|
+
inputSchema: {
|
|
2126
|
+
type: "object",
|
|
2127
|
+
properties: { video_id: VIDEO_ID, ...METADATA_FIELDS, ...STATUS_FIELDS },
|
|
2128
|
+
required: ["video_id"],
|
|
2129
|
+
additionalProperties: false
|
|
2130
|
+
},
|
|
2131
|
+
async run(args, h) {
|
|
2132
|
+
const snippetKeys = ["title", "description", "tags", "category_id", "default_language", "default_audio_language"];
|
|
2133
|
+
const statusKeys = ["privacy_status", "publish_at", "made_for_kids", "contains_synthetic_media", "embeddable", "public_stats_viewable", "license"];
|
|
2134
|
+
const changesSnippet = snippetKeys.some((key) => args[key] !== void 0);
|
|
2135
|
+
const changesStatus = statusKeys.some((key) => args[key] !== void 0);
|
|
2136
|
+
if (!changesSnippet && !changesStatus) throw new ToolFailure("Nothing to change: give at least one field besides video_id. Nothing was changed.");
|
|
2137
|
+
checkMetadata(args);
|
|
2138
|
+
const publishAt = args.publish_at !== void 0 ? futureTime(args.publish_at) : void 0;
|
|
2139
|
+
const current = await readVideo(h, args.video_id, "snippet,status");
|
|
2140
|
+
requireAccounts(h.ctx.accounts, "channels", String(current?.snippet?.channelId ?? ""), "channel");
|
|
2141
|
+
const body = { id: args.video_id };
|
|
2142
|
+
const parts = [];
|
|
2143
|
+
if (changesSnippet) {
|
|
2144
|
+
const now = current.snippet ?? {};
|
|
2145
|
+
body["snippet"] = compact({
|
|
2146
|
+
title: args.title ?? now.title,
|
|
2147
|
+
categoryId: args.category_id ?? now.categoryId ?? "22",
|
|
2148
|
+
description: args.description ?? now.description,
|
|
2149
|
+
tags: args.tags ?? now.tags,
|
|
2150
|
+
defaultLanguage: args.default_language ?? now.defaultLanguage,
|
|
2151
|
+
defaultAudioLanguage: args.default_audio_language ?? now.defaultAudioLanguage
|
|
2152
|
+
});
|
|
2153
|
+
parts.push("snippet");
|
|
2154
|
+
}
|
|
2155
|
+
if (changesStatus) {
|
|
2156
|
+
const now = current.status ?? {};
|
|
2157
|
+
const privacy = publishAt ? args.privacy_status ?? "private" : args.privacy_status ?? now.privacyStatus;
|
|
2158
|
+
if (publishAt && privacy !== "private") throw new ToolFailure("publish_at needs privacy_status private: YouTube makes the video public at that time. Nothing was changed.");
|
|
2159
|
+
const keepSchedule = !publishAt && args.privacy_status === void 0 && privacy === "private" ? now.publishAt : void 0;
|
|
2160
|
+
body["status"] = compact({
|
|
2161
|
+
privacyStatus: privacy,
|
|
2162
|
+
publishAt: publishAt ?? keepSchedule,
|
|
2163
|
+
embeddable: args.embeddable ?? now.embeddable,
|
|
2164
|
+
publicStatsViewable: args.public_stats_viewable ?? now.publicStatsViewable,
|
|
2165
|
+
license: args.license ?? now.license,
|
|
2166
|
+
selfDeclaredMadeForKids: args.made_for_kids ?? now.selfDeclaredMadeForKids ?? now.madeForKids,
|
|
2167
|
+
containsSyntheticMedia: args.contains_synthetic_media ?? now.containsSyntheticMedia
|
|
2168
|
+
});
|
|
2169
|
+
parts.push("status");
|
|
2170
|
+
}
|
|
2171
|
+
const { data } = await googleApi(h, {
|
|
2172
|
+
method: "PUT",
|
|
2173
|
+
path: "/youtube/v3/videos",
|
|
2174
|
+
query: { part: parts.join(",") },
|
|
2175
|
+
json: body,
|
|
2176
|
+
write: true,
|
|
2177
|
+
errors: { 400: "YouTube did not accept the change", 403: "YouTube refused the change: the video must belong to the connected channel" }
|
|
2178
|
+
});
|
|
2179
|
+
const saved = trimVideo(data);
|
|
2180
|
+
const asked = args.privacy_status;
|
|
2181
|
+
if ((asked === "public" || asked === "unlisted") && saved["privacy_status"] === "private") {
|
|
2182
|
+
saved["warning"] = `YouTube kept the video private although ${asked} was asked: ${UPLOAD_NOTE.slice(UPLOAD_NOTE.indexOf("videos uploaded"))}`;
|
|
2183
|
+
}
|
|
2184
|
+
return saved;
|
|
2185
|
+
}
|
|
2186
|
+
},
|
|
2187
|
+
{
|
|
2188
|
+
name: "set_thumbnail",
|
|
2189
|
+
kind: "update",
|
|
2190
|
+
check: "get_videos",
|
|
2191
|
+
title: "Set a YouTube video thumbnail",
|
|
2192
|
+
description: "Sets a video's custom thumbnail from a public https URL of a JPEG or PNG image under 2 MB (1280 x 720 is best). The channel must be verified for custom thumbnails. Returns the thumbnail URLs.",
|
|
2193
|
+
inputSchema: {
|
|
2194
|
+
type: "object",
|
|
2195
|
+
properties: {
|
|
2196
|
+
video_id: VIDEO_ID,
|
|
2197
|
+
image_url: { type: "string", format: "uri", pattern: "^https://", maxLength: 2e3, description: "A public https URL of a JPEG or PNG image under 2 MB." }
|
|
2198
|
+
},
|
|
2199
|
+
required: ["video_id", "image_url"],
|
|
2200
|
+
additionalProperties: false
|
|
2201
|
+
},
|
|
2202
|
+
async run(args, h) {
|
|
2203
|
+
await requireOwnChannel(h);
|
|
2204
|
+
const { bytes } = await h.media(args.image_url, { what: "thumbnail image", maxBytes: MAX_THUMBNAIL_BYTES, accept: "image/jpeg,image/png" });
|
|
2205
|
+
const type = sniffImage(bytes);
|
|
2206
|
+
if (!type) throw new ToolFailure("The image URL did not return a JPEG or PNG image. Nothing was changed.");
|
|
2207
|
+
const { data } = await googleApi(h, {
|
|
2208
|
+
method: "POST",
|
|
2209
|
+
path: "/upload/youtube/v3/thumbnails/set",
|
|
2210
|
+
query: { videoId: args.video_id, uploadType: "media" },
|
|
2211
|
+
body: bytes,
|
|
2212
|
+
contentType: type,
|
|
2213
|
+
write: true,
|
|
2214
|
+
errors: {
|
|
2215
|
+
403: "YouTube refused the thumbnail: custom thumbnails need a verified channel and work only on its own videos",
|
|
2216
|
+
404: `YouTube found no video ${args.video_id} on the connected channel`
|
|
2217
|
+
}
|
|
2218
|
+
});
|
|
2219
|
+
const sizes = data?.items?.[0] ?? {};
|
|
2220
|
+
const thumbnails = compact(Object.fromEntries(["default", "medium", "high", "standard", "maxres"].map((size) => [size, sizes?.[size]?.url])));
|
|
2221
|
+
return { video_id: args.video_id, thumbnails };
|
|
2222
|
+
}
|
|
2223
|
+
},
|
|
2224
|
+
{
|
|
2225
|
+
name: "list_playlists",
|
|
2226
|
+
kind: "read",
|
|
2227
|
+
title: "List YouTube playlists",
|
|
2228
|
+
description: "Lists a channel's playlists with id, title, visibility, item count and link; the connected channel's private playlists too. Pass nextCursor back as cursor for more.",
|
|
2229
|
+
inputSchema: { type: "object", properties: { channel_id: CHANNEL_ID, page_size: PAGE_SIZE, cursor: CURSOR }, additionalProperties: false },
|
|
2230
|
+
async run(args, h) {
|
|
2231
|
+
const state = h.cursor(args.cursor);
|
|
2232
|
+
const pageToken = typeof state?.["p"] === "string" ? state["p"] : void 0;
|
|
2233
|
+
const skip = cursorNumber(state, "o", 0, 0, MAX_OFFSET);
|
|
2234
|
+
const size = cursorNumber(state, "n", args.page_size, 1, 50);
|
|
2235
|
+
const channelId = await resolveChannel(h, args.channel_id);
|
|
2236
|
+
const mine = channelId === await ownChannel(h);
|
|
2237
|
+
const { data } = await googleApi(h, {
|
|
2238
|
+
path: "/youtube/v3/playlists",
|
|
2239
|
+
query: { part: "snippet,contentDetails,status", ...mine ? { mine: true } : { channelId }, maxResults: size, pageToken }
|
|
2240
|
+
});
|
|
2241
|
+
const playlists = (Array.isArray(data?.items) ? data.items : []).map(trimPlaylist);
|
|
2242
|
+
return h.page({
|
|
2243
|
+
key: "playlists",
|
|
2244
|
+
items: playlists.slice(skip),
|
|
2245
|
+
extra: { channel_id: channelId },
|
|
2246
|
+
resumeAt: (index) => h.makeCursor({ ...pageToken ? { p: pageToken } : {}, o: skip + index, n: size }),
|
|
2247
|
+
...typeof data?.nextPageToken === "string" && data.nextPageToken ? { nextPage: h.makeCursor({ p: data.nextPageToken, o: 0, n: size }) } : {}
|
|
2248
|
+
});
|
|
2249
|
+
}
|
|
2250
|
+
},
|
|
2251
|
+
{
|
|
2252
|
+
name: "list_playlist_items",
|
|
2253
|
+
kind: "read",
|
|
2254
|
+
title: "List the videos of a YouTube playlist",
|
|
2255
|
+
description: "Lists the videos of a playlist in order, with each entry's item id, video id, title, position and visibility. Pass nextCursor back as cursor for more.",
|
|
2256
|
+
inputSchema: {
|
|
2257
|
+
type: "object",
|
|
2258
|
+
properties: { playlist_id: PLAYLIST_ID, page_size: PAGE_SIZE, cursor: CURSOR },
|
|
2259
|
+
required: ["playlist_id"],
|
|
2260
|
+
additionalProperties: false
|
|
2261
|
+
},
|
|
2262
|
+
async run(args, h) {
|
|
2263
|
+
const state = h.cursor(args.cursor);
|
|
2264
|
+
const pageToken = typeof state?.["p"] === "string" ? state["p"] : void 0;
|
|
2265
|
+
const skip = cursorNumber(state, "o", 0, 0, MAX_OFFSET);
|
|
2266
|
+
const size = cursorNumber(state, "n", args.page_size, 1, 50);
|
|
2267
|
+
await requireOwnChannel(h);
|
|
2268
|
+
const { data } = await googleApi(h, {
|
|
2269
|
+
path: "/youtube/v3/playlistItems",
|
|
2270
|
+
query: { part: "snippet,contentDetails,status", playlistId: args.playlist_id, maxResults: size, pageToken },
|
|
2271
|
+
errors: { 404: `YouTube found no playlist ${args.playlist_id}` }
|
|
2272
|
+
});
|
|
2273
|
+
const items = (Array.isArray(data?.items) ? data.items : []).map((item) => compact({
|
|
2274
|
+
item_id: item?.id,
|
|
2275
|
+
video_id: item?.contentDetails?.videoId ?? item?.snippet?.resourceId?.videoId,
|
|
2276
|
+
title: text(item?.snippet?.title, 200),
|
|
2277
|
+
position: item?.snippet?.position,
|
|
2278
|
+
published_at: item?.contentDetails?.videoPublishedAt,
|
|
2279
|
+
privacy_status: item?.status?.privacyStatus,
|
|
2280
|
+
owner_channel_id: item?.snippet?.videoOwnerChannelId
|
|
2281
|
+
}));
|
|
2282
|
+
return h.page({
|
|
2283
|
+
key: "items",
|
|
2284
|
+
items: items.slice(skip),
|
|
2285
|
+
extra: { playlist_id: args.playlist_id },
|
|
2286
|
+
resumeAt: (index) => h.makeCursor({ ...pageToken ? { p: pageToken } : {}, o: skip + index, n: size }),
|
|
2287
|
+
...typeof data?.nextPageToken === "string" && data.nextPageToken ? { nextPage: h.makeCursor({ p: data.nextPageToken, o: 0, n: size }) } : {}
|
|
2288
|
+
});
|
|
2289
|
+
}
|
|
2290
|
+
},
|
|
2291
|
+
{
|
|
2292
|
+
name: "create_playlist",
|
|
2293
|
+
kind: "create",
|
|
2294
|
+
check: "list_playlists",
|
|
2295
|
+
title: "Create a YouTube playlist",
|
|
2296
|
+
description: "Creates a playlist on the connected channel (private unless told otherwise). Returns its id and link.",
|
|
2297
|
+
inputSchema: {
|
|
2298
|
+
type: "object",
|
|
2299
|
+
properties: {
|
|
2300
|
+
title: { type: "string", minLength: 1, maxLength: 150, description: "The playlist title." },
|
|
2301
|
+
description: { type: "string", maxLength: 5e3, description: "The playlist description." },
|
|
2302
|
+
privacy_status: { type: "string", enum: PRIVACY, default: "private", description: "public, unlisted or private (default)." },
|
|
2303
|
+
default_language: { ...LANGUAGE, description: "The language of the title and description." }
|
|
2304
|
+
},
|
|
2305
|
+
required: ["title"],
|
|
2306
|
+
additionalProperties: false
|
|
2307
|
+
},
|
|
2308
|
+
async run(args, h) {
|
|
2309
|
+
if (/[<>]/.test(args.title) || /[<>]/.test(args.description ?? "")) throw new ToolFailure("The title and description may not contain < or >. Nothing was changed.");
|
|
2310
|
+
await requireOwnChannel(h);
|
|
2311
|
+
const { data } = await googleApi(h, {
|
|
2312
|
+
method: "POST",
|
|
2313
|
+
path: "/youtube/v3/playlists",
|
|
2314
|
+
query: { part: "snippet,status" },
|
|
2315
|
+
json: {
|
|
2316
|
+
snippet: compact({ title: args.title, description: args.description, defaultLanguage: args.default_language }),
|
|
2317
|
+
status: { privacyStatus: args.privacy_status }
|
|
2318
|
+
},
|
|
2319
|
+
write: true
|
|
2320
|
+
});
|
|
2321
|
+
return trimPlaylist(data);
|
|
2322
|
+
}
|
|
2323
|
+
},
|
|
2324
|
+
{
|
|
2325
|
+
name: "add_to_playlist",
|
|
2326
|
+
kind: "create",
|
|
2327
|
+
check: "list_playlist_items",
|
|
2328
|
+
title: "Add a video to a YouTube playlist",
|
|
2329
|
+
description: "Adds a video to one of the connected channel's playlists, at the end or at a position (0 is first). Returns the new playlist item.",
|
|
2330
|
+
inputSchema: {
|
|
2331
|
+
type: "object",
|
|
2332
|
+
properties: {
|
|
2333
|
+
playlist_id: PLAYLIST_ID,
|
|
2334
|
+
video_id: VIDEO_ID,
|
|
2335
|
+
position: { type: "integer", minimum: 0, maximum: 4999, description: "Where in the playlist, 0 first. Leave out to add at the end." }
|
|
2336
|
+
},
|
|
2337
|
+
required: ["playlist_id", "video_id"],
|
|
2338
|
+
additionalProperties: false
|
|
2339
|
+
},
|
|
2340
|
+
async run(args, h) {
|
|
2341
|
+
await requireOwnChannel(h);
|
|
2342
|
+
const { data } = await googleApi(h, {
|
|
2343
|
+
method: "POST",
|
|
2344
|
+
path: "/youtube/v3/playlistItems",
|
|
2345
|
+
query: { part: "snippet" },
|
|
2346
|
+
json: {
|
|
2347
|
+
snippet: {
|
|
2348
|
+
playlistId: args.playlist_id,
|
|
2349
|
+
resourceId: { kind: "youtube#video", videoId: args.video_id },
|
|
2350
|
+
...args.position !== void 0 ? { position: args.position } : {}
|
|
2351
|
+
}
|
|
2352
|
+
},
|
|
2353
|
+
write: true,
|
|
2354
|
+
errors: { 404: "YouTube found no such playlist or video", 403: "YouTube refused: the playlist must belong to the connected channel" }
|
|
2355
|
+
});
|
|
2356
|
+
return compact({ item_id: data?.id, playlist_id: data?.snippet?.playlistId ?? args.playlist_id, video_id: data?.snippet?.resourceId?.videoId ?? args.video_id, position: data?.snippet?.position });
|
|
2357
|
+
}
|
|
2358
|
+
},
|
|
2359
|
+
{
|
|
2360
|
+
name: "get_analytics_report",
|
|
2361
|
+
kind: "read",
|
|
2362
|
+
title: "Get a YouTube Analytics report",
|
|
2363
|
+
description: "Runs a YouTube Analytics report for a channel and a date range: a ready report (top_videos, daily, retention for one video, traffic_sources, countries, devices, demographics; daily when neither report nor metrics is given) or your own metrics, dimensions, filters and sort. Rows come back as objects keyed by column; rows by video also carry the title. The latest two or three days may be missing. Pass nextCursor back as cursor for more rows.",
|
|
2364
|
+
inputSchema: {
|
|
2365
|
+
type: "object",
|
|
2366
|
+
properties: {
|
|
2367
|
+
channel_id: CHANNEL_ID,
|
|
2368
|
+
start_date: { ...DATE, description: "First day, YYYY-MM-DD." },
|
|
2369
|
+
end_date: { ...DATE, description: "Last day, YYYY-MM-DD." },
|
|
2370
|
+
report: { type: "string", enum: Object.keys(REPORTS), description: "A ready report. Leave out to give metrics (and dimensions) yourself; with neither, daily." },
|
|
2371
|
+
video_id: { ...VIDEO_ID, description: "One video: required for retention; with another report, only this video's data." },
|
|
2372
|
+
metrics: { type: "array", items: { type: "string", pattern: "^[A-Za-z][A-Za-z0-9]{0,63}$" }, minItems: 1, maxItems: 20, uniqueItems: true, description: `Your own report's metrics, such as ["views", "estimatedMinutesWatched", "likes"].` },
|
|
2373
|
+
dimensions: { type: "array", items: { type: "string", pattern: "^[A-Za-z][A-Za-z0-9]{0,63}$" }, maxItems: 5, uniqueItems: true, description: `Your own report's dimensions, such as ["day"], ["video"] or ["country"].` },
|
|
2374
|
+
filters: { type: "string", maxLength: 2e3, pattern: "^[A-Za-z0-9=,;:_.\\-]+$", description: `Your own report's filters, such as "video==VIDEO_ID" or "country==US".` },
|
|
2375
|
+
sort: { type: "string", maxLength: 200, pattern: "^-?[A-Za-z0-9]+(,-?[A-Za-z0-9]+)*$", description: `Your own report's sort, such as "-views"; a minus sorts high to low.` },
|
|
2376
|
+
max_results: { type: "integer", minimum: 1, maximum: 200, description: "Rows per page (top video reports allow up to 200)." },
|
|
2377
|
+
cursor: { type: "string", description: "nextCursor from the previous result (with the same report)." }
|
|
2378
|
+
},
|
|
2379
|
+
required: ["start_date", "end_date"],
|
|
2380
|
+
additionalProperties: false
|
|
2381
|
+
},
|
|
2382
|
+
async run(args, h) {
|
|
2383
|
+
const state = h.cursor(args.cursor);
|
|
2384
|
+
const startIndex = cursorNumber(state, "i", 1, 1, 1e6);
|
|
2385
|
+
const skip = cursorNumber(state, "o", 0, 0, MAX_OFFSET);
|
|
2386
|
+
if (args.report && (args.metrics || args.dimensions || args.filters || args.sort)) {
|
|
2387
|
+
throw new ToolFailure("Give either report or your own metrics, dimensions, filters and sort, not both. Nothing was sent.");
|
|
2388
|
+
}
|
|
2389
|
+
const name2 = args.report ?? (args.metrics?.length ? void 0 : "daily");
|
|
2390
|
+
const preset = name2 ? REPORTS[name2] : void 0;
|
|
2391
|
+
if (!preset && !args.metrics?.length) throw new ToolFailure("Give metrics for your own report, or pick a ready report. Nothing was sent.");
|
|
2392
|
+
if (preset?.needsVideo && !args.video_id) throw new ToolFailure(`The ${name2} report needs video_id. Nothing was sent.`);
|
|
2393
|
+
const channelId = await resolveChannel(h, args.channel_id);
|
|
2394
|
+
const filters = preset ? args.video_id ? `video==${args.video_id}` : void 0 : [args.filters, args.video_id ? `video==${args.video_id}` : void 0].filter(Boolean).join(";") || void 0;
|
|
2395
|
+
const maxResults = args.max_results ?? preset?.maxResults;
|
|
2396
|
+
const dimensions = preset ? preset.dimensions : args.dimensions ?? [];
|
|
2397
|
+
const { data } = await googleApi(h, {
|
|
2398
|
+
origin: ANALYTICS,
|
|
2399
|
+
path: "/v2/reports",
|
|
2400
|
+
query: {
|
|
2401
|
+
ids: `channel==${channelId}`,
|
|
2402
|
+
startDate: args.start_date,
|
|
2403
|
+
endDate: args.end_date,
|
|
2404
|
+
metrics: (preset ? preset.metrics : args.metrics ?? []).join(","),
|
|
2405
|
+
dimensions: dimensions.length ? dimensions.join(",") : void 0,
|
|
2406
|
+
filters,
|
|
2407
|
+
sort: preset ? preset.sort : args.sort,
|
|
2408
|
+
maxResults,
|
|
2409
|
+
startIndex: maxResults ? startIndex : void 0
|
|
2410
|
+
},
|
|
2411
|
+
errors: { 400: "YouTube Analytics did not accept the report: check the metrics, dimensions and filters together" }
|
|
2412
|
+
});
|
|
2413
|
+
const columns = (Array.isArray(data?.columnHeaders) ? data.columnHeaders : []).map((header) => String(header?.name));
|
|
2414
|
+
const rows = (Array.isArray(data?.rows) ? data.rows : []).map((row) => Object.fromEntries(columns.map((name3, index) => [name3, row?.[index]])));
|
|
2415
|
+
if (columns.includes("video") && rows.length) {
|
|
2416
|
+
const ids = [...new Set(rows.map((row) => String(row["video"])))].slice(0, 50);
|
|
2417
|
+
try {
|
|
2418
|
+
const details = await videoDetails(h, ids);
|
|
2419
|
+
for (const row of rows) {
|
|
2420
|
+
const title = text(details.get(String(row["video"]))?.snippet?.title, 200);
|
|
2421
|
+
if (title) row["title"] = title;
|
|
2422
|
+
}
|
|
2423
|
+
} catch (error) {
|
|
2424
|
+
if (!(error instanceof ToolFailure)) throw error;
|
|
2425
|
+
}
|
|
2426
|
+
}
|
|
2427
|
+
const more = maxResults !== void 0 && rows.length >= maxResults;
|
|
2428
|
+
return h.page({
|
|
2429
|
+
key: "rows",
|
|
2430
|
+
items: rows.slice(skip),
|
|
2431
|
+
extra: { channel_id: channelId, start_date: args.start_date, end_date: args.end_date, columns },
|
|
2432
|
+
resumeAt: (index) => h.makeCursor({ i: startIndex, o: skip + index }),
|
|
2433
|
+
...more ? { nextPage: h.makeCursor({ i: startIndex + rows.length, o: 0 }) } : {}
|
|
2434
|
+
});
|
|
2435
|
+
}
|
|
2436
|
+
},
|
|
2437
|
+
{
|
|
2438
|
+
name: "screen_videos_for_ads",
|
|
2439
|
+
kind: "read",
|
|
2440
|
+
title: "Screen YouTube videos for video ads",
|
|
2441
|
+
description: "Checks a channel's uploads for use in video ad campaigns: public or unlisted, not made for kids, enough views, a length that fits the ad format (bumper up to 6 s, non_skippable up to 15 s, skippable 12 s to 3 min) and, from Analytics, an average view percentage over the last days. Each video comes back with eligible and the reasons it is not. Pass nextCursor back as cursor for older uploads.",
|
|
2442
|
+
inputSchema: {
|
|
2443
|
+
type: "object",
|
|
2444
|
+
properties: {
|
|
2445
|
+
channel_id: CHANNEL_ID,
|
|
2446
|
+
ad_format: { type: "string", enum: Object.keys(AD_FORMATS), default: "any", description: "any (default), bumper, non_skippable or skippable." },
|
|
2447
|
+
min_views: { type: "integer", minimum: 0, default: 1e3, description: "Fewest views (default 1,000)." },
|
|
2448
|
+
min_view_percentage: { type: "number", minimum: 0, maximum: 100, default: 40, description: "Lowest average view percentage (default 40)." },
|
|
2449
|
+
days: { type: "integer", minimum: 0, maximum: 365, default: 90, description: "Days of Analytics for the view percentage (default 90); 0 skips it." },
|
|
2450
|
+
page_size: { ...PAGE_SIZE, default: 50, description: "Uploads per page, 1 to 50 (default 50)." },
|
|
2451
|
+
cursor: CURSOR
|
|
2452
|
+
},
|
|
2453
|
+
additionalProperties: false
|
|
2454
|
+
},
|
|
2455
|
+
async run(args, h) {
|
|
2456
|
+
const state = h.cursor(args.cursor);
|
|
2457
|
+
const skip = cursorNumber(state, "o", 0, 0, MAX_OFFSET);
|
|
2458
|
+
const size = cursorNumber(state, "n", args.page_size, 1, 50);
|
|
2459
|
+
const format = AD_FORMATS[args.ad_format];
|
|
2460
|
+
const channelId = await resolveChannel(h, args.channel_id);
|
|
2461
|
+
const page = await uploadsPage(h, state, channelId, size);
|
|
2462
|
+
const retention = /* @__PURE__ */ new Map();
|
|
2463
|
+
let note;
|
|
2464
|
+
if (args.days > 0 && page.videos.length) {
|
|
2465
|
+
try {
|
|
2466
|
+
const { data } = await googleApi(h, {
|
|
2467
|
+
origin: ANALYTICS,
|
|
2468
|
+
path: "/v2/reports",
|
|
2469
|
+
query: {
|
|
2470
|
+
ids: `channel==${channelId}`,
|
|
2471
|
+
startDate: day(args.days),
|
|
2472
|
+
endDate: day(0),
|
|
2473
|
+
metrics: "views,averageViewPercentage",
|
|
2474
|
+
dimensions: "video",
|
|
2475
|
+
filters: `video==${page.videos.map((video) => video.id).join(",")}`,
|
|
2476
|
+
sort: "-views",
|
|
2477
|
+
maxResults: 50
|
|
2478
|
+
}
|
|
2479
|
+
});
|
|
2480
|
+
const columns = (Array.isArray(data?.columnHeaders) ? data.columnHeaders : []).map((header) => String(header?.name));
|
|
2481
|
+
const videoAt = columns.indexOf("video");
|
|
2482
|
+
const percentAt = columns.indexOf("averageViewPercentage");
|
|
2483
|
+
for (const row of Array.isArray(data?.rows) ? data.rows : []) {
|
|
2484
|
+
if (videoAt >= 0 && percentAt >= 0 && typeof row?.[percentAt] === "number") retention.set(String(row[videoAt]), row[percentAt]);
|
|
2485
|
+
}
|
|
2486
|
+
} catch (error) {
|
|
2487
|
+
if (!(error instanceof ToolFailure)) throw error;
|
|
2488
|
+
note = `The view percentage could not be read from YouTube Analytics, so it was not checked: ${error.message}`;
|
|
2489
|
+
}
|
|
2490
|
+
}
|
|
2491
|
+
const videos = page.videos.map((video) => {
|
|
2492
|
+
const summary = trimVideoSummary(video);
|
|
2493
|
+
const reasons = [];
|
|
2494
|
+
const privacy = String(summary["privacy_status"] ?? "unknown");
|
|
2495
|
+
if (privacy !== "public" && privacy !== "unlisted") reasons.push(`it is ${privacy}`);
|
|
2496
|
+
if (summary["made_for_kids"] === true) reasons.push("it is made for kids");
|
|
2497
|
+
const views = typeof summary["views"] === "number" ? summary["views"] : 0;
|
|
2498
|
+
if (views < args.min_views) reasons.push(`${formatNumber(views)} views, fewer than ${formatNumber(args.min_views)}`);
|
|
2499
|
+
const seconds = summary["duration_seconds"];
|
|
2500
|
+
if (typeof seconds === "number" && (format.min !== void 0 && seconds < format.min || format.max !== void 0 && seconds > format.max)) {
|
|
2501
|
+
reasons.push(`${seconds} s long; ${args.ad_format} needs ${format.words}`);
|
|
2502
|
+
}
|
|
2503
|
+
const percent = retention.get(String(summary["id"]));
|
|
2504
|
+
if (percent !== void 0 && percent < args.min_view_percentage) reasons.push(`average view percentage ${percent}, below ${args.min_view_percentage}`);
|
|
2505
|
+
return compact({
|
|
2506
|
+
id: summary["id"],
|
|
2507
|
+
title: summary["title"],
|
|
2508
|
+
duration_seconds: seconds,
|
|
2509
|
+
views,
|
|
2510
|
+
privacy_status: privacy,
|
|
2511
|
+
made_for_kids: summary["made_for_kids"],
|
|
2512
|
+
average_view_percentage: percent,
|
|
2513
|
+
eligible: reasons.length === 0,
|
|
2514
|
+
reasons: reasons.length ? reasons : void 0,
|
|
2515
|
+
url: summary["url"]
|
|
2516
|
+
});
|
|
2517
|
+
});
|
|
2518
|
+
return h.page({
|
|
2519
|
+
key: "videos",
|
|
2520
|
+
items: videos.slice(skip),
|
|
2521
|
+
extra: compact({
|
|
2522
|
+
channel_id: channelId,
|
|
2523
|
+
criteria: { ad_format: args.ad_format, length: format.words, min_views: args.min_views, min_view_percentage: args.days > 0 ? args.min_view_percentage : void 0 },
|
|
2524
|
+
note
|
|
2525
|
+
}),
|
|
2526
|
+
resumeAt: (index) => h.makeCursor({ u: page.uploads, ...page.pageToken ? { p: page.pageToken } : {}, o: skip + index, n: size }),
|
|
2527
|
+
...page.nextToken ? { nextPage: h.makeCursor({ u: page.uploads, p: page.nextToken, o: 0, n: size }) } : {}
|
|
2528
|
+
});
|
|
2529
|
+
}
|
|
2530
|
+
},
|
|
2531
|
+
// The rest of the YouTube Data and Analytics APIs: deletes, playlist changes, channel settings.
|
|
2532
|
+
...apiTools({
|
|
2533
|
+
label: "YouTube",
|
|
2534
|
+
description: "The YouTube Data API v3 on https://www.googleapis.com (paths start with /youtube/v3/, such as /youtube/v3/videos with id in query to delete a video, /youtube/v3/playlistItems with id to take a video out of a playlist, or /youtube/v3/channels with part=brandingSettings) and the YouTube Analytics API v2 on https://youtubeanalytics.googleapis.com (/v2/reports with ids=channel==CHANNEL_ID). Comments and captions need a token with the youtube.force-ssl scope. With a channel choice in place, the connected channel and any channel a request names must be chosen. Reference: https://developers.google.com/youtube/v3/docs.",
|
|
2535
|
+
originArgument: "The API host: https://www.googleapis.com (default) or https://youtubeanalytics.googleapis.com.",
|
|
2536
|
+
methods: ["POST", "PUT", "DELETE"],
|
|
2537
|
+
guard,
|
|
2538
|
+
send: (request, h) => googleApi(h, request)
|
|
2539
|
+
})
|
|
2540
|
+
]
|
|
2541
|
+
});
|
|
2542
|
+
module.exports = connector;
|