@bike4mind/cli 4.0.0 → 4.6.0

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