@botconnector/bccli 0.4.0-beta.8 → 0.4.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/README.en.md +242 -0
- package/README.md +95 -3
- package/dist/acp-ATIL4JOZ.js +182 -0
- package/dist/args-J5ONVGIF.js +13 -0
- package/dist/chunk-45SDLMTV.js +341 -0
- package/dist/chunk-6M5X2KZE.js +8 -0
- package/dist/chunk-7F3IWBPQ.js +191 -0
- package/dist/{chunk-CLN4Z5E3.js → chunk-BLOYFIAD.js} +6 -3
- package/dist/chunk-BNA74HPN.js +145 -0
- package/dist/{chunk-DX7CZTBB.js → chunk-BQ2IGPBR.js} +14 -9
- package/dist/chunk-JL5ZCSP2.js +76 -0
- package/dist/chunk-KEMYIGCP.js +235 -0
- package/dist/{chunk-BFZXRKW5.js → chunk-L7QI6JN2.js} +24 -2
- package/dist/chunk-LACUWBWS.js +361 -0
- package/dist/chunk-M7CALSP3.js +733 -0
- package/dist/{chunk-ELML4KVQ.js → chunk-O7M3TGIW.js} +34 -2
- package/dist/chunk-PSO7R5AD.js +10 -0
- package/dist/chunk-PUN4HMAG.js +940 -0
- package/dist/{chunk-SJH3YLW4.js → chunk-QDQU6VY2.js} +60 -6
- package/dist/chunk-QZKLZELZ.js +64 -0
- package/dist/{chunk-7S6JXQCH.js → chunk-SPRNLS7K.js} +2 -1
- package/dist/chunk-TLPFQIS2.js +231 -0
- package/dist/chunk-TVALKHFB.js +2143 -0
- package/dist/chunk-UZWJQF67.js +500 -0
- package/dist/chunk-XBO5GACQ.js +56 -0
- package/dist/cli.js +162 -1383
- package/dist/completion-HPPFDAPB.js +125 -0
- package/dist/{config-YUNKPCNB.js → config-COPNMMV6.js} +5 -2
- package/dist/config-RZ5JONMX.js +30 -0
- package/dist/ghBotCli-IBCZIWT5.js +677 -0
- package/dist/integrationCli-P75R2VSC.js +685 -0
- package/dist/login-SYIQP46J.js +16 -0
- package/dist/{mcpCli-DZWQPTOS.js → mcpCli-QUV5SD64.js} +42 -9
- package/dist/modelsCli-TRRB5LX4.js +36 -0
- package/dist/npmRunner-LU43GM3W.js +46 -0
- package/dist/oauthLogin-6FWQABJ7.js +210 -0
- package/dist/pluginsCli-GNW4TPVV.js +284 -0
- package/dist/prCli-5IMV3VNQ.js +78 -0
- package/dist/providerCli-FAOZHOKW.js +15 -0
- package/dist/sdk.js +5490 -0
- package/dist/serve-6QLBJUYW.js +178 -0
- package/dist/serve-JG7RLIUD.js +515 -0
- package/dist/session-KBAQ4BZ5.js +12 -0
- package/dist/setup-FJAWDWV4.js +24 -0
- package/dist/statsCli-CF3R7ATL.js +353 -0
- package/dist/transferCli-TK2GSVRK.js +71 -0
- package/dist/ui-B3CJ6TGE.js +2365 -0
- package/dist/update-K5IQ2MYR.js +145 -0
- package/package.json +25 -4
- package/dist/args-FLTRM57K.js +0 -12
- package/dist/chunk-2MGINW4O.js +0 -114
- package/dist/chunk-IM3KMPVZ.js +0 -52
- package/dist/chunk-KV27KTOX.js +0 -254
- package/dist/chunk-U7GK73CK.js +0 -341
- package/dist/chunk-Z7PM3LTC.js +0 -93
- package/dist/login-JXFORO3J.js +0 -9
- package/dist/providerCli-Q7LRM2NP.js +0 -12
- package/dist/session-7UB77CEG.js +0 -9
- package/dist/ui-6GTQUJOE.js +0 -1415
|
@@ -0,0 +1,341 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import {
|
|
3
|
+
defineTool
|
|
4
|
+
} from "./chunk-PSO7R5AD.js";
|
|
5
|
+
import {
|
|
6
|
+
t
|
|
7
|
+
} from "./chunk-UZWJQF67.js";
|
|
8
|
+
|
|
9
|
+
// src/tools/websearch.ts
|
|
10
|
+
import { z } from "zod";
|
|
11
|
+
var clean = (items, max) => (Array.isArray(items) ? items : []).filter((r) => typeof r?.url === "string" && /^https?:\/\//.test(r.url)).slice(0, max).map((r) => ({
|
|
12
|
+
title: String(r.title || r.url).slice(0, 200),
|
|
13
|
+
url: r.url,
|
|
14
|
+
snippet: String(r.snippet || r.description || "").replace(/\s+/g, " ").trim().slice(0, 600)
|
|
15
|
+
}));
|
|
16
|
+
async function postJson(url, body, headers, signal) {
|
|
17
|
+
const res = await fetch(url, {
|
|
18
|
+
method: "POST",
|
|
19
|
+
headers: { "content-type": "application/json", ...headers },
|
|
20
|
+
body: JSON.stringify(body),
|
|
21
|
+
signal: AbortSignal.any([signal, AbortSignal.timeout(3e4)])
|
|
22
|
+
});
|
|
23
|
+
if (!res.ok) throw new Error(`HTTP ${res.status}`);
|
|
24
|
+
return res.json();
|
|
25
|
+
}
|
|
26
|
+
function createWebSearchTool(opts) {
|
|
27
|
+
const keenableURL = opts.keenableURL ?? "https://api.keenable.ai/v1/search/public";
|
|
28
|
+
return defineTool({
|
|
29
|
+
name: "web_search",
|
|
30
|
+
description: "Search the web. Returns titles, URLs and short snippets. Use it to find the right pages instead of guessing URLs; then fetch a result URL when you need the full page.",
|
|
31
|
+
schema: z.object({
|
|
32
|
+
query: z.string().min(1).max(500).describe("Search query"),
|
|
33
|
+
max_results: z.number().int().min(1).max(10).optional().describe("Number of results (default 6)")
|
|
34
|
+
}),
|
|
35
|
+
kind: "read",
|
|
36
|
+
target: (input) => input.query,
|
|
37
|
+
parallelSafe: () => true,
|
|
38
|
+
async run(input, ctx) {
|
|
39
|
+
const max = input.max_results ?? 6;
|
|
40
|
+
const errors = [];
|
|
41
|
+
let results = [];
|
|
42
|
+
const bc = opts.botconnector();
|
|
43
|
+
if (bc) {
|
|
44
|
+
try {
|
|
45
|
+
const data = await postJson(`${bc.baseURL.replace(/\/+$/, "")}/web/search`, { query: input.query, max_results: max }, { authorization: `Bearer ${bc.apiKey}` }, ctx.signal);
|
|
46
|
+
results = clean(data.results, max);
|
|
47
|
+
} catch (error) {
|
|
48
|
+
errors.push(`BotConnector: ${error.message}`);
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
if (!results.length) {
|
|
52
|
+
try {
|
|
53
|
+
const data = await postJson(keenableURL, { query: input.query }, { "x-keenable-title": "BotConnector" }, ctx.signal);
|
|
54
|
+
results = clean(data.results, max);
|
|
55
|
+
} catch (error) {
|
|
56
|
+
errors.push(`Keenable: ${error.message}`);
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
if (!results.length) {
|
|
60
|
+
return { output: errors.length ? `Web search failed (${errors.join("; ")}).` : "No results.", isError: errors.length > 0 };
|
|
61
|
+
}
|
|
62
|
+
const output = results.map((r, i) => `${i + 1}. ${r.title}
|
|
63
|
+
${r.url}${r.snippet ? `
|
|
64
|
+
${r.snippet}` : ""}`).join("\n");
|
|
65
|
+
return { output, display: t("{n} results", { n: results.length }) };
|
|
66
|
+
}
|
|
67
|
+
});
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
// src/tools/fetch.ts
|
|
71
|
+
import { lookup as dnsCbLookup } from "dns";
|
|
72
|
+
import { lookup as dnsLookup } from "dns/promises";
|
|
73
|
+
import { isIP } from "net";
|
|
74
|
+
import { Agent, fetch as undiciFetch } from "undici";
|
|
75
|
+
import { z as z2 } from "zod";
|
|
76
|
+
var MAX_CHARS = 12e3;
|
|
77
|
+
var FOCUS_CHUNKS = 3;
|
|
78
|
+
var FOCUS_SIZE = 800;
|
|
79
|
+
var CACHE_MAX = 16;
|
|
80
|
+
var CACHE_TTL_MS = 15 * 6e4;
|
|
81
|
+
var CACHE_MAX_CHARS = 2e6;
|
|
82
|
+
var MAX_BYTES = 5 * 1024 * 1024;
|
|
83
|
+
async function readCapped(res) {
|
|
84
|
+
const reader = res.body?.getReader();
|
|
85
|
+
if (!reader) return { text: "", truncated: false };
|
|
86
|
+
const chunks = [];
|
|
87
|
+
let size = 0;
|
|
88
|
+
for (; ; ) {
|
|
89
|
+
const { done, value } = await reader.read();
|
|
90
|
+
if (done) return { text: Buffer.concat(chunks).toString("utf8"), truncated: false };
|
|
91
|
+
size += value.length;
|
|
92
|
+
if (size > MAX_BYTES) {
|
|
93
|
+
chunks.push(value.subarray(0, value.length - (size - MAX_BYTES)));
|
|
94
|
+
await reader.cancel();
|
|
95
|
+
return { text: Buffer.concat(chunks).toString("utf8"), truncated: true };
|
|
96
|
+
}
|
|
97
|
+
chunks.push(value);
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
function htmlToText(html) {
|
|
101
|
+
return html.replace(/<(script|style|noscript)[\s\S]*?<\/\1>/gi, "").replace(/<(br|\/p|\/div|\/h[1-6]|\/li|\/tr)\s*\/?>/gi, "\n").replace(/<[^>]+>/g, "").replace(/ /g, " ").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, '"').replace(/'/g, "'").replace(/&/g, "&").split("\n").map((l) => l.replace(/\s+/g, " ").trim()).filter(Boolean).join("\n");
|
|
102
|
+
}
|
|
103
|
+
function describeFetchError(error) {
|
|
104
|
+
const cause = error.cause;
|
|
105
|
+
const code = cause?.code ?? "";
|
|
106
|
+
const detail = cause?.message ?? error.message;
|
|
107
|
+
if (error.name === "TimeoutError") return "no response within 30 seconds";
|
|
108
|
+
if (code === "ENOTFOUND" || code === "EAI_AGAIN") return `${detail} \u2014 DNS could not find the host (typo, offline, or blocked by DNS/ISP)`;
|
|
109
|
+
if (/CERT|SELF_SIGNED|UNABLE_TO/.test(code)) {
|
|
110
|
+
return `${detail} \u2014 TLS certificate rejected; often caused by an antivirus or proxy that inspects HTTPS. Try running with NODE_OPTIONS=--use-system-ca`;
|
|
111
|
+
}
|
|
112
|
+
if (/ECONNRESET|ECONNREFUSED|ETIMEDOUT|EHOSTUNREACH|ENETUNREACH|UND_ERR_CONNECT_TIMEOUT|UND_ERR_SOCKET/.test(code)) {
|
|
113
|
+
return `${detail} \u2014 connection failed (firewall, proxy, or the site is blocked by the network)`;
|
|
114
|
+
}
|
|
115
|
+
return code ? `${detail} (${code})` : detail;
|
|
116
|
+
}
|
|
117
|
+
var tokensOf = (text) => Math.ceil(text.length / 4);
|
|
118
|
+
function isPrivateHost(host) {
|
|
119
|
+
const h = host.toLowerCase().replace(/^\[|\]$/g, "");
|
|
120
|
+
if (h === "localhost" || /\.(local|internal|lan|localdomain|home\.arpa)$/.test(h)) return true;
|
|
121
|
+
if (h.includes(":")) return /^(::1?$|f[cd]|fe[89ab]|::ffff:)/.test(h);
|
|
122
|
+
const v4 = h.match(/^(\d+)\.(\d+)\.\d+\.\d+$/);
|
|
123
|
+
if (v4) {
|
|
124
|
+
const [a, b] = [Number(v4[1]), Number(v4[2])];
|
|
125
|
+
return a === 0 || a === 10 || a === 127 || a === 169 && b === 254 || a === 172 && b >= 16 && b <= 31 || a === 192 && b === 168 || a === 100 && b >= 64 && b <= 127;
|
|
126
|
+
}
|
|
127
|
+
return !h.includes(".");
|
|
128
|
+
}
|
|
129
|
+
var words = (s) => s.toLowerCase().match(/[\p{L}\p{N}]{2,}/gu) ?? [];
|
|
130
|
+
function pinLookup(pinned) {
|
|
131
|
+
return (hostname, options, callback) => {
|
|
132
|
+
const opts = typeof options === "object" && options !== null ? options : {};
|
|
133
|
+
const family = typeof options === "number" ? options : opts.family;
|
|
134
|
+
const realDns = () => dnsCbLookup(hostname, typeof options === "number" ? { family: options } : opts, callback);
|
|
135
|
+
if (!pinned.length) return realDns();
|
|
136
|
+
const list = family ? pinned.filter((a) => a.family === family) : pinned;
|
|
137
|
+
if (!list.length) {
|
|
138
|
+
callback(Object.assign(new Error(`no pinned address for family ${family}`), { code: "ENOTFOUND" }), "");
|
|
139
|
+
return;
|
|
140
|
+
}
|
|
141
|
+
if (opts.all) callback(null, list);
|
|
142
|
+
else callback(null, list[0].address, list[0].family);
|
|
143
|
+
};
|
|
144
|
+
}
|
|
145
|
+
function pickRelevant(text, query, count = FOCUS_CHUNKS, size = FOCUS_SIZE) {
|
|
146
|
+
const chunks = [];
|
|
147
|
+
let cur = "";
|
|
148
|
+
for (const line of text.split("\n")) {
|
|
149
|
+
for (let i = 0; i < Math.max(line.length, 1); i += size) {
|
|
150
|
+
cur += `${line.slice(i, i + size)}
|
|
151
|
+
`;
|
|
152
|
+
if (cur.length >= size) {
|
|
153
|
+
chunks.push(cur.trimEnd());
|
|
154
|
+
cur = "";
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
if (cur.trim()) chunks.push(cur.trimEnd());
|
|
159
|
+
const q = [...new Set(words(query))];
|
|
160
|
+
const docs = chunks.map(words);
|
|
161
|
+
const avg = docs.reduce((n, d) => n + d.length, 0) / (docs.length || 1) || 1;
|
|
162
|
+
const idf = q.map((t2) => {
|
|
163
|
+
const df = docs.filter((d) => d.includes(t2)).length;
|
|
164
|
+
return Math.log(1 + (docs.length - df + 0.5) / (df + 0.5));
|
|
165
|
+
});
|
|
166
|
+
const scored = docs.map((d, i) => ({
|
|
167
|
+
i,
|
|
168
|
+
score: q.reduce((sum, t2, k) => {
|
|
169
|
+
const tf = d.filter((w) => w === t2).length;
|
|
170
|
+
return sum + idf[k] * tf * 2.2 / (tf + 1.2 * (0.25 + 0.75 * d.length / avg));
|
|
171
|
+
}, 0)
|
|
172
|
+
})).filter((c) => c.score > 0).sort((a, b) => b.score - a.score).slice(0, count).sort((a, b) => a.i - b.i);
|
|
173
|
+
return scored.length ? scored.map((c) => chunks[c.i]).join("\n\u2026\n") : null;
|
|
174
|
+
}
|
|
175
|
+
var cache = /* @__PURE__ */ new Map();
|
|
176
|
+
function remember(key, value, size) {
|
|
177
|
+
if (size > CACHE_MAX_CHARS) return;
|
|
178
|
+
cache.delete(key);
|
|
179
|
+
cache.set(key, value);
|
|
180
|
+
if (cache.size > CACHE_MAX) cache.delete(cache.keys().next().value);
|
|
181
|
+
}
|
|
182
|
+
function recall(key) {
|
|
183
|
+
const hit = cache.get(key);
|
|
184
|
+
if (typeof hit === "object" && Date.now() - hit.at > CACHE_TTL_MS) {
|
|
185
|
+
cache.delete(key);
|
|
186
|
+
return void 0;
|
|
187
|
+
}
|
|
188
|
+
return hit;
|
|
189
|
+
}
|
|
190
|
+
var ACCEPT = "text/markdown, text/html;q=0.9, text/plain;q=0.8, */*;q=0.5";
|
|
191
|
+
var withCost = (text, what) => `${what} \xB7 ${t("~{n} tokens", { n: tokensOf(text) })}`;
|
|
192
|
+
function createFetchTool(opts = {}) {
|
|
193
|
+
const keenableURL = opts.keenableURL === void 0 ? "https://api.keenable.ai/v1/fetch/public" : opts.keenableURL;
|
|
194
|
+
const isPrivate = opts.isPrivate ?? isPrivateHost;
|
|
195
|
+
const lookup = opts.lookup ?? ((hostname) => dnsLookup(hostname, { all: true }));
|
|
196
|
+
return defineTool({
|
|
197
|
+
name: "fetch",
|
|
198
|
+
description: `Fetch a URL (http/https) as text/markdown. Costs the user tokens, so ask for as little as you need:
|
|
199
|
+
- Pass \`prompt\` (what you want to know from the page) to get only the relevant excerpt instead of the whole page. Prefer this whenever you are looking for specific facts.
|
|
200
|
+
- Without \`prompt\` you get the first ${MAX_CHARS} characters; the reply tells you the \`offset\` to continue from.
|
|
201
|
+
- Fetching a page that is already in this conversation is wasteful; reuse what you have.`,
|
|
202
|
+
schema: z2.object({
|
|
203
|
+
url: z2.string().describe("Absolute http(s) URL"),
|
|
204
|
+
prompt: z2.string().max(2e3).optional().describe("What to look for in the page; returns only the relevant excerpt"),
|
|
205
|
+
offset: z2.number().int().min(0).optional().describe("Start reading at this character (to continue a truncated page)")
|
|
206
|
+
}),
|
|
207
|
+
kind: "fetch",
|
|
208
|
+
target: (input) => input.url,
|
|
209
|
+
async run(input, ctx) {
|
|
210
|
+
if (!/^https?:\/\//i.test(input.url)) return { output: "URL must start with http:// or https://", isError: true };
|
|
211
|
+
const target = new URL(input.url);
|
|
212
|
+
let pinned;
|
|
213
|
+
if (!isPrivate(target.hostname) && isIP(target.hostname) === 0) {
|
|
214
|
+
try {
|
|
215
|
+
const addresses = await lookup(target.hostname);
|
|
216
|
+
const internal = addresses.find((a) => isPrivate(a.address));
|
|
217
|
+
if (internal) {
|
|
218
|
+
return {
|
|
219
|
+
output: t("Blocked: {host} resolves to a private address ({addr}). Fetching an internal host through a public DNS name is not allowed.", { host: target.hostname, addr: internal.address }),
|
|
220
|
+
isError: true
|
|
221
|
+
};
|
|
222
|
+
}
|
|
223
|
+
pinned = addresses;
|
|
224
|
+
} catch {
|
|
225
|
+
}
|
|
226
|
+
}
|
|
227
|
+
const prompt = input.prompt?.trim();
|
|
228
|
+
const askKeenable = !!prompt && !input.offset && !!keenableURL && !target.username && !target.password && !isPrivate(target.hostname);
|
|
229
|
+
if (askKeenable) {
|
|
230
|
+
const key = `x
|
|
231
|
+
${input.url}
|
|
232
|
+
${prompt}`;
|
|
233
|
+
const hit = recall(key);
|
|
234
|
+
if (hit) {
|
|
235
|
+
ctx.refundFetch?.();
|
|
236
|
+
return { output: hit, display: withCost(hit, t("focused excerpt \xB7 cache")) };
|
|
237
|
+
}
|
|
238
|
+
const out = await extractWithKeenable(keenableURL, input.url, prompt, ctx.signal);
|
|
239
|
+
if (out) {
|
|
240
|
+
const output2 = `[Excerpt from ${input.url} for "${prompt}" (extracted by Keenable). If it says the answer is not there, try fetch without a prompt.]
|
|
241
|
+
${out}`;
|
|
242
|
+
remember(key, output2, output2.length);
|
|
243
|
+
return { output: output2, display: withCost(output2, t("focused excerpt (Keenable)")) };
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
let page = recall(`p
|
|
247
|
+
${input.url}`);
|
|
248
|
+
const cached = !!page;
|
|
249
|
+
if (cached) ctx.refundFetch?.();
|
|
250
|
+
if (!page) {
|
|
251
|
+
const loaded = await loadPage(input.url, ctx.signal, pinned, opts.fetchPage);
|
|
252
|
+
if ("error" in loaded) return { output: loaded.error, isError: true };
|
|
253
|
+
page = loaded;
|
|
254
|
+
remember(`p
|
|
255
|
+
${input.url}`, page, page.text.length);
|
|
256
|
+
}
|
|
257
|
+
const { text, truncated } = page;
|
|
258
|
+
const via = cached ? " \xB7 cache" : "";
|
|
259
|
+
if (prompt && !input.offset) {
|
|
260
|
+
const picked = pickRelevant(text, prompt);
|
|
261
|
+
if (picked) {
|
|
262
|
+
const output2 = `[Most relevant excerpt from ${input.url} for "${prompt}" (${text.length} characters total). Full page: fetch without a prompt.]
|
|
263
|
+
${picked}`;
|
|
264
|
+
return { output: output2, display: withCost(output2, `${t("focused excerpt (local)")}${via}`) };
|
|
265
|
+
}
|
|
266
|
+
}
|
|
267
|
+
const offset = input.offset ?? 0;
|
|
268
|
+
if (offset >= text.length && text.length > 0) {
|
|
269
|
+
return { output: `offset ${offset} is past the end of the page (${text.length} characters).`, isError: true };
|
|
270
|
+
}
|
|
271
|
+
const end = Math.min(offset + MAX_CHARS, text.length);
|
|
272
|
+
let output = text.slice(offset, end);
|
|
273
|
+
if (end < text.length || truncated) {
|
|
274
|
+
const total = truncated ? `${text.length}+` : text.length;
|
|
275
|
+
output += `
|
|
276
|
+
\u2026 [truncated: characters ${offset}-${end} of ${total}. Continue with offset=${end}, or use prompt for a focused excerpt.]`;
|
|
277
|
+
}
|
|
278
|
+
const size = truncated ? t("over 5 MB, truncated") : t("{n} characters", { n: text.length });
|
|
279
|
+
return { output, display: withCost(output, `${size}${via}`) };
|
|
280
|
+
}
|
|
281
|
+
});
|
|
282
|
+
}
|
|
283
|
+
async function extractWithKeenable(endpoint, url, prompt, signal) {
|
|
284
|
+
try {
|
|
285
|
+
const u = new URL(endpoint);
|
|
286
|
+
u.searchParams.set("url", url);
|
|
287
|
+
u.searchParams.set("prompt", prompt);
|
|
288
|
+
u.searchParams.set("live", "true");
|
|
289
|
+
u.searchParams.set("max_chars", String(MAX_CHARS));
|
|
290
|
+
const res = await fetch(u, { headers: { "X-Keenable-Title": "BotConnector" }, signal: AbortSignal.any([signal, AbortSignal.timeout(25e3)]) });
|
|
291
|
+
if (!res.ok) return void 0;
|
|
292
|
+
const content = (await res.json()).content;
|
|
293
|
+
return typeof content === "string" && content.trim() ? content.slice(0, MAX_CHARS) : void 0;
|
|
294
|
+
} catch {
|
|
295
|
+
return void 0;
|
|
296
|
+
}
|
|
297
|
+
}
|
|
298
|
+
async function loadPage(inputUrl, signal, pinned, fetchPage) {
|
|
299
|
+
let url = new URL(inputUrl);
|
|
300
|
+
const dispatcher = pinned?.length ? new Agent({ connect: { lookup: pinLookup(pinned) } }) : void 0;
|
|
301
|
+
const doFetch = fetchPage ?? (dispatcher ? undiciFetch : fetch);
|
|
302
|
+
try {
|
|
303
|
+
let res;
|
|
304
|
+
for (let hop = 0; hop < 5; hop++) {
|
|
305
|
+
res = await doFetch(url, {
|
|
306
|
+
headers: { accept: ACCEPT },
|
|
307
|
+
signal: AbortSignal.any([signal, AbortSignal.timeout(3e4)]),
|
|
308
|
+
redirect: "manual",
|
|
309
|
+
...dispatcher ? { dispatcher } : {}
|
|
310
|
+
});
|
|
311
|
+
const location = res.status >= 300 && res.status < 400 ? res.headers.get("location") : null;
|
|
312
|
+
if (!location) break;
|
|
313
|
+
const next = new URL(location, url);
|
|
314
|
+
if (next.host !== url.host) {
|
|
315
|
+
await res.body?.cancel();
|
|
316
|
+
return { error: `Redirect to another host: ${next.href}. Call fetch again with that URL if needed (permission will be requested).` };
|
|
317
|
+
}
|
|
318
|
+
await res.body?.cancel();
|
|
319
|
+
url = next;
|
|
320
|
+
}
|
|
321
|
+
if (!res) return { error: `Failed to fetch ${inputUrl}` };
|
|
322
|
+
const { text: body, truncated } = await readCapped(res);
|
|
323
|
+
const type = res.headers.get("content-type") ?? "";
|
|
324
|
+
const text = type.includes("html") ? htmlToText(body) : body;
|
|
325
|
+
if (!res.ok) return { error: `HTTP ${res.status} from ${inputUrl}: ${text.slice(0, 500)}` };
|
|
326
|
+
return { text, truncated, at: Date.now() };
|
|
327
|
+
} catch (error) {
|
|
328
|
+
return { error: `Failed to fetch ${inputUrl}: ${describeFetchError(error)}` };
|
|
329
|
+
} finally {
|
|
330
|
+
await dispatcher?.close().catch(() => {
|
|
331
|
+
});
|
|
332
|
+
}
|
|
333
|
+
}
|
|
334
|
+
var fetchTool = createFetchTool();
|
|
335
|
+
|
|
336
|
+
export {
|
|
337
|
+
isPrivateHost,
|
|
338
|
+
createFetchTool,
|
|
339
|
+
fetchTool,
|
|
340
|
+
createWebSearchTool
|
|
341
|
+
};
|
|
@@ -0,0 +1,191 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
|
|
3
|
+
// src/mcp/oauth.ts
|
|
4
|
+
import { spawn } from "child_process";
|
|
5
|
+
import { chmodSync, existsSync, mkdirSync, readFileSync, writeFileSync } from "fs";
|
|
6
|
+
import { createServer } from "http";
|
|
7
|
+
import { dirname, join } from "path";
|
|
8
|
+
import { auth } from "@modelcontextprotocol/sdk/client/auth.js";
|
|
9
|
+
var oauthStorePath = (home) => join(home, "mcp-oauth.json");
|
|
10
|
+
function readStore(home) {
|
|
11
|
+
const path = oauthStorePath(home);
|
|
12
|
+
if (!existsSync(path)) return {};
|
|
13
|
+
try {
|
|
14
|
+
return JSON.parse(readFileSync(path, "utf8"));
|
|
15
|
+
} catch {
|
|
16
|
+
return {};
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
function writeStore(home, store) {
|
|
20
|
+
const path = oauthStorePath(home);
|
|
21
|
+
mkdirSync(dirname(path), { recursive: true });
|
|
22
|
+
writeFileSync(path, `${JSON.stringify(store, null, 2)}
|
|
23
|
+
`, { mode: 384 });
|
|
24
|
+
chmodSync(path, 384);
|
|
25
|
+
}
|
|
26
|
+
function hasStoredTokens(home, serverUrl) {
|
|
27
|
+
return Boolean(readStore(home)[serverUrl]?.tokens);
|
|
28
|
+
}
|
|
29
|
+
function clearTokens(home, serverUrl) {
|
|
30
|
+
const store = readStore(home);
|
|
31
|
+
const entry = store[serverUrl];
|
|
32
|
+
if (!entry?.tokens && !entry?.client && !entry?.codeVerifier && !entry?.discovery) return false;
|
|
33
|
+
delete store[serverUrl];
|
|
34
|
+
writeStore(home, store);
|
|
35
|
+
return true;
|
|
36
|
+
}
|
|
37
|
+
function defaultOpen(url) {
|
|
38
|
+
const target = url.href;
|
|
39
|
+
const child = process.platform === "win32" ? spawn("cmd", ["/c", "start", "", target], { detached: true, stdio: "ignore" }) : spawn(process.platform === "darwin" ? "open" : "xdg-open", [target], { detached: true, stdio: "ignore" });
|
|
40
|
+
child.unref();
|
|
41
|
+
child.on("error", () => {
|
|
42
|
+
});
|
|
43
|
+
}
|
|
44
|
+
var FileOAuthProvider = class {
|
|
45
|
+
opts;
|
|
46
|
+
constructor(opts) {
|
|
47
|
+
this.opts = opts;
|
|
48
|
+
}
|
|
49
|
+
/**
|
|
50
|
+
* Always defined: MCP SDK treats a missing redirectUrl as a non-interactive
|
|
51
|
+
* (client_credentials) flow and would try a token exchange without a code.
|
|
52
|
+
*/
|
|
53
|
+
get redirectUrl() {
|
|
54
|
+
return this.opts.redirectUrl ?? "http://127.0.0.1:1/callback";
|
|
55
|
+
}
|
|
56
|
+
get clientMetadata() {
|
|
57
|
+
return {
|
|
58
|
+
client_name: "BCCLI",
|
|
59
|
+
redirect_uris: [String(this.redirectUrl)],
|
|
60
|
+
grant_types: ["authorization_code", "refresh_token"],
|
|
61
|
+
response_types: ["code"],
|
|
62
|
+
token_endpoint_auth_method: "none"
|
|
63
|
+
};
|
|
64
|
+
}
|
|
65
|
+
entry() {
|
|
66
|
+
return readStore(this.opts.home)[this.opts.serverUrl] ?? {};
|
|
67
|
+
}
|
|
68
|
+
patch(patch) {
|
|
69
|
+
const store = readStore(this.opts.home);
|
|
70
|
+
const next = { ...store[this.opts.serverUrl], ...patch };
|
|
71
|
+
for (const key of Object.keys(next)) {
|
|
72
|
+
if (next[key] === void 0) delete next[key];
|
|
73
|
+
}
|
|
74
|
+
store[this.opts.serverUrl] = next;
|
|
75
|
+
if (Object.keys(next).length === 0) delete store[this.opts.serverUrl];
|
|
76
|
+
writeStore(this.opts.home, store);
|
|
77
|
+
}
|
|
78
|
+
clientInformation() {
|
|
79
|
+
return this.entry().client;
|
|
80
|
+
}
|
|
81
|
+
saveClientInformation(clientInformation) {
|
|
82
|
+
this.patch({ client: clientInformation });
|
|
83
|
+
}
|
|
84
|
+
tokens() {
|
|
85
|
+
return this.entry().tokens;
|
|
86
|
+
}
|
|
87
|
+
saveTokens(tokens) {
|
|
88
|
+
this.patch({ tokens });
|
|
89
|
+
}
|
|
90
|
+
saveCodeVerifier(codeVerifier) {
|
|
91
|
+
this.patch({ codeVerifier });
|
|
92
|
+
}
|
|
93
|
+
codeVerifier() {
|
|
94
|
+
return this.entry().codeVerifier ?? "";
|
|
95
|
+
}
|
|
96
|
+
redirectToAuthorization(authorizationUrl) {
|
|
97
|
+
return (this.opts.open ?? defaultOpen)(authorizationUrl);
|
|
98
|
+
}
|
|
99
|
+
saveDiscoveryState(state) {
|
|
100
|
+
this.patch({ discovery: state });
|
|
101
|
+
}
|
|
102
|
+
discoveryState() {
|
|
103
|
+
return this.entry().discovery;
|
|
104
|
+
}
|
|
105
|
+
invalidateCredentials(scope) {
|
|
106
|
+
if (scope === "all") {
|
|
107
|
+
this.patch({ client: void 0, tokens: void 0, codeVerifier: void 0, discovery: void 0 });
|
|
108
|
+
return;
|
|
109
|
+
}
|
|
110
|
+
if (scope === "client") this.patch({ client: void 0 });
|
|
111
|
+
if (scope === "tokens") this.patch({ tokens: void 0 });
|
|
112
|
+
if (scope === "verifier") this.patch({ codeVerifier: void 0 });
|
|
113
|
+
if (scope === "discovery") this.patch({ discovery: void 0 });
|
|
114
|
+
}
|
|
115
|
+
};
|
|
116
|
+
function parseCallback(input) {
|
|
117
|
+
const url = typeof input === "string" ? new URL(input) : input;
|
|
118
|
+
const error = url.searchParams.get("error");
|
|
119
|
+
if (error) {
|
|
120
|
+
const description = url.searchParams.get("error_description");
|
|
121
|
+
throw new Error(description ? `OAuth ${error}: ${description}` : `OAuth ${error}`);
|
|
122
|
+
}
|
|
123
|
+
const code = url.searchParams.get("code");
|
|
124
|
+
if (!code) throw new Error("OAuth callback is missing the code parameter.");
|
|
125
|
+
const state = url.searchParams.get("state") ?? void 0;
|
|
126
|
+
return { code, state };
|
|
127
|
+
}
|
|
128
|
+
var CALLBACK_TIMEOUT_MS = 18e4;
|
|
129
|
+
async function authorizeMcpServer(spec, deps) {
|
|
130
|
+
let settle;
|
|
131
|
+
const codeReceived = new Promise((resolve, reject) => {
|
|
132
|
+
settle = { resolve, reject };
|
|
133
|
+
});
|
|
134
|
+
codeReceived.catch(() => {
|
|
135
|
+
});
|
|
136
|
+
const server = createServer((req, res) => {
|
|
137
|
+
const url = new URL(req.url ?? "/", "http://127.0.0.1");
|
|
138
|
+
if (url.pathname !== "/callback") {
|
|
139
|
+
res.writeHead(404);
|
|
140
|
+
res.end();
|
|
141
|
+
return;
|
|
142
|
+
}
|
|
143
|
+
try {
|
|
144
|
+
const { code } = parseCallback(url);
|
|
145
|
+
res.writeHead(200, { "content-type": "text/html; charset=utf-8" });
|
|
146
|
+
res.end("<html><body><p>BCCLI is connected. You can close this tab.</p></body></html>");
|
|
147
|
+
settle.resolve(code);
|
|
148
|
+
} catch (error) {
|
|
149
|
+
res.writeHead(400, { "content-type": "text/html; charset=utf-8" });
|
|
150
|
+
res.end(`<html><body><p>${error.message}</p></body></html>`);
|
|
151
|
+
settle.reject(error);
|
|
152
|
+
}
|
|
153
|
+
});
|
|
154
|
+
const port = await new Promise((resolve, reject) => {
|
|
155
|
+
server.once("error", reject);
|
|
156
|
+
server.listen(0, "127.0.0.1", () => {
|
|
157
|
+
const address = server.address();
|
|
158
|
+
resolve(typeof address === "object" && address ? address.port : 0);
|
|
159
|
+
});
|
|
160
|
+
});
|
|
161
|
+
try {
|
|
162
|
+
const provider = new FileOAuthProvider({
|
|
163
|
+
home: deps.home,
|
|
164
|
+
serverUrl: spec.config.url,
|
|
165
|
+
redirectUrl: `http://127.0.0.1:${port}/callback`,
|
|
166
|
+
open: deps.open
|
|
167
|
+
});
|
|
168
|
+
const serverUrl = new URL(spec.config.url);
|
|
169
|
+
const result = await auth(provider, { serverUrl, fetchFn: deps.fetchFn });
|
|
170
|
+
if (result === "AUTHORIZED") return;
|
|
171
|
+
const timer = setTimeout(() => settle.reject(new Error("Timed out waiting for the OAuth callback.")), CALLBACK_TIMEOUT_MS);
|
|
172
|
+
let code;
|
|
173
|
+
try {
|
|
174
|
+
code = await codeReceived;
|
|
175
|
+
} finally {
|
|
176
|
+
clearTimeout(timer);
|
|
177
|
+
}
|
|
178
|
+
const second = await auth(provider, { serverUrl, authorizationCode: code, fetchFn: deps.fetchFn });
|
|
179
|
+
if (second !== "AUTHORIZED") throw new Error("OAuth authorization did not complete.");
|
|
180
|
+
} finally {
|
|
181
|
+
server.close();
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
export {
|
|
186
|
+
hasStoredTokens,
|
|
187
|
+
clearTokens,
|
|
188
|
+
defaultOpen,
|
|
189
|
+
FileOAuthProvider,
|
|
190
|
+
authorizeMcpServer
|
|
191
|
+
};
|
|
@@ -1,4 +1,7 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
+
import {
|
|
3
|
+
t
|
|
4
|
+
} from "./chunk-UZWJQF67.js";
|
|
2
5
|
|
|
3
6
|
// src/reasoning.ts
|
|
4
7
|
var REASONING_LEVELS = ["auto", "off", "low", "medium", "high", "max"];
|
|
@@ -9,7 +12,7 @@ function isReasoningLevel(value) {
|
|
|
9
12
|
}
|
|
10
13
|
function parseReasoningLevel(value, label = "reasoning") {
|
|
11
14
|
if (!isReasoningLevel(value)) {
|
|
12
|
-
throw new Error(
|
|
15
|
+
throw new Error(t("{label} must be one of: {levels}", { label, levels: REASONING_LEVELS.join(", ") }));
|
|
13
16
|
}
|
|
14
17
|
return value;
|
|
15
18
|
}
|
|
@@ -32,11 +35,11 @@ function assertReasoningSupported(providerId, level) {
|
|
|
32
35
|
if (level === "auto") return;
|
|
33
36
|
const capability = reasoningCapability(providerId);
|
|
34
37
|
if (!capability) {
|
|
35
|
-
throw new Error("
|
|
38
|
+
throw new Error(t("This provider has no manual reasoning setting yet. Use Auto."));
|
|
36
39
|
}
|
|
37
40
|
if (!capability.levels.includes(level)) {
|
|
38
41
|
const supported = capability.levels.filter((x) => x !== "auto").map(capitalize).join("/");
|
|
39
|
-
throw new Error(
|
|
42
|
+
throw new Error(t("This model/provider does not support reasoning level '{level}'. Use Auto{supported}.", { level, supported: supported ? `/${supported}` : "" }));
|
|
40
43
|
}
|
|
41
44
|
}
|
|
42
45
|
function reasoningPayload(providerId, level) {
|