@bike4mind/cli 4.0.0 → 4.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (56) hide show
  1. package/README.md +184 -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-Bvmcy2kf.mjs} +3807 -1375
  6. package/dist/{ApiClient-_JrM_xWw.mjs → ApiClient-Yp2LPlX3.mjs} +22 -3
  7. package/dist/BubblewrapRuntime-OI4qFPNB.mjs +157 -0
  8. package/dist/ConfigStore-Bo4od3Eu.mjs +2 -0
  9. package/dist/ConfigStore-CP1W86Ui.mjs +3438 -0
  10. package/dist/{ConfigStore-BwqsQ0U9.mjs → Logger-3RbeTZ9o.mjs} +34769 -22138
  11. package/dist/{ProxyManager-B0-RuR2w.mjs → ProxyManager-TxEKlgdO.mjs} +88 -3
  12. package/dist/{RemoteSkillSource-qTvRkaNA.mjs → RemoteSkillSource-D_F99yBR.mjs} +5 -0
  13. package/dist/{SandboxOrchestrator-BcUv9fQ3.mjs → SandboxOrchestrator-lpxVEFO7.mjs} +26 -7
  14. package/dist/SandboxRuntimeAdapter-C3xICJtQ.mjs +190 -0
  15. package/dist/SandboxRuntimeAdapter-u6c_IrjP.mjs +2 -0
  16. package/dist/SeatbeltRuntime-Ccd_QbjX.mjs +194 -0
  17. package/dist/{WorkItemsClient-CERTDrhT.mjs → WorkItemsClient-D4sFGL9X.mjs} +1 -1
  18. package/dist/agents/defaults/review.md +8 -1
  19. package/dist/agents/defaults/test.md +8 -1
  20. package/dist/buildToolSearch-CqHKSLtG.mjs +417 -0
  21. package/dist/commands/acpCommand.mjs +26 -20
  22. package/dist/commands/apiCommand.mjs +3 -5
  23. package/dist/commands/doctorCommand.mjs +2 -2
  24. package/dist/commands/envCommand.mjs +1 -1
  25. package/dist/commands/headlessCommand.mjs +118 -37
  26. package/dist/commands/hostCommand.mjs +2344 -0
  27. package/dist/commands/mcpCommand.mjs +45 -30
  28. package/dist/commands/mirrorCommand.mjs +279 -0
  29. package/dist/commands/modelsCommand.mjs +1117 -0
  30. package/dist/commands/pluginCommand.mjs +9 -9
  31. package/dist/commands/skillsCommand.mjs +175 -30
  32. package/dist/commands/updateCommand.mjs +2 -2
  33. package/dist/curated-build.json +1 -0
  34. package/dist/dist-BPhZ0dCz.mjs +4776 -0
  35. package/dist/dist-K7a9yOUb.mjs +7864 -0
  36. package/dist/fit-BOnDsgbk.mjs +200 -0
  37. package/dist/{grepSearch-BgoOOwGe-B388GxRD.mjs → grepSearch-CLtEqT4j-BnKPtNWr.mjs} +2 -2
  38. package/dist/index.mjs +3215 -508
  39. package/dist/modelHub-BSB6qRFP.mjs +1963 -0
  40. package/dist/modelServers-B7zI5XnO.mjs +2465 -0
  41. package/dist/{package-CQaam4Dq.mjs → package-WlxLVpUb.mjs} +1 -1
  42. package/dist/{serve-CFxUhjml.mjs → serve-DpsV0mag.mjs} +599 -26
  43. package/dist/store-Bpdo9Syo.mjs +2 -0
  44. package/dist/{store-BbvSi3KK.mjs → store-xeJRhBtO.mjs} +2 -0
  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-Boq0RruU.mjs} +7 -29
  48. package/package.json +17 -14
  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/buildToolSearch-D9GEK91u.mjs +0 -2351
  54. package/dist/dist-Ul2qwn5x.mjs +0 -624
  55. package/dist/store-BYeE0shc.mjs +0 -2
  56. package/dist/types-I45lMh7Q.mjs +0 -2
@@ -19,6 +19,7 @@ import { dirname, join, resolve } from 'path';
19
19
  import { existsSync } from 'fs';
20
20
  import yargs from 'yargs';
21
21
  import { hideBin } from 'yargs/helpers';
22
+ import { splitEnvFlags } from './envFlags.mjs';
22
23
 
23
24
  const __filename = fileURLToPath(import.meta.url);
24
25
  const __dirname = dirname(__filename);
@@ -29,30 +30,43 @@ const require = createRequire(import.meta.url);
29
30
  // whichever package.json it discovers first, which is not necessarily ours.
30
31
  const { version: cliVersion } = require('../package.json');
31
32
 
32
- // --- API environment flags (--dev / --prod) ---
33
- // Intercept these BEFORE yargs parses argv. They're accepted with either a
34
- // single or double dash (e.g. `b4m -prod` and `b4m --prod` both work), but
35
- // single-dash multi-char tokens would otherwise be split into clustered short
36
- // flags by yargs (`-prod` -> `-p -r -o -d`, colliding with -p/--prompt). We pull
37
- // them out here, record the target, and strip them so yargs sees a clean argv.
38
- const ENV_FLAG_MAP = {
39
- '--dev': 'dev', '-dev': 'dev', '--local': 'dev', '-local': 'dev',
40
- '--prod': 'prod', '-prod': 'prod', '--production': 'prod', '-production': 'prod',
41
- };
42
- let envTarget = null;
43
- {
44
- const cleaned = [];
45
- for (const token of process.argv.slice(2)) {
46
- if (Object.prototype.hasOwnProperty.call(ENV_FLAG_MAP, token)) {
47
- envTarget = ENV_FLAG_MAP[token]; // last one wins
48
- } else {
49
- cleaned.push(token);
50
- }
33
+ // Auto-detect environment: prefer production mode when dist exists
34
+ const distPath = join(__dirname, '../dist/index.mjs');
35
+ const srcPath = join(__dirname, '../src/index.tsx');
36
+ const hasSource = existsSync(srcPath);
37
+ const hasDist = existsSync(distPath);
38
+
39
+ // Development mode ONLY when:
40
+ // 1. NODE_ENV is explicitly 'development', OR
41
+ // 2. dist doesn't exist but source does (fallback)
42
+ // Otherwise: use production mode (this is what npm users will run)
43
+ const isDev = process.env.NODE_ENV === 'development' ||
44
+ (!hasDist && hasSource);
45
+
46
+ // `b4m host ...` is b4m-host: its arguments go through untouched, before yargs or the env flags see them,
47
+ // and dial-stdio's stdout must carry nothing but the bridged bytes.
48
+ if (process.argv[2] === 'host') {
49
+ let handleHostCommand;
50
+ if (isDev) {
51
+ const { register } = require('tsx/esm/api');
52
+ register();
53
+ ({ handleHostCommand } = await import('../src/commands/hostCommand.ts'));
54
+ } else {
55
+ ({ handleHostCommand } = await import('../dist/commands/hostCommand.mjs'));
51
56
  }
52
- // Rebuild argv without the env tokens so yargs doesn't choke on them.
53
- process.argv = [process.argv[0], process.argv[1], ...cleaned];
57
+ process.exit(await handleHostCommand(process.argv.slice(3)));
54
58
  }
55
59
 
60
+ // --- API environment flags (--dev / --prod) ---
61
+ // Intercept these BEFORE yargs parses argv (see envFlags.mjs) and strip them so
62
+ // yargs sees a clean argv.
63
+ const { cleaned: cleanedArgs, envTarget, envFlags, mcpServe, serveLocal } = splitEnvFlags(process.argv.slice(2));
64
+ if (serveLocal && envTarget) {
65
+ process.stderr.write(`Error: mcp serve --local ignores the backend; drop ${envFlags.join(' ')}.\n`);
66
+ process.exit(1);
67
+ }
68
+ process.argv = [process.argv[0], process.argv[1], ...cleanedArgs];
69
+
56
70
  const argv = await yargs(hideBin(process.argv))
57
71
  // --dev / --prod are declared here ONLY so they appear in `--help`. The actual
58
72
  // handling is the pre-yargs argv interception above - these yargs-side values
@@ -93,7 +107,7 @@ const argv = await yargs(hideBin(process.argv))
93
107
  })
94
108
  .option('output-format', {
95
109
  type: 'string',
96
- description: 'Output format when using -p: text (default), json, stream-json (NDJSON)',
110
+ description: 'Output format when using -p: text (default), json, stream-json (NDJSON); json also applies to b4m models ls/search/show/curated',
97
111
  choices: ['text', 'json', 'stream-json'],
98
112
  default: 'text',
99
113
  })
@@ -108,7 +122,7 @@ const argv = await yargs(hideBin(process.argv))
108
122
  })
109
123
  .option('ollama-host', {
110
124
  type: 'string',
111
- description: 'Add local Ollama models to the model picker (e.g. http://localhost:11434)',
125
+ description: 'Add local Ollama models to the model picker (e.g. http://localhost:11434); `b4m models` remembers it',
112
126
  })
113
127
  // claude-compatible flags (host drop-in masquerade). Declared so a host's
114
128
  // claude launch flags parse into named options instead of leaking into the
@@ -204,6 +218,11 @@ const argv = await yargs(hideBin(process.argv))
204
218
  description: 'Serve over streamable HTTP instead of stdio',
205
219
  default: false,
206
220
  })
221
+ .option('local', {
222
+ type: 'boolean',
223
+ description: 'Serve only the local model tools (models_*), with no Bike4Mind backend. Stdio only',
224
+ default: false,
225
+ })
207
226
  .option('port', {
208
227
  type: 'number',
209
228
  description: 'Port for --http mode',
@@ -222,6 +241,7 @@ const argv = await yargs(hideBin(process.argv))
222
241
  description: 'Bearer token required by --http mode (overrides B4M_MCP_TOKEN; generated and printed when unset). Visible in process listings; prefer B4M_MCP_TOKEN',
223
242
  })
224
243
  .example('b4m mcp serve', 'Serve over stdio for Claude Desktop and other local clients')
244
+ .example('b4m mcp serve --local', 'Serve only the local model tools, without a backend')
225
245
  .example('b4m mcp serve --http --port 7000', 'Serve over streamable HTTP on port 7000');
226
246
  }, async () => {
227
247
  // Handled by external command handler
@@ -256,7 +276,7 @@ const argv = await yargs(hideBin(process.argv))
256
276
  })
257
277
  .command('skills', 'Manage your Bike4Mind skills', (yargs) => {
258
278
  return yargs
259
- .command('push <path>', 'Create or update a skill from a Claude Code SKILL.md', (yargs) => {
279
+ .command('push <path>', 'Create or update a skill from a Claude Code SKILL.md, and optionally publish it', (yargs) => {
260
280
  return yargs
261
281
  .positional('path', {
262
282
  type: 'string',
@@ -272,15 +292,164 @@ const argv = await yargs(hideBin(process.argv))
272
292
  description: "Push another author's Skill Market skill as your own without asking",
273
293
  default: false,
274
294
  })
295
+ .option('publish', {
296
+ type: 'boolean',
297
+ description: 'Also list it on the Skill Market: a new listing, or a new version of its live listing',
298
+ default: false,
299
+ })
300
+ .option('visibility', {
301
+ type: 'string',
302
+ choices: ['organization', 'public', 'unlisted'],
303
+ description: 'Who can see a new listing (with --publish)',
304
+ default: 'organization',
305
+ })
306
+ .option('org', {
307
+ type: 'string',
308
+ description: 'Organization id for an organization listing; optional when you belong to exactly one',
309
+ })
310
+ .option('tags', {
311
+ type: 'string',
312
+ description: 'Comma-separated listing tags (with --publish)',
313
+ })
314
+ .option('api-key', {
315
+ type: 'string',
316
+ description:
317
+ 'Bike4Mind API key with the skills:write and me:read scopes (overrides B4M_API_KEY and the stored login). Visible in process listings; prefer B4M_API_KEY, which also takes precedence over the stored login when set, even without --publish',
318
+ })
275
319
  .example('b4m skills push ~/.claude/skills/my-skill', 'Create a skill from a Claude Code skill folder')
276
- .example('b4m skills push ./SKILL.md --update', 'Update the existing skill of the same name');
320
+ .example('b4m skills push ./SKILL.md --update', 'Update the existing skill of the same name')
321
+ .example('b4m skills push ./my-skill --publish --update', 'Update the skill and publish it to the Skill Market');
277
322
  }, async () => {
278
323
  // Handled by external command handler
279
324
  })
280
325
  .demandCommand(1, 'You must provide a subcommand (push)');
281
326
  })
327
+ .command('host', 'Run b4m-host, which reports this machine\'s hardware and Ollama to Bike4Mind (see: b4m host --help)', {}, () => {
328
+ // `host` as the first argument is handled at the top of this file; reaching here means a flag came before it.
329
+ process.stderr.write('b4m host must be the first argument: b4m host <command> (see: b4m host --help)\n');
330
+ process.exit(2);
331
+ })
332
+ .command('models', 'Find, download and use local models (Ollama, Hugging Face GGUF)', (yargs) => {
333
+ return yargs
334
+ .option('server', {
335
+ type: 'string',
336
+ description: "Run ls, use, pull or rm against one of Desktop's saved model servers (see: b4m models servers)",
337
+ })
338
+ .command(['ls', 'list'], 'List models installed on the local runtime', {}, async () => {
339
+ // Handled by external command handler
340
+ })
341
+ .command('servers [action] [name]', "List Desktop's saved model servers, find the ones on a machine over SSH, or log in or out of one", (yargs) => {
342
+ return yargs
343
+ .positional('action', { type: 'string', choices: ['discover', 'login', 'logout'], describe: 'Find servers over SSH, or keep or remove the CLI\'s credential for a server' })
344
+ .positional('name', { type: 'string', describe: 'Server name, as `b4m models servers` shows it; for discover, an SSH destination' })
345
+ .option('port', {
346
+ type: 'string',
347
+ description: 'discover: look only at this port on that machine, instead of the usual ones',
348
+ })
349
+ .option('check-tools', {
350
+ type: 'boolean',
351
+ description: 'servers: send each OpenAI-compatible server a one-token request to see whether it accepts tool calls',
352
+ default: false,
353
+ })
354
+ .option('token-stdin', {
355
+ type: 'boolean',
356
+ description: 'login: read the credential from stdin instead of prompting',
357
+ default: false,
358
+ })
359
+ .example('b4m models servers', 'List the servers with their status')
360
+ .example('b4m models servers discover me@gpu-box', 'Find Ollama, LM Studio, llama-server and vLLM on gpu-box over SSH')
361
+ .example('b4m models servers login gpu-box', 'Enter the CLI\'s credential for gpu-box (hidden)');
362
+ }, async () => {
363
+ // Handled by external command handler
364
+ })
365
+ .command('search <query..>', 'Search Hugging Face for GGUF models', (yargs) => {
366
+ return yargs
367
+ .positional('query', { type: 'string', describe: 'Search terms' })
368
+ .option('include-abliterated', {
369
+ type: 'boolean',
370
+ description: 'Also list abliterated and uncensored builds, labelled and last',
371
+ default: false,
372
+ });
373
+ }, async () => {
374
+ // Handled by external command handler
375
+ })
376
+ .command('show <repo>', "Show a Hugging Face repo's GGUF builds, license and gating", (yargs) => {
377
+ return yargs.positional('repo', { type: 'string', describe: 'owner/repo' });
378
+ }, async () => {
379
+ // Handled by external command handler
380
+ })
381
+ .command('curated', 'List the models Bike4Mind picked, with picks for this computer first', (yargs) => {
382
+ return yargs
383
+ .option('refresh', {
384
+ type: 'boolean',
385
+ description: 'Check for a newer signed list now instead of when the last check is 6 hours old',
386
+ default: false,
387
+ })
388
+ .option('offline', {
389
+ type: 'boolean',
390
+ description: 'Use the last verified list on this computer (else the bundled one) with no update check (also: B4M_CURATED=off)',
391
+ default: false,
392
+ });
393
+ }, async () => {
394
+ // Handled by external command handler
395
+ })
396
+ .command('pull <ref>', 'Download a model after showing its size and license', (yargs) => {
397
+ return yargs
398
+ .positional('ref', {
399
+ type: 'string',
400
+ describe: 'owner/repo[:quant] or hf.co/owner/repo:quant (Hugging Face), or an Ollama name like qwen2.5:0.5b',
401
+ })
402
+ .option('yes', {
403
+ type: 'boolean',
404
+ description: 'Download without asking for confirmation',
405
+ default: false,
406
+ })
407
+ .option('accept-license', {
408
+ type: 'boolean',
409
+ description: 'Accept a non-permissive model license without a prompt',
410
+ default: false,
411
+ })
412
+ .option('force', {
413
+ type: 'boolean',
414
+ description: 'Download even when the fit check rates the model too large for this machine',
415
+ default: false,
416
+ })
417
+ .option('offline', {
418
+ type: 'boolean',
419
+ description: 'Use the last verified curated list on this computer with no update check (also: B4M_CURATED=off)',
420
+ default: false,
421
+ })
422
+ .example('b4m models pull Qwen/Qwen2.5-0.5B-Instruct-GGUF:Q4_K_M', 'Pull a Hugging Face GGUF build')
423
+ .example('b4m models pull qwen2.5:0.5b', 'Pull from the Ollama library');
424
+ }, async () => {
425
+ // Handled by external command handler
426
+ })
427
+ .command(['rm <name>', 'remove <name>'], 'Remove an installed model', (yargs) => {
428
+ return yargs
429
+ .positional('name', { type: 'string', describe: 'Installed model name' })
430
+ .option('yes', {
431
+ type: 'boolean',
432
+ description: 'Remove without asking for confirmation',
433
+ default: false,
434
+ });
435
+ }, async () => {
436
+ // Handled by external command handler
437
+ })
438
+ .command('use <name>', 'Make an installed model the default the CLI chats with', (yargs) => {
439
+ return yargs.positional('name', { type: 'string', describe: 'Installed model name' });
440
+ }, async () => {
441
+ // Handled by external command handler
442
+ })
443
+ .example('b4m models ls --ollama-host http://127.0.0.1:11434', 'Use and remember an Ollama host')
444
+ .demandCommand(1, 'You must provide a subcommand (ls, search, show, curated, servers, pull, rm, use)');
445
+ })
282
446
  .command('update', 'Check for and install CLI updates')
283
447
  .command('doctor', 'Run diagnostic checks on CLI installation')
448
+ .command('mirror <dir>', 'Mirror your notebooks into a local v2 bundle and keep it current', y =>
449
+ y
450
+ .positional('dir', { type: 'string', describe: 'Directory that holds the mirror state and bundle' })
451
+ .option('watch', { type: 'number', describe: 'Keep syncing, pausing this many seconds between passes' })
452
+ )
284
453
  .command('acp', 'Run as an Agent Client Protocol (ACP) stdio server for editors like Zed')
285
454
  .help()
286
455
  .alias('help', 'h')
@@ -314,6 +483,7 @@ if (argv['no-remote-skills']) {
314
483
  }
315
484
 
316
485
  // claude-compatible flags -> B4M_* env (read by src/index.tsx init).
486
+ // Host-launch signal: keep in sync with HOST_FLAG_ENV_KEYS in src/bootstrap/startupTrustGates.ts.
317
487
  // Mirrors the established bin->env->init channel (cf. --add-dir -> B4M_ADDITIONAL_DIRS).
318
488
  if (argv['mcp-config']) {
319
489
  process.env.B4M_MCP_CONFIG_FILE = resolve(argv['mcp-config']);
@@ -341,24 +511,11 @@ if (argv.resume) {
341
511
  }
342
512
  // Positional task (claude `<prompt>` form): seeds AND submits turn 1, stays interactive.
343
513
  // Only when it's not a known subcommand and headless -p wasn't used.
344
- const KNOWN_SUBCOMMANDS = new Set(['mcp', 'plugin', 'skills', 'update', 'doctor', 'acp']);
514
+ const KNOWN_SUBCOMMANDS = new Set(['mcp', 'plugin', 'skills', 'models', 'update', 'doctor', 'mirror', 'acp', 'host']);
345
515
  if (argv.prompt === undefined && argv._.length > 0 && !KNOWN_SUBCOMMANDS.has(String(argv._[0]))) {
346
516
  process.env.B4M_INITIAL_PROMPT = String(argv._[0]);
347
517
  }
348
518
 
349
- // Auto-detect environment: prefer production mode when dist exists
350
- const distPath = join(__dirname, '../dist/index.mjs');
351
- const srcPath = join(__dirname, '../src/index.tsx');
352
- const hasSource = existsSync(srcPath);
353
- const hasDist = existsSync(distPath);
354
-
355
- // Development mode ONLY when:
356
- // 1. NODE_ENV is explicitly 'development', OR
357
- // 2. dist doesn't exist but source does (fallback)
358
- // Otherwise: use production mode (this is what npm users will run)
359
- const isDev = process.env.NODE_ENV === 'development' ||
360
- (!hasDist && hasSource);
361
-
362
519
  // Signal source mode to the app so endpoint resolution can default an
363
520
  // otherwise-unconfigured run to the local dev server (build-time brand
364
521
  // defaults are never injected into a source run). Set before any command
@@ -414,7 +571,14 @@ if (envTarget) {
414
571
  ({ applyEnvironmentFlag } = await import('../dist/commands/envCommand.mjs'));
415
572
  }
416
573
 
417
- await applyEnvironmentFlag(envTarget);
574
+ // On `mcp serve` stdout is the JSON-RPC stream, so the banner goes to stderr.
575
+ const log = console.log;
576
+ if (mcpServe) console.log = console.error;
577
+ try {
578
+ await applyEnvironmentFlag(envTarget);
579
+ } finally {
580
+ console.log = log;
581
+ }
418
582
  } catch (error) {
419
583
  console.error('Failed to switch API environment:', error.message);
420
584
  process.exit(1);
@@ -534,6 +698,30 @@ if (argv._[0] === 'skills') {
534
698
  }
535
699
  }
536
700
 
701
+ // Handle models subcommands (external commands)
702
+ if (argv._[0] === 'models') {
703
+ const modelsSubcommand = argv._[1];
704
+
705
+ try {
706
+ let handleModelsCommand;
707
+
708
+ if (isDev) {
709
+ const { register } = require('tsx/esm/api');
710
+ register();
711
+ const module = await import('../src/commands/modelsCommand.ts');
712
+ handleModelsCommand = module.handleModelsCommand;
713
+ } else {
714
+ const module = await import('../dist/commands/modelsCommand.mjs');
715
+ handleModelsCommand = module.handleModelsCommand;
716
+ }
717
+
718
+ process.exit(await handleModelsCommand(modelsSubcommand, argv));
719
+ } catch (error) {
720
+ console.error('Error:', error.message);
721
+ process.exit(1);
722
+ }
723
+ }
724
+
537
725
  // Handle update command (external command)
538
726
  if (argv._[0] === 'update') {
539
727
  try {
@@ -605,6 +793,27 @@ if (argv._[0] === 'doctor') {
605
793
  }
606
794
  }
607
795
 
796
+ // Handle mirror command (external command)
797
+ if (argv._[0] === 'mirror') {
798
+ try {
799
+ let handleMirrorCommand;
800
+
801
+ if (isDev) {
802
+ const { register } = require('tsx/esm/api');
803
+ register();
804
+ handleMirrorCommand = (await import('../src/commands/mirrorCommand.ts')).handleMirrorCommand;
805
+ } else {
806
+ handleMirrorCommand = (await import('../dist/commands/mirrorCommand.mjs')).handleMirrorCommand;
807
+ }
808
+
809
+ await handleMirrorCommand(argv.dir, { watchSeconds: argv.watch });
810
+ process.exit(0);
811
+ } catch (error) {
812
+ console.error('Error:', error.message);
813
+ process.exit(1);
814
+ }
815
+ }
816
+
608
817
  if (isDev) {
609
818
  // Note: this is about *how the CLI runs* (unbuilt TypeScript source), which is
610
819
  // distinct from the `--dev` flag (which selects the local dev *backend*).
@@ -0,0 +1,17 @@
1
+ export type EnvTarget = 'dev' | 'prod';
2
+
3
+ export declare const ENV_FLAG_MAP: Record<string, EnvTarget>;
4
+
5
+ export declare const VALUE_OPTIONS: ReadonlySet<string>;
6
+
7
+ export declare const ARRAY_OPTIONS: ReadonlySet<string>;
8
+
9
+ export interface SplitEnvFlags {
10
+ cleaned: string[];
11
+ envTarget: EnvTarget | null;
12
+ envFlags: string[];
13
+ mcpServe: boolean;
14
+ serveLocal: boolean;
15
+ }
16
+
17
+ export declare function splitEnvFlags(args: string[]): SplitEnvFlags;
@@ -0,0 +1,89 @@
1
+ // API environment flags (--dev / --prod), split out of argv before yargs parses it.
2
+ // They're accepted with either a single or double dash (e.g. `b4m -prod` and
3
+ // `b4m --prod` both work), but single-dash multi-char tokens would otherwise be
4
+ // split into clustered short flags by yargs (`-prod` -> `-p -r -o -d`, colliding
5
+ // with -p/--prompt), so they are removed here and recorded as the target.
6
+ export const ENV_FLAG_MAP = {
7
+ '--dev': 'dev',
8
+ '-dev': 'dev',
9
+ '--local': 'dev',
10
+ '-local': 'dev',
11
+ '--prod': 'prod',
12
+ '-prod': 'prod',
13
+ '--production': 'prod',
14
+ '-production': 'prod',
15
+ };
16
+
17
+ const LOCAL_TOKENS = new Set(['--local', '-local']);
18
+
19
+ // Top-level options that take the next token as their value, so that token is not a positional
20
+ // (`b4m --ollama-host <url> mcp serve --local`). Array options take every following non-flag token,
21
+ // as yargs parses them. Must stay in sync with the global options in bike4mind-cli.mjs;
22
+ // envFlags.test.ts checks it.
23
+ export const VALUE_OPTIONS = new Set([
24
+ '--prompt',
25
+ '-p',
26
+ '--output-format',
27
+ '--permission-policy',
28
+ '--ollama-host',
29
+ '--mcp-config',
30
+ '--append-system-prompt',
31
+ '--settings',
32
+ '--session-id',
33
+ '--resume',
34
+ '--api-url',
35
+ ]);
36
+ export const ARRAY_OPTIONS = new Set(['--add-dir', '--allowedTools', '--allowed-tools']);
37
+
38
+ function positionalIndexes(args) {
39
+ const positionals = [];
40
+ let takesNext = false;
41
+ let inArray = false;
42
+ args.forEach((token, index) => {
43
+ if (takesNext) {
44
+ takesNext = false;
45
+ } else if (Object.prototype.hasOwnProperty.call(ENV_FLAG_MAP, token)) {
46
+ // Stripped before yargs sees argv, so it neither ends an array option nor is a positional.
47
+ } else if (token.startsWith('-')) {
48
+ takesNext = VALUE_OPTIONS.has(token);
49
+ inArray = ARRAY_OPTIONS.has(token);
50
+ } else if (!inArray) {
51
+ positionals.push(index);
52
+ }
53
+ });
54
+ return positionals;
55
+ }
56
+
57
+ /**
58
+ * Split the environment flags out of `args` (argv without node and the script).
59
+ *
60
+ * `mcpServe` is true when `mcp` is the first positional and `serve` the next one. Only then, and only
61
+ * after `serve`, is `--local` serve's own flag (local model tools only), kept as `--local` and reported
62
+ * as `serveLocal`; everywhere else it is the --dev alias. `envFlags` lists the env tokens removed.
63
+ */
64
+ export function splitEnvFlags(args) {
65
+ const positionals = positionalIndexes(args);
66
+ const mcpServe = args[positionals[0]] === 'mcp' && args[positionals[1]] === 'serve';
67
+ const serveIndex = mcpServe ? positionals[1] : Infinity;
68
+
69
+ const cleaned = [];
70
+ const envFlags = [];
71
+ let envTarget = null;
72
+ let serveLocal = false;
73
+ args.forEach((token, index) => {
74
+ if (index > serveIndex && LOCAL_TOKENS.has(token)) {
75
+ cleaned.push('--local');
76
+ serveLocal = true;
77
+ } else if (index > serveIndex && /^--?local=/.test(token)) {
78
+ const value = token.slice(token.indexOf('=') + 1);
79
+ cleaned.push(`--local=${value}`);
80
+ serveLocal = value !== 'false';
81
+ } else if (Object.prototype.hasOwnProperty.call(ENV_FLAG_MAP, token)) {
82
+ envTarget = ENV_FLAG_MAP[token]; // last one wins
83
+ envFlags.push(token);
84
+ } else {
85
+ cleaned.push(token);
86
+ }
87
+ });
88
+ return { cleaned, envTarget, envFlags, mcpServe, serveLocal };
89
+ }