@bike4mind/cli 3.4.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 (56) hide show
  1. package/README.md +223 -39
  2. package/bin/bike4mind-cli.mjs +301 -38
  3. package/bin/envFlags.d.mts +17 -0
  4. package/bin/envFlags.mjs +89 -0
  5. package/bin/hearth-hook.mjs +53 -7
  6. package/dist/{AgentHistoryStore-ClO2zOn6.mjs → AgentHistoryStore--J3sgO_-.mjs} +9011 -6699
  7. package/dist/ApiClient-CdO4Gamg.mjs +152 -0
  8. package/dist/BubblewrapRuntime-3jAbC60G.mjs +157 -0
  9. package/dist/ConfigStore-CausUCzY.mjs +2 -0
  10. package/dist/ConfigStore-Dusy6glb.mjs +3364 -0
  11. package/dist/{ConfigStore-CbVFLXMH.mjs → Logger-C1Wj6xla.mjs} +32880 -20779
  12. package/dist/{ProxyManager-B0-RuR2w.mjs → ProxyManager-TxEKlgdO.mjs} +88 -3
  13. package/dist/RemoteSkillSource-qTvRkaNA.mjs +455 -0
  14. package/dist/{SandboxOrchestrator-BcUv9fQ3.mjs → SandboxOrchestrator-CQwYq_uy.mjs} +26 -7
  15. package/dist/SandboxRuntimeAdapter-BsT2iLky.mjs +190 -0
  16. package/dist/SandboxRuntimeAdapter-Zg_0th7V.mjs +2 -0
  17. package/dist/SeatbeltRuntime-C2DEkrjy.mjs +194 -0
  18. package/dist/{WorkItemsClient-SeNbzvEw.mjs → WorkItemsClient-CxNZaOmc.mjs} +1 -1
  19. package/dist/agents/defaults/review.md +8 -1
  20. package/dist/agents/defaults/test.md +8 -1
  21. package/dist/buildToolSearch-DOb7mx6F.mjs +417 -0
  22. package/dist/commands/acpCommand.mjs +33 -27
  23. package/dist/commands/apiCommand.mjs +3 -5
  24. package/dist/commands/doctorCommand.mjs +2 -2
  25. package/dist/commands/envCommand.mjs +1 -1
  26. package/dist/commands/headlessCommand.mjs +118 -36
  27. package/dist/commands/hostCommand.mjs +2344 -0
  28. package/dist/commands/mcpCommand.mjs +46 -30
  29. package/dist/commands/mirrorCommand.mjs +279 -0
  30. package/dist/commands/modelsCommand.mjs +1117 -0
  31. package/dist/commands/pluginCommand.mjs +9 -9
  32. package/dist/commands/skillsCommand.mjs +404 -0
  33. package/dist/commands/updateCommand.mjs +2 -2
  34. package/dist/curated-build.json +1 -0
  35. package/dist/dist-CbViwiS9.mjs +4739 -0
  36. package/dist/dist-Citbv0y0.mjs +7864 -0
  37. package/dist/fit-CVWDiavv.mjs +200 -0
  38. package/dist/index.mjs +1001 -442
  39. package/dist/modelHub-BSB6qRFP.mjs +1963 -0
  40. package/dist/modelServers-BaegigV-.mjs +2465 -0
  41. package/dist/{package-MoDZ9cGj.mjs → package-C9pfAdGF.mjs} +1 -1
  42. package/dist/{serve-zi-B2iUT.mjs → serve-8wyGb8of.mjs} +1243 -44
  43. package/dist/store-BYeE0shc.mjs +2 -0
  44. package/dist/{store-BxmPEI3v.mjs → store-BbvSi3KK.mjs} +26 -2
  45. package/dist/types-BFIvwByC.mjs +2 -0
  46. package/dist/{types-F61_hxmG.mjs → types-CxrzVXel.mjs} +9 -5
  47. package/dist/{updateChecker-CCLVVdH0.mjs → updateChecker-BAKb8KWP.mjs} +7 -29
  48. package/package.json +17 -13
  49. package/dist/BubblewrapRuntime-5bLPTwEC.mjs +0 -72
  50. package/dist/SandboxRuntimeAdapter-BgLUVTJL.mjs +0 -57
  51. package/dist/SandboxRuntimeAdapter-Bt1wPpld.mjs +0 -2
  52. package/dist/SeatbeltRuntime-C_Y8q8Mr.mjs +0 -124
  53. package/dist/buildAgent-BeaVbpzH.mjs +0 -1992
  54. package/dist/dist-DlBq3wHu.mjs +0 -739
  55. package/dist/store-BkMur6uk.mjs +0 -2
  56. package/dist/types-I45lMh7Q.mjs +0 -2
@@ -1,9 +1,17 @@
1
1
  #!/usr/bin/env node
2
- import { B as CreateArtifactRequestSchema, D as AGENT_QUEST_MANIFEST, E as AGENT_QUEST_ID, Et as joinReplySlots, F as BriefcasePromptIdSchema, Ft as supportedVoiceGenerationVendor, G as GENERATED_IMAGE_EXTENSION_RE, K as ImageModels, Lt as ttsBase64ResponseSchema, M as ArtifactTypeSchema, N as BRIEFCASE_CATALOG_QUERIES, O as AGENT_QUEST_MCP_URI, Ot as questReplyText, Rt as ttsRequestSchema, V as DEFAULT_TTS_PROVIDER, _t as generatedAudioResponseSchema, b as logger, kt as replacePromptVariables, lt as VisibilitySchema, p as requireApiUrl, pt as buildPromptContext, q as ImagePromptResolutionSchema, t as ConfigStore, tt as PROMPT_TEXT_MAX, v as NotAuthenticatedError, y as parseApiUrl, zt as ttsResponseTooLargeSchema } from "./ConfigStore-CbVFLXMH.mjs";
3
- import { a as ApiClient, i as parseRetryAfterSeconds, o as isProviderKeyFailure, r as createClient, t as B4mApiError } from "./dist-DlBq3wHu.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";
4
11
  import { z as z$1 } from "zod";
5
12
  import { isAxiosError } from "axios";
6
- import { createHash, randomUUID } from "node:crypto";
13
+ import { createHash, randomBytes, randomUUID, timingSafeEqual } from "node:crypto";
14
+ import { open, realpath } from "node:fs/promises";
7
15
  import { Writable } from "node:stream";
8
16
  import { createServer } from "node:http";
9
17
  import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
@@ -13,6 +21,82 @@ import { ErrorCode, GetPromptRequestSchema, ListPromptsRequestSchema, McpError }
13
21
  //#region src/mcp/b4mApiClient.ts
14
22
  const NOTEBOOK_ID_PATTERN = /^[a-f0-9]{24}$/i;
15
23
  const STOP_REPLY_TIMEOUT_MS = 1e4;
24
+ /** Only the route is known here: the solver roster and limits are fetched at runtime. */
25
+ const SOLVER_ROUTE = "/api/premium-optihashi/quantum/solve";
26
+ /**
27
+ * The catalog and the key-scope lookup run before the stdio handshake completes, so they must not
28
+ * inherit the client's 10-minute default: a hung backend would otherwise stall `initialize` for every
29
+ * user, entitled or not.
30
+ */
31
+ const SOLVER_CATALOG_TIMEOUT_MS = 5e3;
32
+ /** Bob's routes. Bob is deployed apart from the host, so a server may not serve them. */
33
+ const BOB_ROUTE = "/api/premium-bob";
34
+ /**
35
+ * One Bob run as `GET bob-run?id=&view=agent` answers it. Every field the tools read is required or
36
+ * nullable here, so a server that ignores `view=agent` (and answers the app's own shape) fails the
37
+ * parse rather than reading as a run with no report.
38
+ */
39
+ const bobAgentRunSchema = z$1.looseObject({
40
+ runId: z$1.string(),
41
+ url: z$1.string(),
42
+ status: z$1.enum([
43
+ "reading",
44
+ "ok",
45
+ "failed"
46
+ ]),
47
+ progress: z$1.object({
48
+ done: z$1.number(),
49
+ total: z$1.number()
50
+ }).nullish(),
51
+ createdAt: z$1.string(),
52
+ settledAt: z$1.string().nullish(),
53
+ error: z$1.string().nullish(),
54
+ scanOnly: z$1.string().nullish(),
55
+ reportMarkdown: z$1.string().nullish(),
56
+ appPath: z$1.string(),
57
+ publishedPath: z$1.string().nullish(),
58
+ visibility: z$1.string().nullish()
59
+ });
60
+ const bobAgentComparisonSchema = z$1.looseObject({
61
+ comparisonId: z$1.string(),
62
+ status: z$1.enum([
63
+ "reading",
64
+ "ok",
65
+ "failed"
66
+ ]),
67
+ you: bobAgentRunSchema.nullable(),
68
+ them: bobAgentRunSchema.nullable(),
69
+ summaryMarkdown: z$1.string().nullish(),
70
+ appPath: z$1.string()
71
+ });
72
+ /**
73
+ * One row of `GET bob-run?list=recent`: a single-site run or a two-site comparison (`you` and
74
+ * `them` are the two URLs). A server that predates comparison rows sends runs with no `kind`.
75
+ */
76
+ const bobRecentRowSchema = z$1.union([z$1.looseObject({
77
+ kind: z$1.literal("run").optional(),
78
+ runId: z$1.string(),
79
+ url: z$1.string(),
80
+ createdAt: z$1.string().nullish()
81
+ }), z$1.looseObject({
82
+ kind: z$1.literal("comparison"),
83
+ comparisonId: z$1.string(),
84
+ you: z$1.string(),
85
+ them: z$1.string(),
86
+ createdAt: z$1.string().nullish()
87
+ })]);
88
+ const bobRecentListSchema = z$1.object({ runs: z$1.array(z$1.unknown()) });
89
+ /** A start's 200 refusal: the daily cap or a credits refusal, in Bob's words. */
90
+ const bobRefusalSchema = z$1.object({
91
+ ok: z$1.literal(false),
92
+ error: z$1.string()
93
+ });
94
+ const bobOrganizationField = (organizationId) => organizationId === void 0 ? {} : { organizationId };
95
+ const keyScopeListSchema = z$1.array(z$1.object({
96
+ keyPrefix: z$1.string().optional(),
97
+ scopes: z$1.array(z$1.string()).optional(),
98
+ status: z$1.string().optional()
99
+ }));
16
100
  /**
17
101
  * An empty or dot-segment id collapses `/api/sessions/{id}` to `/api/sessions`, whose DELETE wipes every
18
102
  * notebook the caller owns, so write paths refuse anything that is not an ObjectId before any request.
@@ -36,6 +120,7 @@ function writableNotebookId(notebookId) {
36
120
  var B4mApiClient = class {
37
121
  constructor(baseURL, configStore, apiKey) {
38
122
  this.baseURL = baseURL;
123
+ this.apiKey = apiKey;
39
124
  this.client = new ApiClient(baseURL, configStore, apiKey);
40
125
  this.sdk = createClient({
41
126
  baseUrl: baseURL,
@@ -139,6 +224,31 @@ var B4mApiClient = class {
139
224
  async getFile(fileId) {
140
225
  return this.client.get(`/api/files/${encodeURIComponent(fileId)}`);
141
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
+ }
142
252
  /** Generate a sound effect. The SDK requests base64 and rebuilds an old server's raw-bytes answer. */
143
253
  async generateSoundEffect(args) {
144
254
  const body = {
@@ -265,12 +375,16 @@ var B4mApiClient = class {
265
375
  /**
266
376
  * PUT one draft file to the URL upload-url minted. Plain fetch, never the app
267
377
  * client: that client injects auth headers, which break an S3 presigned
268
- * 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.
269
380
  */
270
- async uploadPublishDraftFile(uploadUrl, body, mimeType) {
271
- 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), {
272
383
  method: "PUT",
273
- headers: { "Content-Type": mimeType },
384
+ headers: {
385
+ ...upload.headers,
386
+ "Content-Type": mimeType
387
+ },
274
388
  body
275
389
  });
276
390
  if (!res.ok) throw new Error(`publish upload failed (${res.status})`);
@@ -293,7 +407,108 @@ var B4mApiClient = class {
293
407
  async getBriefcasePrompt(promptId) {
294
408
  return (await this.client.get(`/api/briefcase/prompts/${encodeURIComponent(promptId)}`)).prompt;
295
409
  }
410
+ /**
411
+ * Scopes held by the API key this client authenticates with, read from the caller's own key list by
412
+ * matching the key's stored prefix. Undefined for a login (JWT) caller, who has no scopes to check;
413
+ * an empty list when the key is not found or cannot be told apart from another, so a caller that cannot be
414
+ * identified is never treated as scoped. Stored prefixes differ in length (older keys keep a shorter one),
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.
418
+ */
419
+ async getOwnKeyScopes() {
420
+ const apiKey = this.apiKey;
421
+ if (!apiKey) return void 0;
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));
430
+ const longest = matches.reduce((length, key) => Math.max(length, key.keyPrefix?.length ?? 0), 0);
431
+ const best = matches.filter((k) => k.keyPrefix?.length === longest);
432
+ return best.length === 1 ? best[0].scopes ?? [] : [];
433
+ }
434
+ /** GET on the entitlement-gated solver route: the runnable rosters and limits for this caller. */
435
+ async getSolverCatalog() {
436
+ return this.client.get(SOLVER_ROUTE, { timeout: SOLVER_CATALOG_TIMEOUT_MS });
437
+ }
438
+ /** POST on the same route: run a bounded solver race. The body is validated server-side. */
439
+ async runSolverRace(body) {
440
+ return this.client.post(SOLVER_ROUTE, body);
441
+ }
442
+ /** POST bob-run: start one site read under a caller-minted run id. Throws Bob's words on a refusal. */
443
+ async startBobRun(args) {
444
+ const body = {
445
+ url: args.url,
446
+ runId: args.runId,
447
+ ...bobOrganizationField(args.organizationId)
448
+ };
449
+ throwBobRefusal(await this.client.post(`${BOB_ROUTE}/bob-run`, body));
450
+ }
451
+ async getBobRun(runId) {
452
+ const result = await this.client.get(`${BOB_ROUTE}/bob-run`, { params: {
453
+ id: runId,
454
+ view: "agent"
455
+ } });
456
+ return this.parseBobView(z$1.object({ run: bobAgentRunSchema }), result, "run").run;
457
+ }
458
+ /** POST bob-compare: start a read of each site, linked as one comparison. Throws Bob's words on a refusal. */
459
+ async startBobComparison(args) {
460
+ const { organizationId, ...ids } = args;
461
+ const body = {
462
+ ...ids,
463
+ ...bobOrganizationField(organizationId)
464
+ };
465
+ throwBobRefusal(await this.client.post(`${BOB_ROUTE}/bob-compare`, body));
466
+ }
467
+ async getBobComparison(comparisonId) {
468
+ const result = await this.client.get(`${BOB_ROUTE}/bob-compare`, { params: {
469
+ id: comparisonId,
470
+ view: "agent"
471
+ } });
472
+ return this.parseBobView(z$1.object({ comparison: bobAgentComparisonSchema }), result, "comparison").comparison;
473
+ }
474
+ /** POST bob-recheck: re-run one check of a run against its site. Answers with the new reading. */
475
+ async recheckBob(args) {
476
+ const result = await this.client.post(`${BOB_ROUTE}/bob-recheck`, args);
477
+ throwBobRefusal(result);
478
+ return result.recheck;
479
+ }
480
+ /**
481
+ * GET bob-run?list=recent: the caller's finished runs and comparisons, newest first. The server caps
482
+ * `limit`. A row of a kind this CLI does not know is dropped, so a newer server cannot break the list.
483
+ */
484
+ async listBobReports(limit) {
485
+ const result = await this.client.get(`${BOB_ROUTE}/bob-run`, { params: {
486
+ list: "recent",
487
+ ...limit !== void 0 ? { limit } : {}
488
+ } });
489
+ return bobRecentListSchema.parse(result).runs.flatMap((row) => {
490
+ const parsed = bobRecentRowSchema.safeParse(row);
491
+ return parsed.success ? [parsed.data] : [];
492
+ });
493
+ }
494
+ /** GET bob-run?quota: runs left under the daily cap, for the account a start would bill. */
495
+ async getBobQuota(organizationId) {
496
+ return (await this.client.get(`${BOB_ROUTE}/bob-run`, { params: {
497
+ quota: "",
498
+ ...organizationId === void 0 ? {} : { organizationId: organizationId ?? "" }
499
+ } })).quota ?? {};
500
+ }
501
+ parseBobView(schema, body, what) {
502
+ const parsed = schema.safeParse(body);
503
+ if (!parsed.success) throw new Error(`the Bike4Mind server at ${this.baseURL} answered the Bob ${what} without its agent view; it likely predates these tools`);
504
+ return parsed.data;
505
+ }
296
506
  };
507
+ /** A 2xx `{ ok: false, error }` from Bob is a refusal (the daily cap, credits), not a transport error. */
508
+ function throwBobRefusal(body) {
509
+ const refusal = bobRefusalSchema.safeParse(body);
510
+ if (refusal.success) throw new Error(refusal.data.error);
511
+ }
297
512
  /**
298
513
  * Turn an API failure into an actionable, transport-agnostic message. `scope` is
299
514
  * the recommended API-key scope for the failing tool. A 403 can come from a
@@ -335,6 +550,20 @@ function mapApiError(error, baseURL, scope) {
335
550
  return error instanceof Error ? error.message : String(error);
336
551
  }
337
552
  /**
553
+ * {@link mapApiError} for Bob's routes, which do enforce their scopes. A scope 403 (Bob's own
554
+ * `missing_scope`, or the host gate's `required_scopes`) names the scope to grant; a 429 or 503 that
555
+ * carries `retryAfterMs` says how long to wait; a 404 with no error body means the server has no Bob.
556
+ */
557
+ function mapBobApiError(error, baseURL, scope) {
558
+ const failure = httpFailure(error);
559
+ const message = extractServerMessage(failure?.data);
560
+ const body = failure?.data && typeof failure.data === "object" ? failure.data : {};
561
+ if (failure?.status === 403 && (body.code === "missing_scope" || Array.isArray(body.required_scopes))) return `${message ?? "API key forbidden"} (grant the key ${scope})`;
562
+ if ((failure?.status === 429 || failure?.status === 503) && typeof body.retryAfterMs === "number") return `${message ?? "Bob is busy"} (retry after ${Math.ceil(body.retryAfterMs / 1e3)}s)`;
563
+ if (failure?.status === 404 && !message) return `Bob is not available on the Bike4Mind server at ${baseURL}`;
564
+ return mapApiError(error, baseURL, scope);
565
+ }
566
+ /**
338
567
  * Status and body of an HTTP failure from either transport: a `B4mApiError` from the SDK calls or an
339
568
  * AxiosError from the axios ones (with no status when the request never got a response). Undefined for
340
569
  * anything else.
@@ -464,6 +693,12 @@ const TOOL_META = [
464
693
  description: "Fetch a file's metadata and a signed download URL.",
465
694
  scope: "files:read"
466
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
+ },
467
702
  {
468
703
  name: "generate_sound_effect",
469
704
  title: "Generate sound effect",
@@ -493,6 +728,48 @@ const TOOL_META = [
493
728
  title: "Publish artifact",
494
729
  description: "Publish an artifact you own to a shareable /p/... link and return its absolute URL. Republishing an artifact updates its existing page and keeps that page's visibility unless you pass one; a first publish defaults to public.",
495
730
  scope: "files:write"
731
+ },
732
+ {
733
+ name: "bob_read_site",
734
+ title: "Read a site with Bob",
735
+ description: "Have Bob read a website: a panel of synthetic personas reads it and reports where visitors get lost. Spends the key owner's credits and publishes the report as them, as a run started in the app does. Waits for the report, reporting progress, and returns it as Markdown with links to the in-app and published reports; fails with Bob's reason when the read fails. If Bob is still reading when waitSeconds runs out, returns the runId to pass to get_bob_report later.",
736
+ scope: "bob:run"
737
+ },
738
+ {
739
+ name: "bob_compare_sites",
740
+ title: "Compare two sites with Bob",
741
+ description: "Have Bob read your site and another one side by side. Spends the key owner's credits for both reads and publishes each report as them. Waits for both, reporting progress, and returns the comparison summary as Markdown with each side's status and links, plus each side's full report when includeReports is true. If Bob is still reading when waitSeconds runs out, returns the comparisonId to pass to get_bob_comparison later.",
742
+ scope: "bob:run"
743
+ },
744
+ {
745
+ name: "bob_recheck",
746
+ title: "Re-check a Bob finding",
747
+ description: "Re-scan one check from a Bob report against the live site, e.g. after a fix, and return the new reading. Costs no credits and adds the reading to the existing report beside the original; no new report is published. checkId is the id the report shows in backticks beside the check. Re-checks are rate-limited, and a refusal says how long to wait.",
748
+ scope: "bob:run"
749
+ },
750
+ {
751
+ name: "get_bob_report",
752
+ title: "Get a Bob report",
753
+ description: "Fetch one Bob run by runId: its status (reading, ok or failed), its progress while reading, and once it is ok the report as Markdown with links to the in-app and published reports.",
754
+ scope: "bob:read"
755
+ },
756
+ {
757
+ name: "get_bob_comparison",
758
+ title: "Get a Bob comparison",
759
+ description: "Fetch one Bob comparison by comparisonId: its status, the summary as Markdown once both sides are read, and each side's status and links. Pass a side's runId to get_bob_report for its full report.",
760
+ scope: "bob:read"
761
+ },
762
+ {
763
+ name: "list_bob_reports",
764
+ title: "List Bob reports",
765
+ description: "List the key owner's recent finished Bob reports, newest first: single-site runs (kind 'run') and two-site comparisons (kind 'comparison'), each with its in-app link. Read a run with get_bob_report and its runId, and a comparison with get_bob_comparison and its comparisonId.",
766
+ scope: "bob:read"
767
+ },
768
+ {
769
+ name: "bob_runs_left",
770
+ title: "Bob runs left",
771
+ description: "How many Bob runs the key owner can start now under the daily limit, when the next one frees up, and whether the account's credits cover a full read. A comparison uses two runs.",
772
+ scope: "bob:read"
496
773
  }
497
774
  ];
498
775
  TOOL_META.map((t) => t.name);
@@ -550,8 +827,15 @@ const listFilesShape = {
550
827
  page: z$1.number().int().min(1).default(1).describe("1-based page number; request the next page when hasMore is true")
551
828
  };
552
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
+ };
553
837
  const generateSoundEffectShape = {
554
- 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"),
555
839
  provider: z$1.enum(["elevenlabs"]).default("elevenlabs").describe("Sound-generation provider"),
556
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"),
557
841
  promptInfluence: z$1.number().min(0).max(1).optional().describe("How strictly to follow the prompt (0 = loose, 1 = strict)"),
@@ -586,6 +870,32 @@ const textToSpeechShape = {
586
870
  provider: ttsRequestSchema.shape.provider.describe(`Speech provider; defaults to ${DEFAULT_TTS_PROVIDER}`),
587
871
  preview: ttsRequestSchema.shape.preview.describe("Skip saving a copy to the file browser")
588
872
  };
873
+ const BOB_ID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
874
+ const BOB_WAIT_DEFAULT_SECONDS = 600;
875
+ const BOB_WAIT_MAX_SECONDS = 900;
876
+ const bobId = (description) => z$1.string().regex(BOB_ID_PATTERN, "must be a UUID").describe(description);
877
+ const bobOrganizationId = z$1.string().min(1).nullable().optional().describe("Organization whose credits pay for the run: an organization id, or null for the key owner's personal account; omit for their home organization");
878
+ const bobWaitSeconds = z$1.number().int().min(0).max(BOB_WAIT_MAX_SECONDS).default(BOB_WAIT_DEFAULT_SECONDS).describe(`How long to wait for the result, in seconds (0-${BOB_WAIT_MAX_SECONDS}, default ${BOB_WAIT_DEFAULT_SECONDS}); a read takes about 1 to 5 minutes and Bob keeps reading after the wait ends`);
879
+ const bobReadSiteShape = {
880
+ url: z$1.string().min(1).describe("The site to read, e.g. acme.io or acme.io/pricing"),
881
+ organizationId: bobOrganizationId,
882
+ waitSeconds: bobWaitSeconds
883
+ };
884
+ const bobCompareSitesShape = {
885
+ yourUrl: z$1.string().min(1).describe("Your site, e.g. acme.io"),
886
+ theirUrl: z$1.string().min(1).describe("The site to compare yours with"),
887
+ organizationId: bobOrganizationId,
888
+ waitSeconds: bobWaitSeconds,
889
+ includeReports: z$1.boolean().default(false).describe("Also return each side's full report as Markdown")
890
+ };
891
+ const bobRecheckShape = {
892
+ runId: bobId("The run the check belongs to"),
893
+ checkId: z$1.string().min(1).describe("The check id, as the report shows it in backticks beside the check")
894
+ };
895
+ const getBobReportShape = { runId: bobId("The run id") };
896
+ const getBobComparisonShape = { comparisonId: bobId("The comparison id") };
897
+ const listBobReportsShape = { limit: z$1.number().int().min(1).max(100).optional().describe("Maximum reports to return; the server caps the list") };
898
+ const bobRunsLeftShape = { organizationId: bobOrganizationId.describe("Account whose credits to check: an organization id, or null for the key owner's personal account; omit for their home organization") };
589
899
  function notebookSummary(n) {
590
900
  return {
591
901
  id: n.id,
@@ -725,6 +1035,66 @@ async function listFiles(client, args) {
725
1035
  async function getFile(client, args) {
726
1036
  return client.getFile(args.fileId);
727
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
+ }
728
1098
  async function generateSoundEffect(client, args) {
729
1099
  return generatedAudioResult(await client.generateSoundEffect(args), { provider: args.provider });
730
1100
  }
@@ -746,30 +1116,38 @@ const isPermanentApiError = (err) => {
746
1116
  const status = apiErrorStatus(err);
747
1117
  return status === 401 || status === 403 || status === 404;
748
1118
  };
749
- /** Poll a queued quest until `isFinished`, the timeout, a permanent poll failure, or an abort. */
750
- async function pollQuest(client, { questId, ref, task, scope, isFinished }, { interval, timeoutMs, sleep = defaultSleep, signal, onProgress, baseURL = "" }) {
1119
+ /** Poll `read` until `isFinished`, the timeout, a permanent poll failure, or an abort. */
1120
+ async function pollUntil({ read, ref, task, isFinished, describeError }, { interval, timeoutMs, sleep = defaultSleep, signal, onProgress }) {
751
1121
  const started = Date.now();
752
1122
  let failures = 0;
753
1123
  let retryAfterMs = 0;
1124
+ let latest;
754
1125
  for (;;) {
755
1126
  signal?.throwIfAborted();
756
- let quest;
1127
+ let value;
757
1128
  try {
758
- quest = await client.getQuest(questId);
1129
+ value = await read();
1130
+ latest = value;
759
1131
  failures = 0;
760
- if (isFinished(quest)) return quest;
1132
+ if (isFinished(value)) return {
1133
+ finished: true,
1134
+ value
1135
+ };
761
1136
  } catch (err) {
762
1137
  if (isRateLimited(err)) retryAfterMs = (apiErrorRetryAfterSeconds(err) ?? 0) * 1e3;
763
1138
  else {
764
1139
  failures += 1;
765
- if (isPermanentApiError(err) || failures >= MAX_CONSECUTIVE_POLL_FAILURES) throw new Error(`${mapApiError(err, baseURL, scope)} (${ref}; the ${task} may still complete)`);
1140
+ if (isPermanentApiError(err) || failures >= MAX_CONSECUTIVE_POLL_FAILURES) throw new Error(`${describeError(err)} (${ref}; the ${task} may still complete)`);
766
1141
  }
767
1142
  }
768
1143
  const elapsed = Date.now() - started;
769
- if (elapsed >= timeoutMs) throw new Error(`${task} did not finish within ${Math.round(timeoutMs / 1e3)}s (${ref})`);
1144
+ if (elapsed >= timeoutMs) return {
1145
+ finished: false,
1146
+ latest
1147
+ };
770
1148
  signal?.throwIfAborted();
771
1149
  try {
772
- await onProgress?.(elapsed, quest);
1150
+ await onProgress?.(elapsed, value);
773
1151
  } catch (err) {
774
1152
  logger.warn(`mcp: progress notification failed (${ref}): ${err instanceof Error ? err.message : String(err)}`);
775
1153
  }
@@ -778,6 +1156,18 @@ async function pollQuest(client, { questId, ref, task, scope, isFinished }, { in
778
1156
  retryAfterMs = 0;
779
1157
  }
780
1158
  }
1159
+ /** Poll a queued quest until `isFinished`, the timeout, a permanent poll failure, or an abort. */
1160
+ async function pollQuest(client, { questId, ref, task, scope, isFinished }, { baseURL = "", ...timing }) {
1161
+ const outcome = await pollUntil({
1162
+ read: () => client.getQuest(questId),
1163
+ ref,
1164
+ task,
1165
+ isFinished,
1166
+ describeError: (err) => mapApiError(err, baseURL, scope)
1167
+ }, timing);
1168
+ if (!outcome.finished) throw new Error(`${task} did not finish within ${Math.round(timing.timeoutMs / 1e3)}s (${ref})`);
1169
+ return outcome.value;
1170
+ }
781
1171
  /**
782
1172
  * Queue an image render and poll its quest to completion. A failed render still
783
1173
  * resolves `status: 'done'`, so `type: 'error'` (reason in `reply`) is the failure signal.
@@ -877,13 +1267,14 @@ async function publishArtifact(client, args) {
877
1267
  if (!body) throw new Error(`artifact ${artifact.id} has no content to publish`);
878
1268
  const artifactType = ArtifactTypeSchema.safeParse(artifact.type);
879
1269
  if (!artifactType.success) throw new Error(`artifact ${artifact.id} has an unsupported type (${String(artifact.type)})`);
880
- if (typeof artifact.userId !== "string") throw new Error(`artifact ${artifact.id} has no owner to publish under`);
881
1270
  const storedTitle = typeof artifact.title === "string" ? artifact.title : "";
882
1271
  const title = (args.title ?? storedTitle).trim().slice(0, PUBLISH_TITLE_MAX) || PUBLISH_FALLBACK_TITLE;
883
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`);
884
1275
  const request = {
885
1276
  tier: existing?.tier ?? "user",
886
- scopeId: existing?.scopeId ?? artifact.userId,
1277
+ scopeId: ownerScope,
887
1278
  slug: existing?.slug ?? artifactSlug(title, artifact.id),
888
1279
  title,
889
1280
  visibility: args.visibility ?? existing?.visibility ?? PUBLISH_DEFAULT_VISIBILITY,
@@ -903,7 +1294,7 @@ async function publishArtifact(client, args) {
903
1294
  const draft = existing ? await client.requestPublishUpload(request) : await openPublishDraft(client, request);
904
1295
  const upload = draft.uploadUrls.find((u) => u.path === PUBLISH_INDEX_PATH);
905
1296
  if (!upload) throw new Error(`publish draft ${draft.draftId} returned no upload URL for ${PUBLISH_INDEX_PATH}`);
906
- await client.uploadPublishDraftFile(upload.url, body, PUBLISH_INDEX_MIME);
1297
+ await client.uploadPublishDraftFile(upload, body, PUBLISH_INDEX_MIME);
907
1298
  const published = await client.finalizePublish(draft.draftId);
908
1299
  return {
909
1300
  publicId: published.publicId,
@@ -1016,19 +1407,19 @@ async function textToSpeech(client, args) {
1016
1407
  });
1017
1408
  }
1018
1409
  /**
1019
- * Turn a quest poll's progress callback into MCP `notifications/progress`, or nothing when the
1020
- * client sent no progressToken. Progress also lets a client that resets its request timeout on
1021
- * progress wait out a slow quest.
1410
+ * Turn a poll's progress callback into MCP `notifications/progress`, or nothing when the client
1411
+ * sent no progressToken. Progress counts elapsed seconds, so it rises on every poll, and that lets a
1412
+ * client that resets its request timeout on progress wait out slow work.
1022
1413
  */
1023
1414
  function progressReporter({ _meta, sendNotification }, describe) {
1024
1415
  const progressToken = _meta?.progressToken;
1025
1416
  if (progressToken === void 0) return void 0;
1026
- return (elapsedMs, quest) => sendNotification({
1417
+ return (elapsedMs, latest) => sendNotification({
1027
1418
  method: "notifications/progress",
1028
1419
  params: {
1029
1420
  progressToken,
1030
1421
  progress: Math.floor(elapsedMs / 1e3),
1031
- message: describe(quest)
1422
+ message: describe(latest)
1032
1423
  }
1033
1424
  });
1034
1425
  }
@@ -1038,6 +1429,188 @@ function chatProgress(quest) {
1038
1429
  return characters > 0 ? `generating reply (${characters} characters so far)` : "generating reply";
1039
1430
  }
1040
1431
  /**
1432
+ * Bob's own done/total count goes in the progress message, not in `progress`: a count can stay flat
1433
+ * for a while, and MCP needs `progress` to rise on every notification (see {@link progressReporter}).
1434
+ */
1435
+ function bobProgressMessage(what, count) {
1436
+ return count && count.total > 0 ? `${what} (${count.done} of ${count.total})` : what;
1437
+ }
1438
+ function bobComparisonCount(comparison) {
1439
+ const counts = [comparison.you?.progress, comparison.them?.progress].filter((c) => !!c);
1440
+ if (counts.length === 0) return null;
1441
+ return counts.reduce((sum, c) => ({
1442
+ done: sum.done + c.done,
1443
+ total: sum.total + c.total
1444
+ }));
1445
+ }
1446
+ /** send_message's cadence (fast for the first 30s, then slower), bounded by the caller's wait. */
1447
+ function bobPollTiming({ intervalMs = CHAT_POLL_INTERVAL_MS, ...poll }, waitSeconds) {
1448
+ return {
1449
+ ...poll,
1450
+ timeoutMs: waitSeconds * 1e3,
1451
+ interval: (elapsedMs) => chatPollInterval(elapsedMs, intervalMs)
1452
+ };
1453
+ }
1454
+ /** Bob's views carry app paths; a link is the API base URL plus one. */
1455
+ const bobLink = (baseURL, path) => path ? `${baseURL.replace(/\/+$/, "")}${path}` : null;
1456
+ function bobRunSummary(run, baseURL) {
1457
+ return {
1458
+ runId: run.runId,
1459
+ url: run.url,
1460
+ status: run.status,
1461
+ progress: run.progress ?? null,
1462
+ createdAt: run.createdAt,
1463
+ settledAt: run.settledAt ?? null,
1464
+ error: run.error ?? null,
1465
+ scanOnly: run.scanOnly ?? null,
1466
+ appUrl: bobLink(baseURL, run.appPath),
1467
+ publishedUrl: bobLink(baseURL, run.publishedPath),
1468
+ visibility: run.visibility ?? null
1469
+ };
1470
+ }
1471
+ function bobComparisonSummary(comparison, baseURL) {
1472
+ return {
1473
+ comparisonId: comparison.comparisonId,
1474
+ status: comparison.status,
1475
+ you: comparison.you && bobRunSummary(comparison.you, baseURL),
1476
+ them: comparison.them && bobRunSummary(comparison.them, baseURL),
1477
+ appUrl: bobLink(baseURL, comparison.appPath)
1478
+ };
1479
+ }
1480
+ /**
1481
+ * The summary as JSON (and as structuredContent), then each Markdown document as a text block of its
1482
+ * own. The documents stay out of structuredContent so a long report is not sent twice, as the audio
1483
+ * tools keep their bytes out.
1484
+ */
1485
+ function bobResult(summary, documents) {
1486
+ const result = toResult(summary);
1487
+ for (const text of documents) if (text) result.content.push({
1488
+ type: "text",
1489
+ text
1490
+ });
1491
+ return result;
1492
+ }
1493
+ function bobComparisonResult(comparison, baseURL, includeReports) {
1494
+ const reports = includeReports ? [comparison.you, comparison.them].map((side) => side?.reportMarkdown && `Report for ${side.url}:\n\n${side.reportMarkdown}`) : [];
1495
+ return bobResult(bobComparisonSummary(comparison, baseURL), [comparison.summaryMarkdown, ...reports]);
1496
+ }
1497
+ const bobStillReading = (waitSeconds, readBack) => `Bob is still reading after ${waitSeconds}s and carries on without this call; use ${readBack} later.`;
1498
+ /**
1499
+ * Start a Bob read of one site and poll it until it settles or `waitSeconds` passes. A refusal or a
1500
+ * failed read throws, so the tool reports isError in Bob's words. A read still going at the deadline
1501
+ * is not an error: the result carries the runId to read it back with.
1502
+ */
1503
+ async function bobReadSite(client, args, poll = {}) {
1504
+ const runId = randomUUID();
1505
+ await client.startBobRun({
1506
+ url: args.url,
1507
+ runId,
1508
+ organizationId: args.organizationId
1509
+ });
1510
+ const ref = `run ${runId}`;
1511
+ const outcome = await pollUntil({
1512
+ read: () => client.getBobRun(runId),
1513
+ ref,
1514
+ task: "site read",
1515
+ isFinished: (run) => run.status !== "reading",
1516
+ describeError: (err) => mapBobApiError(err, client.baseURL, "bob:run")
1517
+ }, bobPollTiming(poll, args.waitSeconds));
1518
+ if (!outcome.finished) return toResult({
1519
+ ...outcome.latest ? bobRunSummary(outcome.latest, client.baseURL) : {
1520
+ runId,
1521
+ url: args.url,
1522
+ status: "reading"
1523
+ },
1524
+ note: bobStillReading(args.waitSeconds, "get_bob_report with this runId")
1525
+ });
1526
+ const run = outcome.value;
1527
+ if (run.status === "failed") throw new Error(`Bob could not read ${run.url}: ${run.error || "the read failed"} (${ref})`);
1528
+ return bobResult(bobRunSummary(run, client.baseURL), [run.reportMarkdown]);
1529
+ }
1530
+ /** {@link bobReadSite} for two sites started as one comparison; fails only when neither side could be read. */
1531
+ async function bobCompareSites(client, args, poll = {}) {
1532
+ const comparisonId = randomUUID();
1533
+ const you = {
1534
+ url: args.yourUrl,
1535
+ runId: randomUUID()
1536
+ };
1537
+ const them = {
1538
+ url: args.theirUrl,
1539
+ runId: randomUUID()
1540
+ };
1541
+ await client.startBobComparison({
1542
+ comparisonId,
1543
+ you,
1544
+ them,
1545
+ organizationId: args.organizationId
1546
+ });
1547
+ const ref = `comparison ${comparisonId}`;
1548
+ const outcome = await pollUntil({
1549
+ read: () => client.getBobComparison(comparisonId),
1550
+ ref,
1551
+ task: "comparison",
1552
+ isFinished: (comparison) => comparison.status !== "reading",
1553
+ describeError: (err) => mapBobApiError(err, client.baseURL, "bob:run")
1554
+ }, bobPollTiming(poll, args.waitSeconds));
1555
+ if (!outcome.finished) return toResult({
1556
+ ...outcome.latest ? bobComparisonSummary(outcome.latest, client.baseURL) : {
1557
+ comparisonId,
1558
+ status: "reading",
1559
+ you,
1560
+ them
1561
+ },
1562
+ note: bobStillReading(args.waitSeconds, "get_bob_comparison with this comparisonId")
1563
+ });
1564
+ const comparison = outcome.value;
1565
+ if (comparison.status === "failed") {
1566
+ const reasons = [comparison.you, comparison.them].map((side) => side ? `${side.url}: ${side.error || "the read failed"}` : "one side has no run").join("; ");
1567
+ throw new Error(`Bob could not read either site: ${reasons} (${ref})`);
1568
+ }
1569
+ return bobComparisonResult(comparison, client.baseURL, args.includeReports === true);
1570
+ }
1571
+ async function bobRecheck(client, args) {
1572
+ return toResult({
1573
+ runId: args.runId,
1574
+ recheck: await client.recheckBob(args)
1575
+ });
1576
+ }
1577
+ async function getBobReport(client, args) {
1578
+ const run = await client.getBobRun(args.runId);
1579
+ return bobResult(bobRunSummary(run, client.baseURL), [run.reportMarkdown]);
1580
+ }
1581
+ async function getBobComparison(client, args) {
1582
+ return bobComparisonResult(await client.getBobComparison(args.comparisonId), client.baseURL, false);
1583
+ }
1584
+ /** A recent-list row in compact form, with the in-app link its kind opens at. */
1585
+ function bobReportRow(row, baseURL) {
1586
+ if (row.kind === "comparison") {
1587
+ const { comparisonId, you, them } = row;
1588
+ const appUrl = bobLink(baseURL, `/bob?compare=${encodeURIComponent(comparisonId)}`);
1589
+ return {
1590
+ kind: "comparison",
1591
+ comparisonId,
1592
+ you,
1593
+ them,
1594
+ createdAt: row.createdAt ?? null,
1595
+ appUrl
1596
+ };
1597
+ }
1598
+ const appUrl = bobLink(baseURL, `/bob?run=${encodeURIComponent(row.runId)}`);
1599
+ return {
1600
+ kind: "run",
1601
+ runId: row.runId,
1602
+ url: row.url,
1603
+ createdAt: row.createdAt ?? null,
1604
+ appUrl
1605
+ };
1606
+ }
1607
+ async function listBobReports(client, args) {
1608
+ return toResult({ reports: (await client.listBobReports(args.limit)).map((row) => bobReportRow(row, client.baseURL)) });
1609
+ }
1610
+ async function bobRunsLeft(client, args) {
1611
+ return toResult(await client.getBobQuota(args.organizationId));
1612
+ }
1613
+ /**
1041
1614
  * Register the Bike4Mind MCP tools on `server`. Each handler is wrapped so an
1042
1615
  * API failure becomes a structured `isError` result carrying a friendly message
1043
1616
  * (see {@link mapApiError}) rather than throwing across the transport.
@@ -1126,6 +1699,11 @@ function registerTools(server, client) {
1126
1699
  description: meta("get_file").description,
1127
1700
  inputSchema: getFileShape
1128
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)));
1129
1707
  server.registerTool("generate_sound_effect", {
1130
1708
  title: meta("generate_sound_effect").title,
1131
1709
  description: meta("generate_sound_effect").description,
@@ -1167,6 +1745,550 @@ function registerTools(server, client) {
1167
1745
  description: meta("publish_artifact").description,
1168
1746
  inputSchema: publishArtifactShape
1169
1747
  }, (args) => run("files:write", () => publishArtifact(client, args)));
1748
+ const runBob = async (scope, fn) => {
1749
+ try {
1750
+ return await fn();
1751
+ } catch (err) {
1752
+ return errorResult(mapBobApiError(err, baseURL, scope));
1753
+ }
1754
+ };
1755
+ server.registerTool("bob_read_site", {
1756
+ title: meta("bob_read_site").title,
1757
+ description: meta("bob_read_site").description,
1758
+ inputSchema: bobReadSiteShape
1759
+ }, (args, extra) => runBob("bob:run", () => bobReadSite(client, args, {
1760
+ signal: extra.signal,
1761
+ onProgress: progressReporter(extra, (run) => bobProgressMessage(`reading ${args.url}`, run?.progress))
1762
+ })));
1763
+ server.registerTool("bob_compare_sites", {
1764
+ title: meta("bob_compare_sites").title,
1765
+ description: meta("bob_compare_sites").description,
1766
+ inputSchema: bobCompareSitesShape
1767
+ }, (args, extra) => runBob("bob:run", () => bobCompareSites(client, args, {
1768
+ signal: extra.signal,
1769
+ onProgress: progressReporter(extra, (comparison) => bobProgressMessage("reading both sites", comparison && bobComparisonCount(comparison)))
1770
+ })));
1771
+ server.registerTool("bob_recheck", {
1772
+ title: meta("bob_recheck").title,
1773
+ description: meta("bob_recheck").description,
1774
+ inputSchema: bobRecheckShape
1775
+ }, (args) => runBob("bob:run", () => bobRecheck(client, args)));
1776
+ server.registerTool("get_bob_report", {
1777
+ title: meta("get_bob_report").title,
1778
+ description: meta("get_bob_report").description,
1779
+ inputSchema: getBobReportShape
1780
+ }, (args) => runBob("bob:read", () => getBobReport(client, args)));
1781
+ server.registerTool("get_bob_comparison", {
1782
+ title: meta("get_bob_comparison").title,
1783
+ description: meta("get_bob_comparison").description,
1784
+ inputSchema: getBobComparisonShape
1785
+ }, (args) => runBob("bob:read", () => getBobComparison(client, args)));
1786
+ server.registerTool("list_bob_reports", {
1787
+ title: meta("list_bob_reports").title,
1788
+ description: meta("list_bob_reports").description,
1789
+ inputSchema: listBobReportsShape
1790
+ }, (args) => runBob("bob:read", () => listBobReports(client, args)));
1791
+ server.registerTool("bob_runs_left", {
1792
+ title: meta("bob_runs_left").title,
1793
+ description: meta("bob_runs_left").description,
1794
+ inputSchema: bobRunsLeftShape
1795
+ }, (args) => runBob("bob:read", () => bobRunsLeft(client, args)));
1796
+ }
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
2213
+ //#region src/mcp/solverTools.ts
2214
+ /** Both scopes the tools need; named in a 403 so callers know what to grant. */
2215
+ const REQUIRED_SCOPES = [ApiKeyScope.OPTIHASHI_READ, ApiKeyScope.OPTIHASHI_COMPUTE];
2216
+ const SOLVER_SCOPES = REQUIRED_SCOPES.join(" and ");
2217
+ const SOLVER_DISCOVERY_TIMEOUT_MS = 5e3;
2218
+ /**
2219
+ * The route's GET answer, trusted only as far as the tool schemas need. Everything beyond these
2220
+ * fields passes through to the agent untouched, so a roster or limit the server adds later needs
2221
+ * no CLI release.
2222
+ */
2223
+ const catalogSchema = z$1.looseObject({
2224
+ family: z$1.looseObject({
2225
+ familyIds: z$1.array(z$1.string()),
2226
+ solverIds: z$1.array(z$1.string())
2227
+ }),
2228
+ scheduling: z$1.looseObject({ solverIds: z$1.array(z$1.string()) }),
2229
+ defaultSolverIds: z$1.array(z$1.string()),
2230
+ limits: z$1.looseObject({
2231
+ maxSolversPerRequest: z$1.number().int().positive(),
2232
+ defaultTimeoutMs: z$1.number().int().positive(),
2233
+ maxTimeoutMs: z$1.number().int().positive()
2234
+ })
2235
+ });
2236
+ const oneOf = (ids) => ids.length > 0 ? [ids[0], ...ids.slice(1)] : void 0;
2237
+ function solveInputShape(catalog) {
2238
+ const solverIds = oneOf([.../* @__PURE__ */ new Set([...catalog.family.solverIds, ...catalog.scheduling.solverIds])]);
2239
+ const familyIds = oneOf(catalog.family.familyIds);
2240
+ const { limits } = catalog;
2241
+ return {
2242
+ familyId: (familyIds ? z$1.enum(familyIds) : z$1.string()).optional().describe("Problem family. Omit for a scheduling brief; the problem must then be a scheduling problem."),
2243
+ problem: z$1.record(z$1.string(), z$1.unknown()).describe("The problem instance. The server validates it and names what is wrong on a 400."),
2244
+ solverIds: z$1.array(solverIds ? z$1.enum(solverIds) : z$1.string()).min(1).max(limits.maxSolversPerRequest).optional().describe(`Solvers to race. Defaults to ${catalog.defaultSolverIds.join(", ")}.`),
2245
+ timeoutMs: z$1.number().int().min(100).max(limits.maxTimeoutMs).optional().describe(`Per-solver time budget in ms (default ${limits.defaultTimeoutMs}).`),
2246
+ includeTrace: z$1.boolean().optional().describe("Include a truncated convergence trace per solver.")
2247
+ };
2248
+ }
2249
+ /**
2250
+ * Register the solver tools an entitled caller may use, built from what the server reports at
2251
+ * startup. Stdio only: the HTTP transport has no per-request auth, so it never calls this.
2252
+ *
2253
+ * Offering nothing is the normal outcome for a caller without the feature, the scopes or the
2254
+ * entitlement (the route answers 403/404), so any failure here leaves the server's other tools
2255
+ * untouched instead of failing the session. Only the free classical race is exposed; no tool here
2256
+ * commissions paid compute.
2257
+ */
2258
+ async function registerSolverTools(server, client) {
2259
+ let catalog;
2260
+ let discoveryTimer;
2261
+ try {
2262
+ const [rawCatalog, scopes] = await Promise.race([Promise.all([client.getSolverCatalog(), client.getOwnKeyScopes()]), new Promise((_resolve, reject) => {
2263
+ discoveryTimer = setTimeout(() => reject(/* @__PURE__ */ new Error("solver discovery timed out")), SOLVER_DISCOVERY_TIMEOUT_MS);
2264
+ })]);
2265
+ if (scopes && !REQUIRED_SCOPES.every((scope) => scopes.includes(scope))) {
2266
+ logger.debug(`mcp: solver tools not offered: key lacks ${SOLVER_SCOPES}`);
2267
+ return;
2268
+ }
2269
+ catalog = catalogSchema.parse(rawCatalog);
2270
+ } catch (err) {
2271
+ logger.debug(`mcp: solver tools not offered: ${mapApiError(err, client.baseURL, SOLVER_SCOPES)}`);
2272
+ return;
2273
+ } finally {
2274
+ clearTimeout(discoveryTimer);
2275
+ }
2276
+ const run = async (fn) => {
2277
+ try {
2278
+ return toResult(await fn());
2279
+ } catch (err) {
2280
+ return errorResult(mapApiError(err, client.baseURL, SOLVER_SCOPES));
2281
+ }
2282
+ };
2283
+ server.registerTool("optihashi_solvers", {
2284
+ title: "List OptiHashi solvers",
2285
+ description: "List the problem families, solvers, default race and limits available to the caller. Call before optihashi_solve."
2286
+ }, () => run(async () => catalogSchema.parse(await client.getSolverCatalog())));
2287
+ server.registerTool("optihashi_solve", {
2288
+ title: "Solve with OptiHashi",
2289
+ description: "Race classical solvers on an optimization problem and return the ranked results and the winner. Bounded and synchronous; no credits are spent.",
2290
+ inputSchema: solveInputShape(catalog)
2291
+ }, (args) => run(() => client.runSolverRace(args)));
1170
2292
  }
1171
2293
  //#endregion
1172
2294
  //#region src/mcp/resources.ts
@@ -1408,8 +2530,7 @@ function registerPrompts(server, client, now = () => /* @__PURE__ */ new Date())
1408
2530
  * network - only tool/resource *calls* and prompt listing/gets hit the API - so a
1409
2531
  * server built with an unreachable endpoint still advertises its full capability set.
1410
2532
  */
1411
- function buildMcpServer(options) {
1412
- const client = new B4mApiClient(options.baseURL, options.configStore, options.apiKey);
2533
+ function buildMcpServer(options, client = new B4mApiClient(options.baseURL, options.configStore, options.apiKey)) {
1413
2534
  const server = new McpServer({
1414
2535
  name: "bike4mind",
1415
2536
  version: options.version
@@ -1423,6 +2544,30 @@ function buildMcpServer(options) {
1423
2544
  registerPrompts(server, client);
1424
2545
  return server;
1425
2546
  }
2547
+ /**
2548
+ * {@link buildMcpServer} plus the tools only an authenticated, entitled caller gets, which the server
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.
2551
+ */
2552
+ async function buildStdioMcpServer(options, modelTools = localModelToolsDeps(options.configStore)) {
2553
+ const client = new B4mApiClient(options.baseURL, options.configStore, options.apiKey);
2554
+ const server = buildMcpServer(options, client);
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);
2569
+ return server;
2570
+ }
1426
2571
  //#endregion
1427
2572
  //#region src/mcp/serve.ts
1428
2573
  /**
@@ -1431,16 +2576,16 @@ function buildMcpServer(options) {
1431
2576
  * Two transports: stdio (default, for Claude Desktop and other local clients)
1432
2577
  * and stateless streamable HTTP (`--http`). Auth precedence is
1433
2578
  * `--api-key` > `B4M_API_KEY` > the stored OAuth JWT; the endpoint is
1434
- * `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.
1435
2581
  *
1436
2582
  * Transport contract for stdio: stdout carries the JSON-RPC frame stream and
1437
2583
  * NOTHING else, so all diagnostics are forced to stderr before ANY other work
1438
2584
  * runs (mirrors the acp command's captureStdout - see src/commands/acpCommand.ts).
1439
2585
  *
1440
- * HTTP mode is deliberately loopback-only (binds 127.0.0.1) with no per-request
1441
- * auth of its own - it trusts anything that can reach the socket, so it must not
1442
- * be exposed on a routable interface. DNS-rebinding protection is on as defense
1443
- * in depth against a browser being tricked into posting to the local port.
2586
+ * HTTP mode binds loopback only (127.0.0.1) and requires `Authorization: Bearer
2587
+ * <token>` on every request. Token precedence is `--token` > `B4M_MCP_TOKEN` >
2588
+ * one generated at startup. DNS-rebinding protection (Host/Origin checks) stays on.
1444
2589
  */
1445
2590
  const HTTP_PATH = "/mcp";
1446
2591
  /**
@@ -1469,8 +2614,29 @@ function resolveBaseURL(options, configStore) {
1469
2614
  }
1470
2615
  return configStore.getApiConfig().then((apiConfig) => requireApiUrl(apiConfig));
1471
2616
  }
1472
- async function serveStdio(buildOptions, writeFrame) {
1473
- const server = buildMcpServer(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) {
1474
2640
  const stdout = new Writable({ write(chunk, _encoding, callback) {
1475
2641
  if (writeFrame(chunk)) {
1476
2642
  callback();
@@ -1485,6 +2651,30 @@ async function serveStdio(buildOptions, writeFrame) {
1485
2651
  process.stdin.once("close", resolve);
1486
2652
  });
1487
2653
  }
2654
+ function resolveHttpToken(flag, env) {
2655
+ if (flag) return {
2656
+ token: flag,
2657
+ source: "flag"
2658
+ };
2659
+ if (env) return {
2660
+ token: env,
2661
+ source: "env"
2662
+ };
2663
+ return {
2664
+ token: randomBytes(32).toString("base64url"),
2665
+ source: "generated"
2666
+ };
2667
+ }
2668
+ function isAuthorized(header, token) {
2669
+ const match = /^Bearer (.+)$/i.exec(header ?? "");
2670
+ if (!match) return false;
2671
+ const given = Buffer.from(match[1]);
2672
+ const expected = Buffer.from(token);
2673
+ return given.length === expected.length && timingSafeEqual(given, expected);
2674
+ }
2675
+ function maskToken(token) {
2676
+ return token.length > 8 ? `${token.slice(0, 4)}...` : "****";
2677
+ }
1488
2678
  async function handleHttpRequest(req, res, buildOptions, port) {
1489
2679
  const server = buildMcpServer(buildOptions);
1490
2680
  const transport = new StreamableHTTPServerTransport({
@@ -1506,13 +2696,21 @@ async function handleHttpRequest(req, res, buildOptions, port) {
1506
2696
  await server.connect(transport);
1507
2697
  await transport.handleRequest(req, res);
1508
2698
  }
1509
- async function serveHttp(buildOptions, port) {
1510
- const httpServer = createServer((req, res) => {
2699
+ function createHttpHandler(buildOptions, port, token) {
2700
+ return (req, res) => {
1511
2701
  if (new URL(req.url ?? "/", `http://localhost:${port}`).pathname !== HTTP_PATH) {
1512
2702
  res.writeHead(404, { "Content-Type": "application/json" });
1513
2703
  res.end(JSON.stringify({ error: `Not found. The MCP endpoint is ${HTTP_PATH}.` }));
1514
2704
  return;
1515
2705
  }
2706
+ if (!isAuthorized(req.headers.authorization, token)) {
2707
+ res.writeHead(401, {
2708
+ "Content-Type": "application/json",
2709
+ "WWW-Authenticate": "Bearer"
2710
+ });
2711
+ res.end(JSON.stringify({ error: "Unauthorized. Send an Authorization: Bearer <token> header." }));
2712
+ return;
2713
+ }
1516
2714
  handleHttpRequest(req, res, buildOptions, port).catch((err) => {
1517
2715
  logger.error("MCP HTTP request failed", err);
1518
2716
  if (!res.headersSent) {
@@ -1527,12 +2725,18 @@ async function serveHttp(buildOptions, port) {
1527
2725
  }));
1528
2726
  }
1529
2727
  });
1530
- });
2728
+ };
2729
+ }
2730
+ async function serveHttp(buildOptions, port, resolved) {
2731
+ const httpServer = createServer(createHttpHandler(buildOptions, port, resolved.token));
1531
2732
  await new Promise((resolve, reject) => {
1532
2733
  httpServer.once("error", reject);
1533
2734
  httpServer.listen(port, "127.0.0.1", () => resolve());
1534
2735
  });
1535
2736
  process.stderr.write(`Bike4Mind MCP server listening on http://127.0.0.1:${port}${HTTP_PATH}\n`);
2737
+ const shown = resolved.source === "generated" ? resolved.token : maskToken(resolved.token);
2738
+ process.stderr.write(`Authorization: Bearer ${shown}\n`);
2739
+ process.stderr.write("Set a fixed token with --token or B4M_MCP_TOKEN.\n");
1536
2740
  await new Promise((resolve) => {
1537
2741
  const shutdown = () => httpServer.close(() => resolve());
1538
2742
  process.once("SIGINT", shutdown);
@@ -1540,16 +2744,11 @@ async function serveHttp(buildOptions, port) {
1540
2744
  });
1541
2745
  }
1542
2746
  async function handleMcpServeCommand(options) {
2747
+ if (options.local && options.http) throw new Error("--local serves over stdio only; drop --http.");
1543
2748
  const writeFrame = options.http ? void 0 : captureStdout();
1544
2749
  const configStore = new ConfigStore();
1545
- const buildOptions = {
1546
- baseURL: await resolveBaseURL(options, configStore),
1547
- apiKey: options.apiKey ?? process.env.B4M_API_KEY,
1548
- configStore,
1549
- version: options.version
1550
- };
1551
- if (writeFrame) await serveStdio(buildOptions, writeFrame);
1552
- else await serveHttp(buildOptions, options.port ?? 7e3);
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));
1553
2752
  }
1554
2753
  //#endregion
1555
2754
  export { handleMcpServeCommand };