@botconnector/bccli 0.4.0-beta.4 → 0.4.0-beta.40

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. package/README.md +80 -1
  2. package/dist/acp-5A7EXLCG.js +114 -0
  3. package/dist/args-4SMOHFN5.js +13 -0
  4. package/dist/chunk-3HCOAJEQ.js +190 -0
  5. package/dist/chunk-AS7VV7D3.js +195 -0
  6. package/dist/{chunk-NGLKANMD.js → chunk-AVB6M4JE.js} +24 -2
  7. package/dist/{chunk-GW36UMHZ.js → chunk-DSFHN5CH.js} +2 -2
  8. package/dist/{chunk-ELML4KVQ.js → chunk-GAFJEQTJ.js} +32 -2
  9. package/dist/chunk-GGNXHJL6.js +884 -0
  10. package/dist/chunk-HE33XAPZ.js +341 -0
  11. package/dist/{chunk-UESQNU4A.js → chunk-ISCT3PN3.js} +14 -9
  12. package/dist/chunk-JROUQ5YS.js +76 -0
  13. package/dist/chunk-LN32JIZR.js +56 -0
  14. package/dist/chunk-M23QBX3V.js +419 -0
  15. package/dist/chunk-M7LLJQ7M.js +310 -0
  16. package/dist/chunk-NI5JZUZ3.js +63 -0
  17. package/dist/chunk-PDVS4UWM.js +8 -0
  18. package/dist/chunk-PSO7R5AD.js +10 -0
  19. package/dist/chunk-RV74TCEP.js +231 -0
  20. package/dist/{chunk-U7DLMVPZ.js → chunk-SESBH44L.js} +2 -1
  21. package/dist/{chunk-SJH3YLW4.js → chunk-VM7HYAJS.js} +4 -1
  22. package/dist/chunk-WH7XLDGZ.js +2125 -0
  23. package/dist/chunk-ZMU7MXCH.js +674 -0
  24. package/dist/cli.js +94 -1278
  25. package/dist/{config-NPSYFAFD.js → config-C4KLLDC6.js} +5 -2
  26. package/dist/integrationCli-HR7CDUSI.js +685 -0
  27. package/dist/{login-F4G5QXOU.js → login-T5S6SPZA.js} +1 -1
  28. package/dist/{mcpCli-Q2H63ISP.js → mcpCli-5QTXH7XJ.js} +42 -9
  29. package/dist/modelsCli-DKTT3UZD.js +36 -0
  30. package/dist/providerCli-DDH4ZZUY.js +15 -0
  31. package/dist/sdk.js +5130 -0
  32. package/dist/serve-I2VQUTHR.js +178 -0
  33. package/dist/serve-JNQUP7CZ.js +514 -0
  34. package/dist/session-H2YL5RSB.js +12 -0
  35. package/dist/setup-I7UY7X7C.js +23 -0
  36. package/dist/ui-GVIMUZNS.js +2280 -0
  37. package/dist/update-SZUG3YSB.js +109 -0
  38. package/package.json +24 -3
  39. package/dist/args-FCLPQ7TO.js +0 -11
  40. package/dist/chunk-C5AFWX7H.js +0 -328
  41. package/dist/chunk-OSWQPSA4.js +0 -252
  42. package/dist/chunk-RZUJYAQV.js +0 -112
  43. package/dist/chunk-UN7QXPCB.js +0 -82
  44. package/dist/providerCli-MXV6PD6F.js +0 -11
  45. package/dist/session-7UB77CEG.js +0 -9
  46. package/dist/ui-7FXPXXGN.js +0 -1333
@@ -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-M23QBX3V.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(/&nbsp;/g, " ").replace(/&lt;/g, "<").replace(/&gt;/g, ">").replace(/&quot;/g, '"').replace(/&#39;/g, "'").replace(/&amp;/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
+ };
@@ -1,23 +1,28 @@
1
1
  #!/usr/bin/env node
2
2
  import {
3
3
  ConfigError
4
- } from "./chunk-RZUJYAQV.js";
4
+ } from "./chunk-M7LLJQ7M.js";
5
+ import {
6
+ t
7
+ } from "./chunk-M23QBX3V.js";
5
8
 
6
9
  // src/mcp/catalog.ts
7
10
  var CATALOG = [
8
- { name: "playwright", description: "kontrol browser (buka halaman, klik, isi form, screenshot)", config: { command: "npx", args: ["-y", "@playwright/mcp@latest"] } },
9
- { name: "context7", description: "dokumentasi library terbaru", config: { type: "http", url: "https://mcp.context7.com/mcp" } },
10
- { name: "fetch", description: "ambil halaman web jadi markdown (butuh uv)", config: { command: "uvx", args: ["mcp-server-fetch"] } },
11
+ { name: "playwright", description: "control a browser (open pages, click, fill forms, screenshot)", config: { command: "npx", args: ["-y", "@playwright/mcp@latest"] } },
12
+ { name: "context7", description: "up-to-date library documentation", config: { type: "http", url: "https://mcp.context7.com/mcp" } },
13
+ { name: "fetch", description: "fetch web pages as markdown (needs uv)", config: { command: "uvx", args: ["mcp-server-fetch"] } },
11
14
  {
12
15
  name: "filesystem",
13
- description: "akses folder di luar project",
16
+ description: "access folders outside the project",
17
+ // biome-ignore lint/suspicious/noTemplateCurlyInString: ${dir} is filled by fillTemplate, not a template literal
14
18
  config: { command: "npx", args: ["-y", "@modelcontextprotocol/server-filesystem", "${dir}"] },
15
- inputs: [{ key: "dir", label: "Folder yang boleh diakses" }]
19
+ inputs: [{ key: "dir", label: "Folder the server may access" }]
16
20
  },
17
- { name: "git", description: "operasi git terstruktur (butuh uv)", config: { command: "uvx", args: ["mcp-server-git"] } },
21
+ { name: "git", description: "structured git operations (needs uv)", config: { command: "uvx", args: ["mcp-server-git"] } },
18
22
  {
19
23
  name: "github",
20
- description: "issue, PR, dan repo GitHub",
24
+ description: "GitHub issues, PRs, and repos",
25
+ // biome-ignore lint/suspicious/noTemplateCurlyInString: ${token} is filled by fillTemplate, not a template literal
21
26
  config: { type: "http", url: "https://api.githubcopilot.com/mcp/", headers: { Authorization: "Bearer ${token}" } },
22
27
  inputs: [{ key: "token", label: "GitHub Personal Access Token", secret: true }]
23
28
  }
@@ -35,7 +40,7 @@ function fillTemplate(config, values) {
35
40
  ...config.args ? { args: config.args.map(fill) } : {},
36
41
  ...config.env ? { env: mapValues(config.env) } : {}
37
42
  };
38
- if (missing.size) throw new ConfigError(`Isian MCP belum lengkap: ${[...missing].join(", ")}`);
43
+ if (missing.size) throw new ConfigError(t("Missing MCP fields: {fields}", { fields: [...missing].join(", ") }));
39
44
  return out;
40
45
  }
41
46
 
@@ -0,0 +1,76 @@
1
+ #!/usr/bin/env node
2
+ import {
3
+ listAllModels
4
+ } from "./chunk-LN32JIZR.js";
5
+ import {
6
+ hasKey,
7
+ providerName,
8
+ removeGlobalProvider,
9
+ writeGlobalConfig
10
+ } from "./chunk-SESBH44L.js";
11
+ import {
12
+ PRESETS,
13
+ loadConfig,
14
+ saveCredential
15
+ } from "./chunk-M7LLJQ7M.js";
16
+ import {
17
+ t
18
+ } from "./chunk-M23QBX3V.js";
19
+
20
+ // src/providerCli.ts
21
+ async function addProviderKey(providerId, key, deps) {
22
+ const config = loadConfig(deps.cwd, deps.env);
23
+ const [group] = await listAllModels(config, deps.env, { only: providerId, fetch: deps.fetch, keyOverride: key || void 0 });
24
+ if (!group || group.error) return { ok: false, error: t("The API key was rejected or {provider} could not be reached.", { provider: providerName(config, providerId) }) };
25
+ if (key) saveCredential(providerId, key, deps.env);
26
+ return { ok: true, models: group.models.length };
27
+ }
28
+ async function runProviderCommand(args, deps) {
29
+ const [action = "list", id] = args.subArgs;
30
+ const config = loadConfig(deps.cwd, deps.env);
31
+ if (action === "list") {
32
+ for (const pid of Object.keys(config.providers)) {
33
+ const mark = hasKey(config, pid, deps.env) ? "\u2713" : "\u25CB";
34
+ deps.out(`${mark} ${pid.padEnd(14)} ${providerName(config, pid).padEnd(20)} ${config.providers[pid].baseURL}`);
35
+ }
36
+ return 0;
37
+ }
38
+ if (!id) {
39
+ deps.err(t("Usage: bccli provider {action} <id>", { action }));
40
+ return 1;
41
+ }
42
+ if (action === "remove") {
43
+ removeGlobalProvider(id, deps.env);
44
+ deps.out(t("{id} removed.", { id }));
45
+ return 0;
46
+ }
47
+ if (action !== "add") {
48
+ deps.err(t("Unknown action: {action}. Use list, add, or remove.", { action }));
49
+ return 1;
50
+ }
51
+ const preset = PRESETS.find((p) => p.id === id);
52
+ if (!preset && !config.providers[id]) {
53
+ if (!args.url) {
54
+ deps.err(t("{id} is not a preset. For a custom provider add --url <OpenAI-compatible base URL>.", { id }));
55
+ return 1;
56
+ }
57
+ writeGlobalConfig(
58
+ { providers: { [id]: { baseURL: args.url, ...args.name ? { name: args.name } : {}, ...args.keyEnv ? { apiKeyEnv: args.keyEnv } : {} } } },
59
+ deps.env
60
+ );
61
+ }
62
+ const needsKey = !!loadConfig(deps.cwd, deps.env).providers[id].apiKeyEnv || !preset;
63
+ const key = needsKey ? await deps.readSecret(t("API key for {id} (leave empty if not needed): ", { id })) : "";
64
+ const result = await addProviderKey(id, key, deps);
65
+ if (!result.ok) {
66
+ deps.err(result.error);
67
+ return 1;
68
+ }
69
+ deps.out(t("{id} is ready. {n} models available.", { id, n: result.models }));
70
+ return 0;
71
+ }
72
+
73
+ export {
74
+ addProviderKey,
75
+ runProviderCommand
76
+ };
@@ -0,0 +1,56 @@
1
+ #!/usr/bin/env node
2
+ import {
3
+ hasKey,
4
+ providerName
5
+ } from "./chunk-SESBH44L.js";
6
+ import {
7
+ createProvider
8
+ } from "./chunk-GGNXHJL6.js";
9
+ import {
10
+ PRESETS,
11
+ readCredentials
12
+ } from "./chunk-M7LLJQ7M.js";
13
+ import {
14
+ t
15
+ } from "./chunk-M23QBX3V.js";
16
+
17
+ // src/models.ts
18
+ function order(ids) {
19
+ const presetIds = PRESETS.map((p) => p.id);
20
+ const presets = presetIds.filter((id) => ids.includes(id));
21
+ const custom = ids.filter((id) => !presetIds.includes(id)).sort();
22
+ return [...presets, ...custom];
23
+ }
24
+ async function listAllModels(config, env = process.env, opts = {}) {
25
+ const timeoutMs = opts.timeoutMs ?? 5e3;
26
+ const baseFetch = opts.fetch ?? fetch;
27
+ const untrusted = new Set(config.projectProviders ?? []);
28
+ const ids = order(Object.keys(config.providers)).filter((id) => opts.only ? id === opts.only : !untrusted.has(id) && hasKey(config, id, env));
29
+ const results = await Promise.all(
30
+ ids.map(async (id) => {
31
+ const provider = config.providers[id];
32
+ const apiKey = (opts.keyOverride && id === opts.only ? opts.keyOverride : void 0) || (provider.apiKeyEnv ? env[provider.apiKeyEnv] : void 0) || readCredentials(env)[id] || void 0;
33
+ const local = !provider.apiKeyEnv;
34
+ const timedFetch = ((input, init) => baseFetch(input, { ...init, signal: AbortSignal.timeout(timeoutMs) }));
35
+ const list = createProvider({ baseURL: provider.baseURL.replace(/\/+$/, ""), apiKey, model: "", fetch: timedFetch }).listModels();
36
+ let timer;
37
+ const timeout = new Promise((_, reject) => {
38
+ timer = setTimeout(() => reject(new Error("timeout")), timeoutMs);
39
+ });
40
+ try {
41
+ const models = await Promise.race([list, timeout]);
42
+ return { providerId: id, providerName: providerName(config, id), models };
43
+ } catch {
44
+ if (local && !opts.only) return void 0;
45
+ return { providerId: id, providerName: providerName(config, id), models: [], error: t("could not be reached") };
46
+ } finally {
47
+ clearTimeout(timer);
48
+ }
49
+ })
50
+ );
51
+ return results.filter((g) => !!g);
52
+ }
53
+
54
+ export {
55
+ listAllModels
56
+ };