@bike4mind/cli 4.0.0 → 4.8.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.md +184 -4
- package/bin/bike4mind-cli.mjs +249 -40
- package/bin/envFlags.d.mts +17 -0
- package/bin/envFlags.mjs +89 -0
- package/dist/{AgentHistoryStore-DgqmcVLN.mjs → AgentHistoryStore-Bvmcy2kf.mjs} +3807 -1375
- package/dist/{ApiClient-_JrM_xWw.mjs → ApiClient-Yp2LPlX3.mjs} +22 -3
- package/dist/BubblewrapRuntime-OI4qFPNB.mjs +157 -0
- package/dist/ConfigStore-Bo4od3Eu.mjs +2 -0
- package/dist/ConfigStore-CP1W86Ui.mjs +3438 -0
- package/dist/{ConfigStore-BwqsQ0U9.mjs → Logger-3RbeTZ9o.mjs} +34769 -22138
- package/dist/{ProxyManager-B0-RuR2w.mjs → ProxyManager-TxEKlgdO.mjs} +88 -3
- package/dist/{RemoteSkillSource-qTvRkaNA.mjs → RemoteSkillSource-D_F99yBR.mjs} +5 -0
- package/dist/{SandboxOrchestrator-BcUv9fQ3.mjs → SandboxOrchestrator-lpxVEFO7.mjs} +26 -7
- package/dist/SandboxRuntimeAdapter-C3xICJtQ.mjs +190 -0
- package/dist/SandboxRuntimeAdapter-u6c_IrjP.mjs +2 -0
- package/dist/SeatbeltRuntime-Ccd_QbjX.mjs +194 -0
- package/dist/{WorkItemsClient-CERTDrhT.mjs → WorkItemsClient-D4sFGL9X.mjs} +1 -1
- package/dist/agents/defaults/review.md +8 -1
- package/dist/agents/defaults/test.md +8 -1
- package/dist/buildToolSearch-CqHKSLtG.mjs +417 -0
- package/dist/commands/acpCommand.mjs +26 -20
- package/dist/commands/apiCommand.mjs +3 -5
- package/dist/commands/doctorCommand.mjs +2 -2
- package/dist/commands/envCommand.mjs +1 -1
- package/dist/commands/headlessCommand.mjs +118 -37
- package/dist/commands/hostCommand.mjs +2344 -0
- package/dist/commands/mcpCommand.mjs +45 -30
- package/dist/commands/mirrorCommand.mjs +279 -0
- package/dist/commands/modelsCommand.mjs +1117 -0
- package/dist/commands/pluginCommand.mjs +9 -9
- package/dist/commands/skillsCommand.mjs +175 -30
- package/dist/commands/updateCommand.mjs +2 -2
- package/dist/curated-build.json +1 -0
- package/dist/dist-BPhZ0dCz.mjs +4776 -0
- package/dist/dist-K7a9yOUb.mjs +7864 -0
- package/dist/fit-BOnDsgbk.mjs +200 -0
- package/dist/{grepSearch-BgoOOwGe-B388GxRD.mjs → grepSearch-CLtEqT4j-BnKPtNWr.mjs} +2 -2
- package/dist/index.mjs +3215 -508
- package/dist/modelHub-BSB6qRFP.mjs +1963 -0
- package/dist/modelServers-B7zI5XnO.mjs +2465 -0
- package/dist/{package-CQaam4Dq.mjs → package-WlxLVpUb.mjs} +1 -1
- package/dist/{serve-CFxUhjml.mjs → serve-DpsV0mag.mjs} +599 -26
- package/dist/store-Bpdo9Syo.mjs +2 -0
- package/dist/{store-BbvSi3KK.mjs → store-xeJRhBtO.mjs} +2 -0
- package/dist/types-BFIvwByC.mjs +2 -0
- package/dist/{types-F61_hxmG.mjs → types-CxrzVXel.mjs} +9 -5
- package/dist/{updateChecker-CCLVVdH0.mjs → updateChecker-Boq0RruU.mjs} +7 -29
- package/package.json +17 -14
- package/dist/BubblewrapRuntime-5bLPTwEC.mjs +0 -72
- package/dist/SandboxRuntimeAdapter-BgLUVTJL.mjs +0 -57
- package/dist/SandboxRuntimeAdapter-Bt1wPpld.mjs +0 -2
- package/dist/SeatbeltRuntime-C_Y8q8Mr.mjs +0 -124
- package/dist/buildToolSearch-D9GEK91u.mjs +0 -2351
- package/dist/dist-Ul2qwn5x.mjs +0 -624
- package/dist/store-BYeE0shc.mjs +0 -2
- package/dist/types-I45lMh7Q.mjs +0 -2
|
@@ -1,10 +1,17 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import {
|
|
3
|
-
import {
|
|
4
|
-
import {
|
|
2
|
+
import { C as NotAuthenticatedError, T as parseApiUrl, t as ConfigStore, v as requireApiUrl } from "./ConfigStore-CP1W86Ui.mjs";
|
|
3
|
+
import { c as resolveSupportedMimeType, i as parseRetryAfterSeconds, r as createClient, t as B4mApiError } from "./dist-BPhZ0dCz.mjs";
|
|
4
|
+
import { At as replacePromptVariables, Bt as ttsBase64ResponseSchema, D as CreateArtifactRequestSchema, Et as joinReplySlots, F as GENERATED_IMAGE_EXTENSION_RE, Ht as ttsResponseTooLargeSchema, I as ImageModels, L as ImagePromptResolutionSchema, O as DEFAULT_TTS_PROVIDER, Ot as questReplyText, Rt as supportedVoiceGenerationVendor, Vt as ttsRequestSchema, at as buildPromptContext, b as BriefcasePromptIdSchema, c as AGENT_QUEST_MANIFEST, dt as generatedAudioResponseSchema, g as ArtifactTypeSchema, l as AGENT_QUEST_MCP_URI, m as ApiKeyScope, q as PROMPT_TEXT_MAX, s as AGENT_QUEST_ID, t as logger, tt as VisibilitySchema, v as BRIEFCASE_CATALOG_QUERIES } from "./Logger-3RbeTZ9o.mjs";
|
|
5
|
+
import { n as isProviderKeyFailure, t as ApiClient } from "./ApiClient-Yp2LPlX3.mjs";
|
|
6
|
+
import { E as HuggingFaceHub, F as curatedRunner, G as ollamaLibraryLayers, z as isAbliteratedModel } from "./dist-K7a9yOUb.mjs";
|
|
7
|
+
import { G as NO_LICENSE, J as abortable, Q as formatBytes, U as CancelledError, X as clean, Y as buildTag, Z as findInstalledModel, _ as shellWord, _t as resolveRuntimeTarget, bt as shortDigest, c as requireManageable, dt as removeInstalled, et as hadTagBefore, f as serverFetch, ft as requireInstalledReviewed, g as withSignal, gt as requireUnchangedManifest, ht as requireUnchangedLicenses, l as resolveServerTarget, lt as planPull, mt as requireReviewedLayers, n as findModelServer, nt as hubAccessMessage, o as noSuchServer, ot as licenseName, pt as requireRemovable, r as loadModelServers, rt as installedUncheckedMessage, st as listInstalled, t as defaultOn, tt as hiddenAbliteratedMessage, ut as rankSearchHits, vt as runtimeLabel, xt as readOllamaManifest, yt as sameModelName } from "./modelServers-B7zI5XnO.mjs";
|
|
8
|
+
import { i as fitForPlan, o as machineReader, s as createCliCuratedList, t as FIT_LABELS } from "./fit-BOnDsgbk.mjs";
|
|
9
|
+
import { basename, resolve, sep } from "node:path";
|
|
10
|
+
import { constants } from "node:fs";
|
|
5
11
|
import { z as z$1 } from "zod";
|
|
6
12
|
import { isAxiosError } from "axios";
|
|
7
13
|
import { createHash, randomBytes, randomUUID, timingSafeEqual } from "node:crypto";
|
|
14
|
+
import { open, realpath } from "node:fs/promises";
|
|
8
15
|
import { Writable } from "node:stream";
|
|
9
16
|
import { createServer } from "node:http";
|
|
10
17
|
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
|
|
@@ -217,6 +224,35 @@ var B4mApiClient = class {
|
|
|
217
224
|
async getFile(fileId) {
|
|
218
225
|
return this.client.get(`/api/files/${encodeURIComponent(fileId)}`);
|
|
219
226
|
}
|
|
227
|
+
async requestFileUpload(file) {
|
|
228
|
+
return this.client.post("/api/files/generate-presigned-urls-batch", { files: [file] });
|
|
229
|
+
}
|
|
230
|
+
async uploadFileBytes(uploadUrl, bytes, mimeType) {
|
|
231
|
+
const headers = {
|
|
232
|
+
"Content-Type": mimeType,
|
|
233
|
+
"If-None-Match": "*"
|
|
234
|
+
};
|
|
235
|
+
if (uploadUrl.startsWith("//")) throw new Error("Unexpected file upload URL");
|
|
236
|
+
const url = new URL(uploadUrl, this.baseURL);
|
|
237
|
+
if (uploadUrl.startsWith("/")) {
|
|
238
|
+
if (url.origin !== new URL(this.baseURL).origin || !/^\/api\/files\/[^/]+\/upload$/.test(url.pathname)) throw new Error("Unexpected file upload proxy URL");
|
|
239
|
+
await this.client.put(url.pathname, bytes, { headers });
|
|
240
|
+
return;
|
|
241
|
+
}
|
|
242
|
+
if (url.protocol !== "https:" && url.protocol !== "http:") throw new Error("Unexpected file upload URL");
|
|
243
|
+
const res = await fetch(url, {
|
|
244
|
+
method: "PUT",
|
|
245
|
+
headers,
|
|
246
|
+
body: bytes
|
|
247
|
+
});
|
|
248
|
+
if (!res.ok) throw new Error(`file upload failed (${res.status})`);
|
|
249
|
+
}
|
|
250
|
+
async deleteFile(fileId) {
|
|
251
|
+
await this.client.delete(`/api/files/${encodeURIComponent(fileId)}`);
|
|
252
|
+
}
|
|
253
|
+
async attachFileToProject(fileId, projectId) {
|
|
254
|
+
await this.client.post(`/api/projects/${encodeURIComponent(projectId)}/files`, { fileIds: [fileId] });
|
|
255
|
+
}
|
|
220
256
|
/** Generate a sound effect. The SDK requests base64 and rebuilds an old server's raw-bytes answer. */
|
|
221
257
|
async generateSoundEffect(args) {
|
|
222
258
|
const body = {
|
|
@@ -343,12 +379,16 @@ var B4mApiClient = class {
|
|
|
343
379
|
/**
|
|
344
380
|
* PUT one draft file to the URL upload-url minted. Plain fetch, never the app
|
|
345
381
|
* client: that client injects auth headers, which break an S3 presigned
|
|
346
|
-
* signature. Self-host mints a relative proxy URL, so resolve against baseURL
|
|
382
|
+
* signature. Self-host mints a relative proxy URL, so resolve against baseURL,
|
|
383
|
+
* and sends its upload token in the `headers` the entry came with.
|
|
347
384
|
*/
|
|
348
|
-
async uploadPublishDraftFile(
|
|
349
|
-
const res = await fetch(new URL(
|
|
385
|
+
async uploadPublishDraftFile(upload, body, mimeType) {
|
|
386
|
+
const res = await fetch(new URL(upload.url, this.baseURL), {
|
|
350
387
|
method: "PUT",
|
|
351
|
-
headers: {
|
|
388
|
+
headers: {
|
|
389
|
+
...upload.headers,
|
|
390
|
+
"Content-Type": mimeType
|
|
391
|
+
},
|
|
352
392
|
body
|
|
353
393
|
});
|
|
354
394
|
if (!res.ok) throw new Error(`publish upload failed (${res.status})`);
|
|
@@ -377,11 +417,20 @@ var B4mApiClient = class {
|
|
|
377
417
|
* an empty list when the key is not found or cannot be told apart from another, so a caller that cannot be
|
|
378
418
|
* identified is never treated as scoped. Stored prefixes differ in length (older keys keep a shorter one),
|
|
379
419
|
* and the list can include other keys, so the longest matching prefix wins and a tie at that length is refused.
|
|
420
|
+
* Also undefined when the key may not list keys (403: the list needs `api-keys:manage`), since that says
|
|
421
|
+
* nothing about the key's other scopes; the route the caller is about to use still enforces its own.
|
|
380
422
|
*/
|
|
381
423
|
async getOwnKeyScopes() {
|
|
382
424
|
const apiKey = this.apiKey;
|
|
383
425
|
if (!apiKey) return void 0;
|
|
384
|
-
|
|
426
|
+
let response;
|
|
427
|
+
try {
|
|
428
|
+
response = await this.client.get("/api/user-api-keys", { timeout: SOLVER_CATALOG_TIMEOUT_MS });
|
|
429
|
+
} catch (error) {
|
|
430
|
+
if (httpFailure(error)?.status === 403) return void 0;
|
|
431
|
+
throw error;
|
|
432
|
+
}
|
|
433
|
+
const matches = keyScopeListSchema.parse(response).filter((k) => k.status === "active" && !!k.keyPrefix && apiKey.startsWith(k.keyPrefix));
|
|
385
434
|
const longest = matches.reduce((length, key) => Math.max(length, key.keyPrefix?.length ?? 0), 0);
|
|
386
435
|
const best = matches.filter((k) => k.keyPrefix?.length === longest);
|
|
387
436
|
return best.length === 1 ? best[0].scopes ?? [] : [];
|
|
@@ -648,6 +697,12 @@ const TOOL_META = [
|
|
|
648
697
|
description: "Fetch a file's metadata and a signed download URL.",
|
|
649
698
|
scope: "files:read"
|
|
650
699
|
},
|
|
700
|
+
{
|
|
701
|
+
name: "upload_file",
|
|
702
|
+
title: "Upload file",
|
|
703
|
+
description: "Upload a local file or base64 bytes to the file browser. path reads a file the MCP server process can access, except hidden files and anything under a hidden directory; files over 100 MB are refused. Returns its id and pending ingestion state; indexing runs asynchronously. Optional projectId adds it to a project (also requires projects:write).",
|
|
704
|
+
scope: "files:write"
|
|
705
|
+
},
|
|
651
706
|
{
|
|
652
707
|
name: "generate_sound_effect",
|
|
653
708
|
title: "Generate sound effect",
|
|
@@ -776,8 +831,15 @@ const listFilesShape = {
|
|
|
776
831
|
page: z$1.number().int().min(1).default(1).describe("1-based page number; request the next page when hasMore is true")
|
|
777
832
|
};
|
|
778
833
|
const getFileShape = { fileId: z$1.string().describe("The file id") };
|
|
834
|
+
const uploadFileShape = {
|
|
835
|
+
path: z$1.string().min(1).optional().describe("Local path on the machine running the MCP server"),
|
|
836
|
+
base64: z$1.string().min(1).optional().describe("Base64-encoded file bytes; use instead of path"),
|
|
837
|
+
name: z$1.string().min(1).optional().describe("File name; defaults to the basename of path"),
|
|
838
|
+
contentType: z$1.string().min(1).optional().describe("MIME type; otherwise inferred from the file name"),
|
|
839
|
+
projectId: z$1.string().min(1).optional().describe("Project to add the uploaded file to; requires projects:write")
|
|
840
|
+
};
|
|
779
841
|
const generateSoundEffectShape = {
|
|
780
|
-
text: z$1.string().min(1).max(
|
|
842
|
+
text: z$1.string().min(1).max(450).describe("Text description of the sound effect to generate"),
|
|
781
843
|
provider: z$1.enum(["elevenlabs"]).default("elevenlabs").describe("Sound-generation provider"),
|
|
782
844
|
durationSeconds: z$1.number().min(.5).max(30).optional().describe("Length of the sound in seconds (0.5-30); omit to let the provider choose"),
|
|
783
845
|
promptInfluence: z$1.number().min(0).max(1).optional().describe("How strictly to follow the prompt (0 = loose, 1 = strict)"),
|
|
@@ -977,6 +1039,66 @@ async function listFiles(client, args) {
|
|
|
977
1039
|
async function getFile(client, args) {
|
|
978
1040
|
return client.getFile(args.fileId);
|
|
979
1041
|
}
|
|
1042
|
+
const UPLOAD_FILE_MAX_BYTES = 104857600;
|
|
1043
|
+
async function uploadFile(client, args) {
|
|
1044
|
+
if (Boolean(args.path) === Boolean(args.base64)) throw new Error("Provide exactly one of path or base64");
|
|
1045
|
+
const fileName = args.name ?? (args.path ? basename(args.path) : void 0);
|
|
1046
|
+
if (!fileName || fileName === "." || fileName === "..") throw new Error("A file name is required");
|
|
1047
|
+
const tooLarge = () => /* @__PURE__ */ new Error(`File exceeds the ${UPLOAD_FILE_MAX_BYTES / 1048576} MB upload limit`);
|
|
1048
|
+
let bytes;
|
|
1049
|
+
if (args.path) {
|
|
1050
|
+
const target = await realpath(args.path);
|
|
1051
|
+
const isHidden = (p) => p.split(sep).some((seg) => seg.startsWith(".") && seg !== "." && seg !== "..");
|
|
1052
|
+
if (isHidden(resolve(args.path)) || isHidden(target)) throw new Error(`${args.path} is a hidden file or inside a hidden directory; upload_file does not read those`);
|
|
1053
|
+
const file = await open(target, constants.O_RDONLY | constants.O_NONBLOCK);
|
|
1054
|
+
try {
|
|
1055
|
+
const info = await file.stat();
|
|
1056
|
+
if (!info.isFile()) throw new Error(`${args.path} is not a regular file`);
|
|
1057
|
+
if (info.size > UPLOAD_FILE_MAX_BYTES) throw tooLarge();
|
|
1058
|
+
bytes = await file.readFile();
|
|
1059
|
+
if (bytes.length > UPLOAD_FILE_MAX_BYTES) throw tooLarge();
|
|
1060
|
+
} finally {
|
|
1061
|
+
await file.close();
|
|
1062
|
+
}
|
|
1063
|
+
} else {
|
|
1064
|
+
let b64 = args.base64.replace(/\s/g, "").replace(/-/g, "+").replace(/_/g, "/");
|
|
1065
|
+
if (b64.length % 4 === 2 || b64.length % 4 === 3) b64 += "=".repeat(4 - b64.length % 4);
|
|
1066
|
+
if (b64.length % 4 !== 0 || !/^[A-Za-z0-9+/]*={0,2}$/.test(b64)) throw new Error("File bytes must be nonempty and valid base64");
|
|
1067
|
+
const padding = b64.endsWith("==") ? 2 : b64.endsWith("=") ? 1 : 0;
|
|
1068
|
+
if (b64.length / 4 * 3 - padding > UPLOAD_FILE_MAX_BYTES) throw tooLarge();
|
|
1069
|
+
bytes = Buffer.from(b64, "base64");
|
|
1070
|
+
}
|
|
1071
|
+
if (!bytes.length) throw new Error("File bytes must be nonempty and valid base64");
|
|
1072
|
+
const resolved = resolveSupportedMimeType(fileName, args.contentType);
|
|
1073
|
+
if (!resolved.supported) throw new Error(`Unsupported file type for ${fileName}` + (fileName.includes(".") ? "" : "; pass contentType for a name without an extension"));
|
|
1074
|
+
const mimeType = resolved.mimeType;
|
|
1075
|
+
if (args.projectId) {
|
|
1076
|
+
const scopes = await client.getOwnKeyScopes().catch(() => void 0);
|
|
1077
|
+
if (scopes && !scopes.includes(ApiKeyScope.WRITE_PROJECTS)) throw new Error("projectId requires an API key with the projects:write scope");
|
|
1078
|
+
}
|
|
1079
|
+
const upload = (await client.requestFileUpload({
|
|
1080
|
+
fileName,
|
|
1081
|
+
fileSize: bytes.length,
|
|
1082
|
+
mimeType
|
|
1083
|
+
})).files[0];
|
|
1084
|
+
if (!upload?.fileId || !upload.url) throw new Error("File upload request returned no upload URL");
|
|
1085
|
+
const fileId = upload.fileId;
|
|
1086
|
+
try {
|
|
1087
|
+
await client.uploadFileBytes(upload.url, bytes, mimeType);
|
|
1088
|
+
} catch (err) {
|
|
1089
|
+
await client.deleteFile(fileId).catch(() => {});
|
|
1090
|
+
throw new Error(`Upload for file ${fileId} failed: ${mapApiError(err, client.baseURL, "files:write")}`);
|
|
1091
|
+
}
|
|
1092
|
+
try {
|
|
1093
|
+
if (args.projectId) await client.attachFileToProject(fileId, args.projectId);
|
|
1094
|
+
} catch (err) {
|
|
1095
|
+
throw new Error(`File ${fileId} was uploaded but association failed: ${mapApiError(err, client.baseURL, "projects:write")}`);
|
|
1096
|
+
}
|
|
1097
|
+
return {
|
|
1098
|
+
fileId,
|
|
1099
|
+
ingestionState: "pending"
|
|
1100
|
+
};
|
|
1101
|
+
}
|
|
980
1102
|
async function generateSoundEffect(client, args) {
|
|
981
1103
|
return generatedAudioResult(await client.generateSoundEffect(args), { provider: args.provider });
|
|
982
1104
|
}
|
|
@@ -1149,13 +1271,14 @@ async function publishArtifact(client, args) {
|
|
|
1149
1271
|
if (!body) throw new Error(`artifact ${artifact.id} has no content to publish`);
|
|
1150
1272
|
const artifactType = ArtifactTypeSchema.safeParse(artifact.type);
|
|
1151
1273
|
if (!artifactType.success) throw new Error(`artifact ${artifact.id} has an unsupported type (${String(artifact.type)})`);
|
|
1152
|
-
if (typeof artifact.userId !== "string") throw new Error(`artifact ${artifact.id} has no owner to publish under`);
|
|
1153
1274
|
const storedTitle = typeof artifact.title === "string" ? artifact.title : "";
|
|
1154
1275
|
const title = (args.title ?? storedTitle).trim().slice(0, PUBLISH_TITLE_MAX) || PUBLISH_FALLBACK_TITLE;
|
|
1155
1276
|
const existing = await client.findPublishedArtifact(artifact.id);
|
|
1277
|
+
const ownerScope = existing?.scopeId ?? artifact.userId;
|
|
1278
|
+
if (typeof ownerScope !== "string") throw new Error(`artifact ${artifact.id} can only be published by its owner`);
|
|
1156
1279
|
const request = {
|
|
1157
1280
|
tier: existing?.tier ?? "user",
|
|
1158
|
-
scopeId:
|
|
1281
|
+
scopeId: ownerScope,
|
|
1159
1282
|
slug: existing?.slug ?? artifactSlug(title, artifact.id),
|
|
1160
1283
|
title,
|
|
1161
1284
|
visibility: args.visibility ?? existing?.visibility ?? PUBLISH_DEFAULT_VISIBILITY,
|
|
@@ -1175,7 +1298,7 @@ async function publishArtifact(client, args) {
|
|
|
1175
1298
|
const draft = existing ? await client.requestPublishUpload(request) : await openPublishDraft(client, request);
|
|
1176
1299
|
const upload = draft.uploadUrls.find((u) => u.path === PUBLISH_INDEX_PATH);
|
|
1177
1300
|
if (!upload) throw new Error(`publish draft ${draft.draftId} returned no upload URL for ${PUBLISH_INDEX_PATH}`);
|
|
1178
|
-
await client.uploadPublishDraftFile(upload
|
|
1301
|
+
await client.uploadPublishDraftFile(upload, body, PUBLISH_INDEX_MIME);
|
|
1179
1302
|
const published = await client.finalizePublish(draft.draftId);
|
|
1180
1303
|
return {
|
|
1181
1304
|
publicId: published.publicId,
|
|
@@ -1580,6 +1703,11 @@ function registerTools(server, client) {
|
|
|
1580
1703
|
description: meta("get_file").description,
|
|
1581
1704
|
inputSchema: getFileShape
|
|
1582
1705
|
}, (args) => run("files:read", () => getFile(client, args)));
|
|
1706
|
+
server.registerTool("upload_file", {
|
|
1707
|
+
title: meta("upload_file").title,
|
|
1708
|
+
description: meta("upload_file").description,
|
|
1709
|
+
inputSchema: uploadFileShape
|
|
1710
|
+
}, (args) => run("files:write", () => uploadFile(client, args)));
|
|
1583
1711
|
server.registerTool("generate_sound_effect", {
|
|
1584
1712
|
title: meta("generate_sound_effect").title,
|
|
1585
1713
|
description: meta("generate_sound_effect").description,
|
|
@@ -1671,6 +1799,421 @@ function registerTools(server, client) {
|
|
|
1671
1799
|
}, (args) => runBob("bob:read", () => bobRunsLeft(client, args)));
|
|
1672
1800
|
}
|
|
1673
1801
|
//#endregion
|
|
1802
|
+
//#region src/mcp/modelTools.ts
|
|
1803
|
+
const serverShape = z$1.string().trim().min(1).max(100).optional().describe("A model server saved in Desktop, by its name there (the one `b4m models servers` lists); omit it for the user's local Ollama");
|
|
1804
|
+
const listShape = { server: serverShape };
|
|
1805
|
+
/** How long the user has to answer an elicitation prompt (ms). */
|
|
1806
|
+
const ELICITATION_TIMEOUT_MS = 6e5;
|
|
1807
|
+
const PROGRESS_INTERVAL_MS = 500;
|
|
1808
|
+
const SEARCH_LIMIT = 20;
|
|
1809
|
+
const MODEL_TOOL_NAMES = [
|
|
1810
|
+
"models_list",
|
|
1811
|
+
"models_search",
|
|
1812
|
+
"models_pull",
|
|
1813
|
+
"models_remove"
|
|
1814
|
+
];
|
|
1815
|
+
const searchShape = {
|
|
1816
|
+
query: z$1.string().trim().min(1).max(200).describe("Search text, e.g. \"qwen2.5 0.5b\""),
|
|
1817
|
+
limit: z$1.number().int().min(1).max(50).default(SEARCH_LIMIT).describe("Maximum repos to search"),
|
|
1818
|
+
includeAbliterated: z$1.boolean().default(false).describe("Also return abliterated or uncensored builds, labelled notRecommended and listed after every other hit. Pass true only when the user asks for them.")
|
|
1819
|
+
};
|
|
1820
|
+
const pullShape = {
|
|
1821
|
+
server: serverShape,
|
|
1822
|
+
ref: z$1.string().trim().min(1).max(300).describe("An Ollama name (model[:tag]) or a Hugging Face GGUF repo (owner/repo[:quant], Q4_K_M by default)"),
|
|
1823
|
+
force: z$1.boolean().default(false).describe("Go ahead when the fit check rates the model too large for this machine. Pass true only when the user, told the verdict, explicitly asks to download it anyway. It never skips the user approval.")
|
|
1824
|
+
};
|
|
1825
|
+
const removeShape = {
|
|
1826
|
+
server: serverShape,
|
|
1827
|
+
name: z$1.string().trim().min(1).max(300).describe("The installed model name, as models_list shows it")
|
|
1828
|
+
};
|
|
1829
|
+
const baseLicense = (license) => license.base ? [license.base] : [];
|
|
1830
|
+
/** What the user must see before approving a pull. */
|
|
1831
|
+
function pullSummary(plan, fit) {
|
|
1832
|
+
const runtime = runtimeLabel(plan.target);
|
|
1833
|
+
if (plan.kind === "ollama") {
|
|
1834
|
+
const { license } = plan;
|
|
1835
|
+
return {
|
|
1836
|
+
source: "ollama",
|
|
1837
|
+
model: clean(plan.name),
|
|
1838
|
+
sizeBytes: plan.manifest.sizeBytes,
|
|
1839
|
+
size: formatBytes(plan.manifest.sizeBytes),
|
|
1840
|
+
revision: null,
|
|
1841
|
+
digest: shortDigest(plan.manifest.digest),
|
|
1842
|
+
licenses: [license.label, ...baseLicense(license)],
|
|
1843
|
+
license: {
|
|
1844
|
+
label: licenseName(license),
|
|
1845
|
+
link: license.link,
|
|
1846
|
+
permissive: !license.restricted
|
|
1847
|
+
},
|
|
1848
|
+
acknowledgementRequired: license.restricted,
|
|
1849
|
+
runtime,
|
|
1850
|
+
fit
|
|
1851
|
+
};
|
|
1852
|
+
}
|
|
1853
|
+
const { detail, build, license } = plan;
|
|
1854
|
+
return {
|
|
1855
|
+
source: "huggingface",
|
|
1856
|
+
model: plan.id,
|
|
1857
|
+
label: clean(build.label),
|
|
1858
|
+
files: build.files.map((file) => ({
|
|
1859
|
+
path: clean(file.path),
|
|
1860
|
+
sizeBytes: file.sizeBytes
|
|
1861
|
+
})),
|
|
1862
|
+
sizeBytes: build.sizeBytes,
|
|
1863
|
+
size: formatBytes(build.sizeBytes),
|
|
1864
|
+
...plan.projectorBytes > 0 && {
|
|
1865
|
+
visionProjectorUpToBytes: plan.projectorBytes,
|
|
1866
|
+
visionProjectorUpTo: formatBytes(plan.projectorBytes)
|
|
1867
|
+
},
|
|
1868
|
+
revision: clean(detail.revision),
|
|
1869
|
+
licenses: [...detail.licenses.map(clean), ...baseLicense(license)],
|
|
1870
|
+
license: {
|
|
1871
|
+
label: licenseName(license),
|
|
1872
|
+
link: license.link,
|
|
1873
|
+
permissive: !license.restricted
|
|
1874
|
+
},
|
|
1875
|
+
acknowledgementRequired: license.restricted,
|
|
1876
|
+
gated: detail.gated,
|
|
1877
|
+
runtime,
|
|
1878
|
+
fit,
|
|
1879
|
+
...isAbliteratedModel(detail) && { caution: "This is an abliterated or uncensored build." },
|
|
1880
|
+
...detail.ollamaNeedsSshKey && { sshKeyNote: `Ollama downloads ${detail.private ? "private" : "gated"} repos with its own key: add ~/.ollama/id_ed25519.pub of the Ollama host at https://huggingface.co/settings/keys if you have not.` }
|
|
1881
|
+
};
|
|
1882
|
+
}
|
|
1883
|
+
/** The download size, plus the vision projector Ollama's Hugging Face registry adds to the pull. */
|
|
1884
|
+
function sizeText(summary) {
|
|
1885
|
+
return "visionProjectorUpTo" in summary && summary.visionProjectorUpTo ? `${summary.size} plus a vision projector of up to ${summary.visionProjectorUpTo}` : summary.size;
|
|
1886
|
+
}
|
|
1887
|
+
function gatedLine(summary) {
|
|
1888
|
+
if (!("gated" in summary) || !summary.gated) return [];
|
|
1889
|
+
return [`Gated: yes (${summary.gated === "manual" ? "manual approval" : "automatic approval"}), access granted.`];
|
|
1890
|
+
}
|
|
1891
|
+
function licenseSentence(summary) {
|
|
1892
|
+
const { license } = summary;
|
|
1893
|
+
if (license.permissive) return `License: ${license.label}.`;
|
|
1894
|
+
if (license.label === "none declared") return `License: ${NO_LICENSE}. Read the model page first: ${license.link}`;
|
|
1895
|
+
return `License: ${license.label}, not all permissive. Read ${license.link} before accepting.`;
|
|
1896
|
+
}
|
|
1897
|
+
function pullMessage(summary) {
|
|
1898
|
+
return [
|
|
1899
|
+
`Download ${summary.model}${"label" in summary ? ` ${summary.label}` : ""} (${sizeText(summary)}) to ${summary.runtime}?`,
|
|
1900
|
+
`Fit: ${FIT_LABELS[summary.fit.verdict]}. ${summary.fit.detail}`,
|
|
1901
|
+
..."files" in summary ? [`File: ${summary.files.map((file) => file.path).join(", ")}`] : [],
|
|
1902
|
+
...summary.revision ? [`Revision: ${summary.revision}`] : [],
|
|
1903
|
+
..."digest" in summary ? [`Digest: ${summary.digest}`] : [],
|
|
1904
|
+
licenseSentence(summary),
|
|
1905
|
+
...gatedLine(summary),
|
|
1906
|
+
..."sshKeyNote" in summary && summary.sshKeyNote ? [summary.sshKeyNote] : [],
|
|
1907
|
+
..."caution" in summary && summary.caution ? [summary.caution] : []
|
|
1908
|
+
].join("\n");
|
|
1909
|
+
}
|
|
1910
|
+
function pullElicitation(summary) {
|
|
1911
|
+
return {
|
|
1912
|
+
mode: "form",
|
|
1913
|
+
message: pullMessage(summary),
|
|
1914
|
+
requestedSchema: {
|
|
1915
|
+
type: "object",
|
|
1916
|
+
properties: {
|
|
1917
|
+
download: {
|
|
1918
|
+
type: "boolean",
|
|
1919
|
+
title: `Download ${sizeText(summary)}`,
|
|
1920
|
+
default: false
|
|
1921
|
+
},
|
|
1922
|
+
...summary.acknowledgementRequired && { acceptLicense: {
|
|
1923
|
+
type: "boolean",
|
|
1924
|
+
title: `I have read and accept the license: ${summary.license.label}`,
|
|
1925
|
+
description: summary.license.link,
|
|
1926
|
+
default: false
|
|
1927
|
+
} }
|
|
1928
|
+
},
|
|
1929
|
+
required: summary.acknowledgementRequired ? ["download", "acceptLicense"] : ["download"]
|
|
1930
|
+
}
|
|
1931
|
+
};
|
|
1932
|
+
}
|
|
1933
|
+
/** The `b4m models` command that does the same on the same runtime, asking the user in their terminal. */
|
|
1934
|
+
function terminalCommand(target, subcommand, subject, flags = "") {
|
|
1935
|
+
const host = target.source === "env" ? `B4M_OLLAMA_HOST=${shellWord(target.runtime.baseUrl)} ` : "";
|
|
1936
|
+
const server = target.server ? ` --server ${shellWord(target.server.name)}` : "";
|
|
1937
|
+
return `${host}b4m models ${subcommand} ${shellWord(subject)}${server}${flags}`;
|
|
1938
|
+
}
|
|
1939
|
+
/** The ref `b4m models pull` resolves to the same build. */
|
|
1940
|
+
function pullRef(plan) {
|
|
1941
|
+
if (plan.kind === "ollama") return plan.name;
|
|
1942
|
+
return `${plan.detail.id}:${buildTag(plan.build)}`;
|
|
1943
|
+
}
|
|
1944
|
+
function pullProgress(extra, redact) {
|
|
1945
|
+
const progressToken = extra._meta?.progressToken;
|
|
1946
|
+
if (progressToken === void 0) return void 0;
|
|
1947
|
+
let sent = 0;
|
|
1948
|
+
let lastStatus = "";
|
|
1949
|
+
let lastSent = 0;
|
|
1950
|
+
return ({ status, completedBytes, totalBytes }) => {
|
|
1951
|
+
const now = Date.now();
|
|
1952
|
+
if (status === lastStatus && now - lastSent < PROGRESS_INTERVAL_MS) return;
|
|
1953
|
+
lastStatus = status;
|
|
1954
|
+
lastSent = now;
|
|
1955
|
+
sent = Math.max(sent, completedBytes);
|
|
1956
|
+
extra.sendNotification({
|
|
1957
|
+
method: "notifications/progress",
|
|
1958
|
+
params: {
|
|
1959
|
+
progressToken,
|
|
1960
|
+
progress: sent,
|
|
1961
|
+
...totalBytes ? { total: totalBytes } : {},
|
|
1962
|
+
message: clean(redact ? redact(status) : status)
|
|
1963
|
+
}
|
|
1964
|
+
}).catch(() => {});
|
|
1965
|
+
};
|
|
1966
|
+
}
|
|
1967
|
+
function localModelToolsDeps(configStore) {
|
|
1968
|
+
let hub;
|
|
1969
|
+
const curatedList = createCliCuratedList({ offline: false });
|
|
1970
|
+
return {
|
|
1971
|
+
hub: () => hub ??= new HuggingFaceHub({ token: process.env.HF_TOKEN }),
|
|
1972
|
+
ollamaRegistry: (name, signal) => readOllamaManifest(name, signal),
|
|
1973
|
+
libraryLayers: (ref, signal) => ollamaLibraryLayers(ref, { signal }),
|
|
1974
|
+
resolveRuntime: async () => resolveRuntimeTarget({
|
|
1975
|
+
env: process.env.B4M_OLLAMA_HOST,
|
|
1976
|
+
config: (await configStore?.load())?.ollamaHost
|
|
1977
|
+
}),
|
|
1978
|
+
defaultModel: async () => (await configStore?.load())?.defaultModel,
|
|
1979
|
+
machine: machineReader(),
|
|
1980
|
+
curated: () => curatedList.manifest(),
|
|
1981
|
+
servers: {
|
|
1982
|
+
load: () => loadModelServers(),
|
|
1983
|
+
secret: async () => {
|
|
1984
|
+
const credentials = await configStore?.readModelServerCredentials();
|
|
1985
|
+
return (id) => credentials?.[id]?.secret;
|
|
1986
|
+
}
|
|
1987
|
+
}
|
|
1988
|
+
};
|
|
1989
|
+
}
|
|
1990
|
+
/**
|
|
1991
|
+
* Register models_list, models_search, models_pull and models_remove: the `b4m models` operations on the
|
|
1992
|
+
* user's local runtime. Pull and remove act only on an answer the user gives through MCP elicitation; no tool
|
|
1993
|
+
* argument approves them, so a client without elicitation gets a preview and the terminal command instead.
|
|
1994
|
+
* Stdio only: these change the machine the server runs on.
|
|
1995
|
+
*/
|
|
1996
|
+
function registerModelTools(server, deps) {
|
|
1997
|
+
const canElicit = () => Boolean(server.server.getClientCapabilities()?.elicitation?.form);
|
|
1998
|
+
const sources = (signal, from = deps) => ({
|
|
1999
|
+
...from,
|
|
2000
|
+
signal
|
|
2001
|
+
});
|
|
2002
|
+
/** The deps with the runtime swapped for a saved server when the call names one; pull and remove need it manageable. */
|
|
2003
|
+
const scoped = async (name, manage, signal) => {
|
|
2004
|
+
if (!name) return deps;
|
|
2005
|
+
if (!deps.servers) throw new Error("Model servers are not available here.");
|
|
2006
|
+
const loaded = await abortable(deps.servers.load(), signal);
|
|
2007
|
+
const server = findModelServer(loaded.servers, name);
|
|
2008
|
+
if (!server) throw noSuchServer(loaded, name);
|
|
2009
|
+
if (manage) requireManageable(server);
|
|
2010
|
+
const secret = (await abortable(deps.servers.secret(), signal))(server.id);
|
|
2011
|
+
const fetch = withSignal(serverFetch(server, secret, deps.servers.sshFetchFor), signal);
|
|
2012
|
+
return {
|
|
2013
|
+
...deps,
|
|
2014
|
+
resolveRuntime: () => abortable(resolveServerTarget(server, secret, fetch), signal)
|
|
2015
|
+
};
|
|
2016
|
+
};
|
|
2017
|
+
const run = async (fn) => {
|
|
2018
|
+
try {
|
|
2019
|
+
return await fn();
|
|
2020
|
+
} catch (error) {
|
|
2021
|
+
if (error instanceof CancelledError) return errorResult("Cancelled. Nothing was changed.");
|
|
2022
|
+
return errorResult(hubAccessMessage(error, () => deps.hub().endpoint) ?? clean(error instanceof Error ? error.message : String(error)));
|
|
2023
|
+
}
|
|
2024
|
+
};
|
|
2025
|
+
const ask = (params, extra) => server.server.elicitInput(params, {
|
|
2026
|
+
signal: extra.signal,
|
|
2027
|
+
timeout: ELICITATION_TIMEOUT_MS,
|
|
2028
|
+
relatedRequestId: extra.requestId
|
|
2029
|
+
});
|
|
2030
|
+
server.registerTool("models_list", {
|
|
2031
|
+
title: "List local models",
|
|
2032
|
+
description: "List the models installed on the user's local runtime (Ollama), or on one of the model servers saved in Desktop when `server` names it, with size, quantization and capabilities, and which one is loaded or the CLI default.",
|
|
2033
|
+
inputSchema: listShape,
|
|
2034
|
+
annotations: {
|
|
2035
|
+
readOnlyHint: true,
|
|
2036
|
+
openWorldHint: true
|
|
2037
|
+
}
|
|
2038
|
+
}, (args, extra) => run(async () => {
|
|
2039
|
+
const from = await scoped(args.server, false, extra.signal);
|
|
2040
|
+
const target = await abortable(from.resolveRuntime(), extra.signal);
|
|
2041
|
+
const models = await listInstalled(target.runtime, defaultOn(target, await deps.defaultModel()), extra.signal);
|
|
2042
|
+
const { kind, baseUrl } = target.runtime;
|
|
2043
|
+
return toResult({
|
|
2044
|
+
runtime: {
|
|
2045
|
+
kind,
|
|
2046
|
+
baseUrl,
|
|
2047
|
+
source: target.source,
|
|
2048
|
+
...target.server && { server: target.server.name }
|
|
2049
|
+
},
|
|
2050
|
+
models
|
|
2051
|
+
});
|
|
2052
|
+
}));
|
|
2053
|
+
server.registerTool("models_search", {
|
|
2054
|
+
title: "Search local models",
|
|
2055
|
+
description: "Search Hugging Face for GGUF models that run locally, with each repo's declared licenses, gated status and popularity. A repo is permissive only if every license it declares is permissive. Abliterated and uncensored builds are left out unless includeAbliterated is true; then they are marked notRecommended and come last. Never suggest or recommend one. Downloads nothing.",
|
|
2056
|
+
inputSchema: searchShape,
|
|
2057
|
+
annotations: {
|
|
2058
|
+
readOnlyHint: true,
|
|
2059
|
+
openWorldHint: true
|
|
2060
|
+
}
|
|
2061
|
+
}, (args, extra) => run(async () => {
|
|
2062
|
+
const page = await deps.hub().search({
|
|
2063
|
+
query: args.query,
|
|
2064
|
+
limit: args.limit,
|
|
2065
|
+
signal: extra.signal
|
|
2066
|
+
});
|
|
2067
|
+
const { hits, hidden } = rankSearchHits(page.models, Boolean(args.includeAbliterated));
|
|
2068
|
+
return toResult({
|
|
2069
|
+
query: args.query,
|
|
2070
|
+
models: hits.map((model) => ({
|
|
2071
|
+
id: model.id,
|
|
2072
|
+
licenses: model.licenses,
|
|
2073
|
+
gated: model.gated,
|
|
2074
|
+
downloads: model.downloads,
|
|
2075
|
+
likes: model.likes,
|
|
2076
|
+
updatedAt: model.updatedAt,
|
|
2077
|
+
baseModels: model.baseModels,
|
|
2078
|
+
...model.notRecommended && { notRecommended: model.notRecommended }
|
|
2079
|
+
})),
|
|
2080
|
+
...hidden > 0 && { hidden: hiddenAbliteratedMessage(hidden) },
|
|
2081
|
+
next: "models_pull shows the build, size and every license, and asks the user before downloading."
|
|
2082
|
+
});
|
|
2083
|
+
}));
|
|
2084
|
+
server.registerTool("models_pull", {
|
|
2085
|
+
title: "Download a local model",
|
|
2086
|
+
description: "Download a model to the user's local Ollama from an Ollama name (model[:tag]) or a Hugging Face GGUF repo (owner/repo[:quant], Q4_K_M by default). Nothing downloads without the user's own approval. When the client supports elicitation, the user is asked directly with the size, file, revision and every license, and a license that is not all permissive needs its own tick. Without elicitation nothing downloads: the result is that preview plus a `b4m models pull` command for the user to run in a terminal, where the CLI asks them. No argument of this tool approves a download. Every preview carries a fit verdict for this machine (fits, tight, too-large or unknown); a too-large model is refused before the user is asked unless force is true, which only lets the user be asked. Gated repos return the steps to get access instead. Refs to hosts other than Hugging Face and Ollama are refused.",
|
|
2087
|
+
inputSchema: pullShape,
|
|
2088
|
+
annotations: {
|
|
2089
|
+
readOnlyHint: false,
|
|
2090
|
+
destructiveHint: false,
|
|
2091
|
+
openWorldHint: true
|
|
2092
|
+
}
|
|
2093
|
+
}, (args, extra) => run(async () => {
|
|
2094
|
+
const from = await scoped(args.server, true, extra.signal);
|
|
2095
|
+
const plan = await planPull(args.ref, sources(extra.signal, from), "models_pull ref");
|
|
2096
|
+
const fit = await abortable(fitForPlan(plan, deps.machine), extra.signal);
|
|
2097
|
+
const summary = pullSummary(plan, fit);
|
|
2098
|
+
const tooLarge = fit.verdict === "too-large";
|
|
2099
|
+
if (tooLarge && !args.force) return toResult({
|
|
2100
|
+
status: "too-large",
|
|
2101
|
+
downloaded: false,
|
|
2102
|
+
...summary,
|
|
2103
|
+
message: fit.gpuUnread ? "Nothing was downloaded: the fit check rates this model too large from system RAM alone, since the GPU could not be read. Tell the user that; if their GPU can hold it and they ask to download it anyway, call again with force: true." : "Nothing was downloaded: the fit check rates this model too large for this machine. Tell the user, and suggest a smaller quant or model. Call again with force: true only if the user then asks to download it anyway."
|
|
2104
|
+
});
|
|
2105
|
+
if (!canElicit()) return toResult({
|
|
2106
|
+
status: "confirm-in-terminal",
|
|
2107
|
+
downloaded: false,
|
|
2108
|
+
...summary,
|
|
2109
|
+
command: terminalCommand(plan.target, "pull", pullRef(plan), tooLarge ? " --force" : ""),
|
|
2110
|
+
userApproval: "Nothing was downloaded. This MCP client cannot ask the user, so the download has to be approved in a terminal: show the user the size and licenses above and give them the command. The CLI shows them again and asks before downloading" + (summary.acknowledgementRequired ? ", and asks them separately to accept the license." : ".")
|
|
2111
|
+
});
|
|
2112
|
+
const answer = await ask(pullElicitation(summary), extra);
|
|
2113
|
+
if (answer.action !== "accept" || answer.content?.download !== true) return toResult({
|
|
2114
|
+
status: "declined",
|
|
2115
|
+
downloaded: false,
|
|
2116
|
+
...summary,
|
|
2117
|
+
message: "The user declined. Nothing was downloaded."
|
|
2118
|
+
});
|
|
2119
|
+
if (summary.acknowledgementRequired && answer.content?.acceptLicense !== true) return toResult({
|
|
2120
|
+
status: "license-not-accepted",
|
|
2121
|
+
downloaded: false,
|
|
2122
|
+
...summary,
|
|
2123
|
+
message: "The user did not accept the license. Nothing was downloaded."
|
|
2124
|
+
});
|
|
2125
|
+
if (plan.kind === "ollama") await requireUnchangedManifest(plan.name, plan.manifest, sources(extra.signal, from));
|
|
2126
|
+
else await requireUnchangedLicenses(plan.hub, plan.detail, plan.license, extra.signal);
|
|
2127
|
+
const ref = plan.kind === "ollama" ? plan.name : await abortable(plan.hub.verifyOllamaRef(plan.detail, plan.build, { signal: extra.signal }), extra.signal);
|
|
2128
|
+
if (!ref) return errorResult(`Hugging Face's registry does not serve this exact ${summary.model} file to Ollama, so nothing was downloaded. Pick another quant.`);
|
|
2129
|
+
let hadTag = null;
|
|
2130
|
+
if (plan.curated) {
|
|
2131
|
+
await requireReviewedLayers(plan.curated, ref, sources(extra.signal, from));
|
|
2132
|
+
hadTag = await hadTagBefore(plan.target, ref, extra.signal);
|
|
2133
|
+
}
|
|
2134
|
+
try {
|
|
2135
|
+
await plan.target.runtime.pull(ref, {
|
|
2136
|
+
runner: plan.curated ? curatedRunner(plan.curated.build) : void 0,
|
|
2137
|
+
signal: extra.signal,
|
|
2138
|
+
onProgress: pullProgress(extra, plan.target.redact)
|
|
2139
|
+
});
|
|
2140
|
+
} catch (error) {
|
|
2141
|
+
if (extra.signal.aborted) return errorResult("Pull cancelled. Nothing was installed; Ollama keeps the partial download, so pulling again resumes it.");
|
|
2142
|
+
throw error;
|
|
2143
|
+
}
|
|
2144
|
+
if (plan.curated) try {
|
|
2145
|
+
await requireInstalledReviewed(plan.target, plan.curated, ref, hadTag, extra.signal);
|
|
2146
|
+
} catch (error) {
|
|
2147
|
+
if (extra.signal.aborted) return errorResult(installedUncheckedMessage(ref));
|
|
2148
|
+
throw error;
|
|
2149
|
+
}
|
|
2150
|
+
return toResult({
|
|
2151
|
+
status: "pulled",
|
|
2152
|
+
downloaded: true,
|
|
2153
|
+
installedAs: clean(ref),
|
|
2154
|
+
...summary
|
|
2155
|
+
});
|
|
2156
|
+
}));
|
|
2157
|
+
server.registerTool("models_remove", {
|
|
2158
|
+
title: "Remove a local model",
|
|
2159
|
+
description: "Delete an installed model from the user's local runtime. Nothing is removed without the user's own approval: when the client supports elicitation the user is asked directly. Without elicitation nothing is removed: the result names the model and gives a `b4m models rm` command for the user to run in a terminal, where the CLI asks them. No argument of this tool approves a removal.",
|
|
2160
|
+
inputSchema: removeShape,
|
|
2161
|
+
annotations: {
|
|
2162
|
+
readOnlyHint: false,
|
|
2163
|
+
destructiveHint: true,
|
|
2164
|
+
openWorldHint: false
|
|
2165
|
+
}
|
|
2166
|
+
}, (args, extra) => run(async () => {
|
|
2167
|
+
const from = await scoped(args.server, true, extra.signal);
|
|
2168
|
+
const target = await abortable(from.resolveRuntime(), extra.signal);
|
|
2169
|
+
requireRemovable(target);
|
|
2170
|
+
const model = findInstalledModel(await abortable(target.runtime.list(), extra.signal), args.name);
|
|
2171
|
+
if (!model) return errorResult(`No model named ${clean(args.name)} on ${runtimeLabel(target)}. See models_list.`);
|
|
2172
|
+
const summary = {
|
|
2173
|
+
model: clean(model.name),
|
|
2174
|
+
sizeBytes: model.sizeBytes,
|
|
2175
|
+
size: formatBytes(model.sizeBytes),
|
|
2176
|
+
runtime: runtimeLabel(target)
|
|
2177
|
+
};
|
|
2178
|
+
if (!canElicit()) return toResult({
|
|
2179
|
+
status: "confirm-in-terminal",
|
|
2180
|
+
removed: false,
|
|
2181
|
+
...summary,
|
|
2182
|
+
command: terminalCommand(target, "rm", model.name),
|
|
2183
|
+
userApproval: "Nothing was removed. This MCP client cannot ask the user, so the removal has to be approved in a terminal: give the user the command, and the CLI asks them before removing."
|
|
2184
|
+
});
|
|
2185
|
+
const answer = await ask({
|
|
2186
|
+
mode: "form",
|
|
2187
|
+
message: `Remove ${summary.model} (${summary.size}) from ${summary.runtime}? Its files are deleted.`,
|
|
2188
|
+
requestedSchema: {
|
|
2189
|
+
type: "object",
|
|
2190
|
+
properties: { remove: {
|
|
2191
|
+
type: "boolean",
|
|
2192
|
+
title: `Remove ${summary.model}`,
|
|
2193
|
+
default: false
|
|
2194
|
+
} },
|
|
2195
|
+
required: ["remove"]
|
|
2196
|
+
}
|
|
2197
|
+
}, extra);
|
|
2198
|
+
if (answer.action !== "accept" || answer.content?.remove !== true) return toResult({
|
|
2199
|
+
status: "declined",
|
|
2200
|
+
removed: false,
|
|
2201
|
+
...summary,
|
|
2202
|
+
message: "The user declined. Nothing was removed."
|
|
2203
|
+
});
|
|
2204
|
+
await removeInstalled(target, model.name, extra.signal);
|
|
2205
|
+
const defaultModel = await deps.defaultModel();
|
|
2206
|
+
const current = defaultOn(target, defaultModel);
|
|
2207
|
+
const wasDefault = !!current && sameModelName(current, model.name);
|
|
2208
|
+
return toResult({
|
|
2209
|
+
status: "removed",
|
|
2210
|
+
removed: true,
|
|
2211
|
+
...summary,
|
|
2212
|
+
wasDefault
|
|
2213
|
+
});
|
|
2214
|
+
}));
|
|
2215
|
+
}
|
|
2216
|
+
//#endregion
|
|
1674
2217
|
//#region src/mcp/solverTools.ts
|
|
1675
2218
|
/** Both scopes the tools need; named in a 403 so callers know what to grant. */
|
|
1676
2219
|
const REQUIRED_SCOPES = [ApiKeyScope.OPTIHASHI_READ, ApiKeyScope.OPTIHASHI_COMPUTE];
|
|
@@ -2007,13 +2550,26 @@ function buildMcpServer(options, client = new B4mApiClient(options.baseURL, opti
|
|
|
2007
2550
|
}
|
|
2008
2551
|
/**
|
|
2009
2552
|
* {@link buildMcpServer} plus the tools only an authenticated, entitled caller gets, which the server
|
|
2010
|
-
* reports at startup. Stdio only: the HTTP transport trusts anything that
|
|
2011
|
-
* it uses the plain builder and never offers these.
|
|
2553
|
+
* reports at startup, and the local model tools. Stdio only: the HTTP transport trusts anything that
|
|
2554
|
+
* can reach its socket, so it uses the plain builder and never offers these.
|
|
2012
2555
|
*/
|
|
2013
|
-
async function buildStdioMcpServer(options) {
|
|
2556
|
+
async function buildStdioMcpServer(options, modelTools = localModelToolsDeps(options.configStore)) {
|
|
2014
2557
|
const client = new B4mApiClient(options.baseURL, options.configStore, options.apiKey);
|
|
2015
2558
|
const server = buildMcpServer(options, client);
|
|
2016
2559
|
await registerSolverTools(server, client);
|
|
2560
|
+
registerModelTools(server, modelTools);
|
|
2561
|
+
return server;
|
|
2562
|
+
}
|
|
2563
|
+
/**
|
|
2564
|
+
* `mcp serve --local`: only the local model tools, which need the model runtime and Hugging Face but
|
|
2565
|
+
* never a Bike4Mind backend, so it builds no API client. Stdio only, like {@link buildStdioMcpServer}.
|
|
2566
|
+
*/
|
|
2567
|
+
function buildLocalMcpServer(options, modelTools = localModelToolsDeps(options.configStore)) {
|
|
2568
|
+
const server = new McpServer({
|
|
2569
|
+
name: "bike4mind",
|
|
2570
|
+
version: options.version
|
|
2571
|
+
}, { capabilities: { tools: {} } });
|
|
2572
|
+
registerModelTools(server, modelTools);
|
|
2017
2573
|
return server;
|
|
2018
2574
|
}
|
|
2019
2575
|
//#endregion
|
|
@@ -2024,7 +2580,8 @@ async function buildStdioMcpServer(options) {
|
|
|
2024
2580
|
* Two transports: stdio (default, for Claude Desktop and other local clients)
|
|
2025
2581
|
* and stateless streamable HTTP (`--http`). Auth precedence is
|
|
2026
2582
|
* `--api-key` > `B4M_API_KEY` > the stored OAuth JWT; the endpoint is
|
|
2027
|
-
* `B4M_API_URL` > `--api-url` > the CLI's configured backend.
|
|
2583
|
+
* `B4M_API_URL` > `--api-url` > the CLI's configured backend. `--local` (stdio
|
|
2584
|
+
* only) serves just the local model tools and needs no endpoint at all.
|
|
2028
2585
|
*
|
|
2029
2586
|
* Transport contract for stdio: stdout carries the JSON-RPC frame stream and
|
|
2030
2587
|
* NOTHING else, so all diagnostics are forced to stderr before ANY other work
|
|
@@ -2061,8 +2618,29 @@ function resolveBaseURL(options, configStore) {
|
|
|
2061
2618
|
}
|
|
2062
2619
|
return configStore.getApiConfig().then((apiConfig) => requireApiUrl(apiConfig));
|
|
2063
2620
|
}
|
|
2064
|
-
async function
|
|
2065
|
-
|
|
2621
|
+
async function resolveBuildOptions(options, configStore) {
|
|
2622
|
+
return {
|
|
2623
|
+
baseURL: await resolveBaseURL(options, configStore),
|
|
2624
|
+
apiKey: options.apiKey ?? process.env.B4M_API_KEY,
|
|
2625
|
+
configStore,
|
|
2626
|
+
version: options.version
|
|
2627
|
+
};
|
|
2628
|
+
}
|
|
2629
|
+
/**
|
|
2630
|
+
* The server stdio mode runs: the local model tools alone under `--local`, which never resolves an
|
|
2631
|
+
* endpoint, otherwise the full set against the resolved backend (failing when none is configured).
|
|
2632
|
+
*/
|
|
2633
|
+
async function buildServeStdioServer(options, configStore) {
|
|
2634
|
+
if (options.local) {
|
|
2635
|
+
process.stderr.write(`Serving local model tools only (${MODEL_TOOL_NAMES.join(", ")}); drop --local to serve the Bike4Mind tools.\n`);
|
|
2636
|
+
return buildLocalMcpServer({
|
|
2637
|
+
configStore,
|
|
2638
|
+
version: options.version
|
|
2639
|
+
});
|
|
2640
|
+
}
|
|
2641
|
+
return buildStdioMcpServer(await resolveBuildOptions(options, configStore));
|
|
2642
|
+
}
|
|
2643
|
+
async function serveStdio(server, writeFrame) {
|
|
2066
2644
|
const stdout = new Writable({ write(chunk, _encoding, callback) {
|
|
2067
2645
|
if (writeFrame(chunk)) {
|
|
2068
2646
|
callback();
|
|
@@ -2170,16 +2748,11 @@ async function serveHttp(buildOptions, port, resolved) {
|
|
|
2170
2748
|
});
|
|
2171
2749
|
}
|
|
2172
2750
|
async function handleMcpServeCommand(options) {
|
|
2751
|
+
if (options.local && options.http) throw new Error("--local serves over stdio only; drop --http.");
|
|
2173
2752
|
const writeFrame = options.http ? void 0 : captureStdout();
|
|
2174
2753
|
const configStore = new ConfigStore();
|
|
2175
|
-
|
|
2176
|
-
|
|
2177
|
-
apiKey: options.apiKey ?? process.env.B4M_API_KEY,
|
|
2178
|
-
configStore,
|
|
2179
|
-
version: options.version
|
|
2180
|
-
};
|
|
2181
|
-
if (writeFrame) await serveStdio(buildOptions, writeFrame);
|
|
2182
|
-
else await serveHttp(buildOptions, options.port ?? 7e3, resolveHttpToken(options.token, process.env.B4M_MCP_TOKEN));
|
|
2754
|
+
if (writeFrame) await serveStdio(await buildServeStdioServer(options, configStore), writeFrame);
|
|
2755
|
+
else await serveHttp(await resolveBuildOptions(options, configStore), options.port ?? 7e3, resolveHttpToken(options.token, process.env.B4M_MCP_TOKEN));
|
|
2183
2756
|
}
|
|
2184
2757
|
//#endregion
|
|
2185
2758
|
export { handleMcpServeCommand };
|