claude-flow 3.71.4 → 3.72.1

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 (118) hide show
  1. package/.claude/helpers/hook-handler.cjs +23 -10
  2. package/.claude/helpers/statusline.cjs +29 -14
  3. package/README.md +18 -3
  4. package/README.zh-CN.md +16 -3
  5. package/node_modules/@claude-flow/codex/.agents/skills/fast-code-edits/SKILL.md +42 -0
  6. package/node_modules/@claude-flow/codex/.agents/skills/graph-mincut/SKILL.md +42 -0
  7. package/node_modules/@claude-flow/codex/.agents/skills/injection-defense/SKILL.md +45 -0
  8. package/node_modules/@claude-flow/codex/.agents/skills/lora-learning/SKILL.md +39 -0
  9. package/node_modules/@claude-flow/codex/.agents/skills/sublinear-solver/SKILL.md +38 -0
  10. package/node_modules/@claude-flow/codex/.agents/skills/vector-quantization/SKILL.md +49 -0
  11. package/node_modules/@claude-flow/codex/dist/generators/skill-md.d.ts.map +1 -1
  12. package/node_modules/@claude-flow/codex/dist/generators/skill-md.js +6 -0
  13. package/node_modules/@claude-flow/codex/dist/generators/skill-md.js.map +1 -1
  14. package/node_modules/@claude-flow/codex/dist/index.d.ts +3 -3
  15. package/node_modules/@claude-flow/codex/dist/index.js +1 -1
  16. package/node_modules/@claude-flow/codex/dist/templates/index.d.ts.map +1 -1
  17. package/node_modules/@claude-flow/codex/dist/templates/index.js +37 -0
  18. package/node_modules/@claude-flow/codex/dist/templates/index.js.map +1 -1
  19. package/node_modules/@claude-flow/codex/dist/types.d.ts +1 -1
  20. package/node_modules/@claude-flow/codex/dist/types.d.ts.map +1 -1
  21. package/node_modules/@claude-flow/codex/package.json +1 -1
  22. package/package.json +9 -6
  23. package/v3/@claude-flow/cli/README.md +18 -3
  24. package/v3/@claude-flow/cli/bin/cli.js +13 -18
  25. package/v3/@claude-flow/cli/bin/mcp-server.js +13 -18
  26. package/v3/@claude-flow/cli/catalog-manifest.json +4 -4
  27. package/v3/@claude-flow/cli/dist/src/appliance/ruvllm-bridge.d.ts +6 -2
  28. package/v3/@claude-flow/cli/dist/src/appliance/ruvllm-bridge.js +13 -8
  29. package/v3/@claude-flow/cli/dist/src/appliance/rvfa-distribution.js +2 -2
  30. package/v3/@claude-flow/cli/dist/src/benchmarks/gaia-critic.d.ts +1 -7
  31. package/v3/@claude-flow/cli/dist/src/benchmarks/gaia-critic.js +1 -7
  32. package/v3/@claude-flow/cli/dist/src/benchmarks/gaia-decomposer.d.ts +1 -8
  33. package/v3/@claude-flow/cli/dist/src/benchmarks/gaia-decomposer.js +1 -8
  34. package/v3/@claude-flow/cli/dist/src/commands/agent-wasm.js +2 -2
  35. package/v3/@claude-flow/cli/dist/src/commands/analyze.js +1 -1
  36. package/v3/@claude-flow/cli/dist/src/commands/daemon.js +1 -1
  37. package/v3/@claude-flow/cli/dist/src/commands/doctor.js +3 -2
  38. package/v3/@claude-flow/cli/dist/src/commands/guidance.js +9 -9
  39. package/v3/@claude-flow/cli/dist/src/commands/hooks.js +13 -8
  40. package/v3/@claude-flow/cli/dist/src/commands/init.js +16 -16
  41. package/v3/@claude-flow/cli/dist/src/commands/neural.js +87 -77
  42. package/v3/@claude-flow/cli/dist/src/commands/route.js +1 -1
  43. package/v3/@claude-flow/cli/dist/src/commands/ruvector/backup.js +7 -5
  44. package/v3/@claude-flow/cli/dist/src/commands/ruvector/benchmark.js +6 -1
  45. package/v3/@claude-flow/cli/dist/src/commands/ruvector/import.js +19 -5
  46. package/v3/@claude-flow/cli/dist/src/commands/ruvector/init.js +1 -1
  47. package/v3/@claude-flow/cli/dist/src/commands/start.js +1 -1
  48. package/v3/@claude-flow/cli/dist/src/commands/status.js +1 -1
  49. package/v3/@claude-flow/cli/dist/src/commands/task.js +18 -1
  50. package/v3/@claude-flow/cli/dist/src/commands/update.js +1 -1
  51. package/v3/@claude-flow/cli/dist/src/funnel/local-signals.js +7 -2
  52. package/v3/@claude-flow/cli/dist/src/init/executor.js +13 -0
  53. package/v3/@claude-flow/cli/dist/src/init/types.d.ts +6 -0
  54. package/v3/@claude-flow/cli/dist/src/init/types.js +3 -0
  55. package/v3/@claude-flow/cli/dist/src/mcp-client.js +2 -0
  56. package/v3/@claude-flow/cli/dist/src/mcp-protocol.d.ts +90 -0
  57. package/v3/@claude-flow/cli/dist/src/mcp-protocol.js +179 -0
  58. package/v3/@claude-flow/cli/dist/src/mcp-server.d.ts +1 -0
  59. package/v3/@claude-flow/cli/dist/src/mcp-server.js +20 -22
  60. package/v3/@claude-flow/cli/dist/src/mcp-tools/agent-execute-core.js +9 -1
  61. package/v3/@claude-flow/cli/dist/src/mcp-tools/agent-tools.d.ts +13 -0
  62. package/v3/@claude-flow/cli/dist/src/mcp-tools/agent-tools.js +59 -8
  63. package/v3/@claude-flow/cli/dist/src/mcp-tools/agentdb-tools.js +34 -2
  64. package/v3/@claude-flow/cli/dist/src/mcp-tools/browser-argv.d.ts +9 -0
  65. package/v3/@claude-flow/cli/dist/src/mcp-tools/browser-argv.js +33 -0
  66. package/v3/@claude-flow/cli/dist/src/mcp-tools/browser-session-tools.js +4 -0
  67. package/v3/@claude-flow/cli/dist/src/mcp-tools/browser-tools.js +12 -2
  68. package/v3/@claude-flow/cli/dist/src/mcp-tools/coordination-tools.js +5 -4
  69. package/v3/@claude-flow/cli/dist/src/mcp-tools/embeddings-tools.js +12 -4
  70. package/v3/@claude-flow/cli/dist/src/mcp-tools/fast-apply-tools.d.ts +4 -0
  71. package/v3/@claude-flow/cli/dist/src/mcp-tools/fast-apply-tools.js +85 -0
  72. package/v3/@claude-flow/cli/dist/src/mcp-tools/glob-exclusions.d.ts +6 -0
  73. package/v3/@claude-flow/cli/dist/src/mcp-tools/glob-exclusions.js +81 -0
  74. package/v3/@claude-flow/cli/dist/src/mcp-tools/hive-mind-tools.js +104 -35
  75. package/v3/@claude-flow/cli/dist/src/mcp-tools/hooks-tools.js +14 -38
  76. package/v3/@claude-flow/cli/dist/src/mcp-tools/import-limits.d.ts +4 -0
  77. package/v3/@claude-flow/cli/dist/src/mcp-tools/import-limits.js +28 -0
  78. package/v3/@claude-flow/cli/dist/src/mcp-tools/memory-tools.js +21 -42
  79. package/v3/@claude-flow/cli/dist/src/mcp-tools/metaharness-tools.js +1 -1
  80. package/v3/@claude-flow/cli/dist/src/mcp-tools/performance-tools.js +7 -2
  81. package/v3/@claude-flow/cli/dist/src/mcp-tools/realpath-containment.d.ts +3 -0
  82. package/v3/@claude-flow/cli/dist/src/mcp-tools/realpath-containment.js +39 -0
  83. package/v3/@claude-flow/cli/dist/src/mcp-tools/record-store.d.ts +8 -0
  84. package/v3/@claude-flow/cli/dist/src/mcp-tools/record-store.js +98 -1
  85. package/v3/@claude-flow/cli/dist/src/mcp-tools/security-tools.d.ts +9 -0
  86. package/v3/@claude-flow/cli/dist/src/mcp-tools/security-tools.js +39 -3
  87. package/v3/@claude-flow/cli/dist/src/mcp-tools/session-tools.js +5 -3
  88. package/v3/@claude-flow/cli/dist/src/mcp-tools/swarm-tools.js +35 -17
  89. package/v3/@claude-flow/cli/dist/src/mcp-tools/task-tools.js +68 -5
  90. package/v3/@claude-flow/cli/dist/src/mcp-tools/terminal-tools.js +9 -0
  91. package/v3/@claude-flow/cli/dist/src/mcp-tools/workflow-tools.js +13 -12
  92. package/v3/@claude-flow/cli/dist/src/mcp-tools/x-federation-join.js +55 -14
  93. package/v3/@claude-flow/cli/dist/src/memory/intelligence.d.ts +11 -0
  94. package/v3/@claude-flow/cli/dist/src/memory/intelligence.js +84 -6
  95. package/v3/@claude-flow/cli/dist/src/memory/memory-initializer.d.ts +6 -2
  96. package/v3/@claude-flow/cli/dist/src/memory/memory-initializer.js +15 -6
  97. package/v3/@claude-flow/cli/dist/src/mods/command-registry/schema.d.ts +12 -12
  98. package/v3/@claude-flow/cli/dist/src/ruvector/ast-analyzer.d.ts +1 -2
  99. package/v3/@claude-flow/cli/dist/src/ruvector/ast-analyzer.js +4 -12
  100. package/v3/@claude-flow/cli/dist/src/ruvector/coverage-router.d.ts +1 -2
  101. package/v3/@claude-flow/cli/dist/src/ruvector/coverage-router.js +4 -12
  102. package/v3/@claude-flow/cli/dist/src/ruvector/diff-classifier.d.ts +1 -2
  103. package/v3/@claude-flow/cli/dist/src/ruvector/diff-classifier.js +3 -12
  104. package/v3/@claude-flow/cli/dist/src/ruvector/fast-apply.d.ts +46 -0
  105. package/v3/@claude-flow/cli/dist/src/ruvector/fast-apply.js +73 -0
  106. package/v3/@claude-flow/cli/dist/src/ruvector/graph-analyzer.d.ts +11 -1
  107. package/v3/@claude-flow/cli/dist/src/ruvector/graph-analyzer.js +22 -36
  108. package/v3/@claude-flow/cli/dist/src/ruvector/mincut-bridge.d.ts +70 -0
  109. package/v3/@claude-flow/cli/dist/src/ruvector/mincut-bridge.js +172 -0
  110. package/v3/@claude-flow/cli/dist/src/ruvector/model-router.d.ts +6 -1
  111. package/v3/@claude-flow/cli/dist/src/ruvector/model-router.js +16 -4
  112. package/v3/@claude-flow/cli/dist/src/services/distill-oracle.d.ts +1 -1
  113. package/v3/@claude-flow/cli/dist/src/services/distill-oracle.js +2 -2
  114. package/v3/@claude-flow/cli/dist/src/services/worker-daemon.js +30 -12
  115. package/v3/@claude-flow/cli/dist/src/transfer/storage/gcs.js +3 -2
  116. package/v3/@claude-flow/cli/package.json +11 -9
  117. package/.claude/.proven-config-version +0 -1
  118. package/.claude/proven-config.json +0 -42
@@ -145,7 +145,7 @@ export const initCommand = {
145
145
  }
146
146
  const force = ctx.flags.force;
147
147
  const dimensions = parseInt(ctx.flags.dimensions || '1536', 10);
148
- const indexType = ctx.flags['index-type'] || 'hnsw';
148
+ const indexType = (ctx.flags.indexType ?? ctx.flags['index-type']) || 'hnsw';
149
149
  // Show configuration
150
150
  output.writeln(output.highlight('Connection Configuration:'));
151
151
  output.printTable({
@@ -85,7 +85,7 @@ const startAction = async (ctx) => {
85
85
  const daemon = ctx.flags.daemon;
86
86
  const port = ctx.flags.port || DEFAULT_PORT;
87
87
  const topology = ctx.flags.topology || DEFAULT_TOPOLOGY;
88
- const skipMcp = ctx.flags['skip-mcp'];
88
+ const skipMcp = ctx.flags.skipMcp;
89
89
  const cwd = ctx.cwd;
90
90
  // Check initialization
91
91
  if (!isInitialized(cwd)) {
@@ -281,7 +281,7 @@ function formatHealth(health) {
281
281
  const statusAction = async (ctx) => {
282
282
  const watch = ctx.flags.watch;
283
283
  const interval = ctx.flags.interval || DEFAULT_WATCH_INTERVAL / 1000;
284
- const healthCheck = ctx.flags['health-check'];
284
+ const healthCheck = ctx.flags.healthCheck;
285
285
  const cwd = ctx.cwd;
286
286
  // Check initialization
287
287
  if (!isInitialized(cwd)) {
@@ -571,6 +571,12 @@ const assignCommand = {
571
571
  taskId,
572
572
  agentIds: selectedAgents
573
573
  });
574
+ // task_assign answers a finished task or an unknown agent with
575
+ // success: false instead of throwing (#4725).
576
+ if (result.success === false) {
577
+ output.printError(`Failed to assign task ${taskId}: ${result.error || 'unknown error'}`);
578
+ return { success: false, exitCode: 1, data: result };
579
+ }
574
580
  output.writeln();
575
581
  output.printSuccess(`Task ${taskId} assigned to ${result.assignedTo.join(', ')}`);
576
582
  return { success: true, data: result };
@@ -592,6 +598,17 @@ const assignCommand = {
592
598
  agentIds: unassign ? [] : agentIds.split(',').map(id => id.trim()),
593
599
  unassign
594
600
  });
601
+ // task_assign answers a finished task or an unknown agent with
602
+ // success: false instead of throwing (#4725).
603
+ if (result.success === false) {
604
+ if (ctx.flags.format === 'json') {
605
+ output.printJson(result);
606
+ }
607
+ else {
608
+ output.printError(`Failed to assign task ${taskId}: ${result.error || 'unknown error'}`);
609
+ }
610
+ return { success: false, exitCode: 1, data: result };
611
+ }
595
612
  output.writeln();
596
613
  if (unassign) {
597
614
  output.printSuccess(`Task ${taskId} unassigned`);
@@ -630,7 +647,7 @@ const retryCommand = {
630
647
  ],
631
648
  action: async (ctx) => {
632
649
  const taskId = ctx.args[0];
633
- const resetState = ctx.flags['reset-state'];
650
+ const resetState = (ctx.flags.resetState ?? ctx.flags['reset-state']);
634
651
  if (!taskId) {
635
652
  output.printError('Task ID is required');
636
653
  return { success: false, exitCode: 1 };
@@ -120,7 +120,7 @@ const allCommand = {
120
120
  autoUpdate: {
121
121
  patch: true,
122
122
  minor: true,
123
- major: flags['include-major'] || false,
123
+ major: flags.includeMajor || false,
124
124
  },
125
125
  };
126
126
  const { results } = await checkForUpdates(config);
@@ -9,7 +9,7 @@
9
9
  */
10
10
  import * as fs from 'fs';
11
11
  import * as path from 'path';
12
- import { execSync } from 'child_process';
12
+ import { execFileSync, execSync } from 'child_process';
13
13
  export function getSecurityStatus(cwd = process.cwd()) {
14
14
  const empty = {
15
15
  status: 'PENDING', findings: 0, cvesFixed: 0, totalCves: 0,
@@ -67,7 +67,12 @@ export function getSwarmStatus() {
67
67
  /** Count of uncommitted-changed files (git status --short line count). */
68
68
  export function getGitUncommittedCount() {
69
69
  try {
70
- const out = execSync('git status --porcelain 2>/dev/null', { encoding: 'utf-8', timeout: 3000 });
70
+ // #4770: no shell, so this also works on Windows.
71
+ const out = execFileSync('git', ['status', '--porcelain'], {
72
+ encoding: 'utf-8',
73
+ timeout: 3000,
74
+ stdio: ['ignore', 'pipe', 'ignore'],
75
+ });
71
76
  const lines = out.split('\n').filter((l) => l.trim().length > 0);
72
77
  return lines.length;
73
78
  }
@@ -78,6 +78,17 @@ const SKILLS_MAP = {
78
78
  'sparc-methodology',
79
79
  'stream-chain',
80
80
  ],
81
+ // How and when to use the ecosystem packages ruflo ships or wires in:
82
+ // ruvector + @ruvector/mincut-wasm, @ruvector/rabitq-wasm, sublinear-time-solver,
83
+ // @claude-flow/aidefence, agent-booster, @ruvector/learning-wasm.
84
+ ecosystem: [
85
+ 'vector-quantization',
86
+ 'graph-mincut',
87
+ 'sublinear-solver',
88
+ 'injection-defense',
89
+ 'fast-code-edits',
90
+ 'lora-learning',
91
+ ],
81
92
  };
82
93
  /**
83
94
  * Commands to copy based on configuration
@@ -1087,6 +1098,8 @@ async function copySkills(targetDir, options, result) {
1087
1098
  skillsToCopy.push(...SKILLS_MAP.dualMode);
1088
1099
  if (skillsConfig.legacy)
1089
1100
  skillsToCopy.push(...SKILLS_MAP.legacy);
1101
+ if (skillsConfig.ecosystem ?? true)
1102
+ skillsToCopy.push(...SKILLS_MAP.ecosystem);
1090
1103
  }
1091
1104
  // Find source skills directory
1092
1105
  const sourceSkillsDir = findSourceDir('skills', options.sourceBaseDir);
@@ -78,6 +78,12 @@ export interface SkillsConfig {
78
78
  dualMode: boolean;
79
79
  /** Include legacy skills that document commands v3 does not ship (opt-in) */
80
80
  legacy: boolean;
81
+ /**
82
+ * Include ecosystem skills (vector quantization, graph min-cut, sublinear
83
+ * solving, injection defense, fast code edits, LoRA learning). Optional so
84
+ * existing SkillsConfig literals stay valid; absent means on.
85
+ */
86
+ ecosystem?: boolean;
81
87
  /** Include all available skills */
82
88
  all: boolean;
83
89
  }
@@ -79,6 +79,7 @@ export const DEFAULT_INIT_OPTIONS = {
79
79
  v3: false, // ADR-128: opt-in like agents.v3; use --full or `init skills --v3`
80
80
  dualMode: false, // Optional: enable with --dual flag
81
81
  legacy: false, // #4539: stream-chain/sparc document verbs v3 does not ship
82
+ ecosystem: true, // ruvector / agent-booster / aidefence usage skills
82
83
  all: false,
83
84
  },
84
85
  commands: {
@@ -188,6 +189,7 @@ export const MINIMAL_INIT_OPTIONS = {
188
189
  v3: false,
189
190
  dualMode: false,
190
191
  legacy: false,
192
+ ecosystem: false,
191
193
  all: false,
192
194
  },
193
195
  agents: {
@@ -249,6 +251,7 @@ export const FULL_INIT_OPTIONS = {
249
251
  v3: true,
250
252
  dualMode: true, // Include in full init
251
253
  legacy: true, // Include in full init
254
+ ecosystem: true,
252
255
  all: true,
253
256
  },
254
257
  commands: {
@@ -13,6 +13,7 @@ import { swarmTools } from './mcp-tools/swarm-tools.js';
13
13
  import { memoryTools } from './mcp-tools/memory-tools.js';
14
14
  import { configTools } from './mcp-tools/config-tools.js';
15
15
  import { hooksTools } from './mcp-tools/hooks-tools.js';
16
+ import { fastApplyTools } from './mcp-tools/fast-apply-tools.js';
16
17
  import { taskTools } from './mcp-tools/task-tools.js';
17
18
  import { sessionTools } from './mcp-tools/session-tools.js';
18
19
  import { hiveMindTools } from './mcp-tools/hive-mind-tools.js';
@@ -131,6 +132,7 @@ registerTools([
131
132
  ...memoryTools,
132
133
  ...configTools,
133
134
  ...hooksTools,
135
+ ...fastApplyTools,
134
136
  ...taskTools,
135
137
  ...sessionTools,
136
138
  ...hiveMindTools,
@@ -0,0 +1,90 @@
1
+ /**
2
+ * MCP protocol-version handling for the stdio servers (ADR-524).
3
+ *
4
+ * Ruflo ships three stdio entry points (`bin/cli.js` auto-detect, `bin/mcp-server.js`,
5
+ * and `MCPServerManager` in mcp-server.ts). All three answered `initialize` with a
6
+ * hardcoded `2024-11-05` and knew nothing of the 2026-07-28 revision, which drops the
7
+ * handshake and carries the version on every request. This module is the one place
8
+ * that decides which revision a message speaks, so the three handlers cannot drift.
9
+ *
10
+ * Dual-era behaviour (spec: basic/versioning):
11
+ * - `initialize` selects legacy semantics; the requested legacy version is echoed.
12
+ * - a request carrying `_meta["io.modelcontextprotocol/protocolVersion"]` is served
13
+ * statelessly: `resultType` and `serverInfo` on every result, cache hints on lists,
14
+ * `-32602` for an unknown resource, `-32022` for an unsupported version.
15
+ * - `server/discover` is always answered, so a dual-era client's stdio probe succeeds.
16
+ */
17
+ export declare const MODERN_PROTOCOL_VERSIONS: readonly ["2026-07-28"];
18
+ export declare const LEGACY_PROTOCOL_VERSIONS: readonly ["2025-11-25", "2025-06-18", "2024-11-05"];
19
+ export declare const SUPPORTED_PROTOCOL_VERSIONS: readonly string[];
20
+ /** Offered to a legacy client whose requested version we do not know. */
21
+ export declare const LATEST_LEGACY_PROTOCOL_VERSION: "2025-11-25";
22
+ export declare const META_PROTOCOL_VERSION = "io.modelcontextprotocol/protocolVersion";
23
+ export declare const META_CLIENT_CAPABILITIES = "io.modelcontextprotocol/clientCapabilities";
24
+ export declare const META_SERVER_INFO = "io.modelcontextprotocol/serverInfo";
25
+ export declare const ERROR_INVALID_PARAMS = -32602;
26
+ export declare const ERROR_UNSUPPORTED_PROTOCOL_VERSION = -32022;
27
+ /** 2025-11-25 and earlier; replaced by -32602 in 2026-07-28. */
28
+ export declare const ERROR_LEGACY_RESOURCE_NOT_FOUND = -32002;
29
+ /** Tool catalogue is fixed for the life of a stdio process; five minutes is a conservative hint. */
30
+ export declare const TOOLS_LIST_TTL_MS = 300000;
31
+ export declare const DISCOVER_TTL_MS = 3600000;
32
+ export interface ServerIdentity {
33
+ name: string;
34
+ version: string;
35
+ }
36
+ export interface ProtocolContext {
37
+ /** True when the request used 2026-07-28 per-request metadata. */
38
+ modern: boolean;
39
+ /** Version the request declared, or undefined for legacy requests. */
40
+ version?: string;
41
+ /** Validated W3C traceparent, if the client propagated one. */
42
+ traceparent?: string;
43
+ tracestate?: string;
44
+ }
45
+ export interface JsonRpcMessage {
46
+ jsonrpc?: string;
47
+ id?: string | number | null;
48
+ method?: string;
49
+ params?: unknown;
50
+ }
51
+ export interface JsonRpcResponse {
52
+ jsonrpc: '2.0';
53
+ id?: string | number | null;
54
+ result?: Record<string, unknown>;
55
+ error?: {
56
+ code: number;
57
+ message: string;
58
+ data?: unknown;
59
+ };
60
+ }
61
+ export type Preflight = {
62
+ response: JsonRpcResponse;
63
+ context?: undefined;
64
+ } | {
65
+ response?: undefined;
66
+ context: ProtocolContext;
67
+ };
68
+ /** The CLI package version, read once from package.json (dist/src/ → ../../). */
69
+ export declare function rufloPackageVersion(): string;
70
+ export declare function defaultServerIdentity(): ServerIdentity;
71
+ /** Pick the legacy version to answer `initialize` with (spec: echo if supported, else our latest). */
72
+ export declare function negotiateLegacyVersion(requested: unknown): string;
73
+ export declare function isValidTraceparent(value: unknown): value is string;
74
+ /**
75
+ * Decide how to serve one inbound message before the handler's own switch runs.
76
+ * Returns a complete response for `initialize`, `server/discover` and protocol
77
+ * errors; otherwise returns the context the handler passes to `finalizeResponse`.
78
+ */
79
+ export declare function protocolPreflight(message: JsonRpcMessage, capabilities: Record<string, unknown>, identity?: ServerIdentity): Preflight;
80
+ /** The resource-not-found code the request's revision expects. */
81
+ export declare function resourceNotFoundCode(context: ProtocolContext): number;
82
+ /** Stable, name-ordered copy so `tools/list` is byte-identical across calls (prompt-cache friendly). */
83
+ export declare function sortToolsDeterministically<T extends {
84
+ name: string;
85
+ }>(tools: readonly T[]): T[];
86
+ /** Tool-call context fields to forward, so handlers and logs can join the caller's trace. */
87
+ export declare function traceContextFields(context: ProtocolContext): Record<string, string>;
88
+ /** Add the 2026-07-28 result fields to a handler's response. Legacy responses pass through untouched. */
89
+ export declare function finalizeResponse(response: JsonRpcResponse | null, method: string | undefined, context: ProtocolContext, identity?: ServerIdentity): JsonRpcResponse | null;
90
+ //# sourceMappingURL=mcp-protocol.d.ts.map
@@ -0,0 +1,179 @@
1
+ /**
2
+ * MCP protocol-version handling for the stdio servers (ADR-524).
3
+ *
4
+ * Ruflo ships three stdio entry points (`bin/cli.js` auto-detect, `bin/mcp-server.js`,
5
+ * and `MCPServerManager` in mcp-server.ts). All three answered `initialize` with a
6
+ * hardcoded `2024-11-05` and knew nothing of the 2026-07-28 revision, which drops the
7
+ * handshake and carries the version on every request. This module is the one place
8
+ * that decides which revision a message speaks, so the three handlers cannot drift.
9
+ *
10
+ * Dual-era behaviour (spec: basic/versioning):
11
+ * - `initialize` selects legacy semantics; the requested legacy version is echoed.
12
+ * - a request carrying `_meta["io.modelcontextprotocol/protocolVersion"]` is served
13
+ * statelessly: `resultType` and `serverInfo` on every result, cache hints on lists,
14
+ * `-32602` for an unknown resource, `-32022` for an unsupported version.
15
+ * - `server/discover` is always answered, so a dual-era client's stdio probe succeeds.
16
+ */
17
+ import { readFileSync } from 'node:fs';
18
+ export const MODERN_PROTOCOL_VERSIONS = ['2026-07-28'];
19
+ // 2025-03-26 is deliberately absent: it is the one revision that allowed JSON-RPC batching, which these
20
+ // line-at-a-time handlers do not accept. A client asking for it is offered 2025-11-25 instead.
21
+ export const LEGACY_PROTOCOL_VERSIONS = ['2025-11-25', '2025-06-18', '2024-11-05'];
22
+ export const SUPPORTED_PROTOCOL_VERSIONS = [
23
+ ...MODERN_PROTOCOL_VERSIONS,
24
+ ...LEGACY_PROTOCOL_VERSIONS,
25
+ ];
26
+ /** Offered to a legacy client whose requested version we do not know. */
27
+ export const LATEST_LEGACY_PROTOCOL_VERSION = LEGACY_PROTOCOL_VERSIONS[0];
28
+ export const META_PROTOCOL_VERSION = 'io.modelcontextprotocol/protocolVersion';
29
+ export const META_CLIENT_CAPABILITIES = 'io.modelcontextprotocol/clientCapabilities';
30
+ export const META_SERVER_INFO = 'io.modelcontextprotocol/serverInfo';
31
+ export const ERROR_INVALID_PARAMS = -32602;
32
+ export const ERROR_UNSUPPORTED_PROTOCOL_VERSION = -32022;
33
+ /** 2025-11-25 and earlier; replaced by -32602 in 2026-07-28. */
34
+ export const ERROR_LEGACY_RESOURCE_NOT_FOUND = -32002;
35
+ /** Tool catalogue is fixed for the life of a stdio process; five minutes is a conservative hint. */
36
+ export const TOOLS_LIST_TTL_MS = 300_000;
37
+ export const DISCOVER_TTL_MS = 3_600_000;
38
+ const LIST_METHODS = new Set(['tools/list', 'prompts/list', 'resources/list', 'resources/templates/list']);
39
+ // W3C Trace Context: version-traceid-parentid-flags, lowercase hex, ids not all zero, version != ff.
40
+ const TRACEPARENT = /^([0-9a-f]{2})-([0-9a-f]{32})-([0-9a-f]{16})-([0-9a-f]{2})$/;
41
+ let cachedVersion;
42
+ /** The CLI package version, read once from package.json (dist/src/ → ../../). */
43
+ export function rufloPackageVersion() {
44
+ if (cachedVersion)
45
+ return cachedVersion;
46
+ for (const rel of ['../../package.json', '../package.json']) {
47
+ try {
48
+ const pkg = JSON.parse(readFileSync(new URL(rel, import.meta.url), 'utf8'));
49
+ if (pkg.name === '@claude-flow/cli' && typeof pkg.version === 'string') {
50
+ cachedVersion = pkg.version;
51
+ return cachedVersion;
52
+ }
53
+ }
54
+ catch {
55
+ // try the next candidate
56
+ }
57
+ }
58
+ cachedVersion = '0.0.0';
59
+ return cachedVersion;
60
+ }
61
+ export function defaultServerIdentity() {
62
+ return { name: 'ruflo', version: rufloPackageVersion() };
63
+ }
64
+ /** Pick the legacy version to answer `initialize` with (spec: echo if supported, else our latest). */
65
+ export function negotiateLegacyVersion(requested) {
66
+ return typeof requested === 'string' && LEGACY_PROTOCOL_VERSIONS.includes(requested)
67
+ ? requested
68
+ : LATEST_LEGACY_PROTOCOL_VERSION;
69
+ }
70
+ export function isValidTraceparent(value) {
71
+ if (typeof value !== 'string')
72
+ return false;
73
+ const m = TRACEPARENT.exec(value);
74
+ if (!m)
75
+ return false;
76
+ const [, version, traceId, parentId] = m;
77
+ return version !== 'ff' && !/^0+$/.test(traceId) && !/^0+$/.test(parentId);
78
+ }
79
+ function metaOf(params) {
80
+ if (!params || typeof params !== 'object')
81
+ return undefined;
82
+ const meta = params._meta;
83
+ return meta && typeof meta === 'object' && !Array.isArray(meta) ? meta : undefined;
84
+ }
85
+ function error(id, code, message, data) {
86
+ return { jsonrpc: '2.0', id: id ?? null, error: data === undefined ? { code, message } : { code, message, data } };
87
+ }
88
+ /**
89
+ * Decide how to serve one inbound message before the handler's own switch runs.
90
+ * Returns a complete response for `initialize`, `server/discover` and protocol
91
+ * errors; otherwise returns the context the handler passes to `finalizeResponse`.
92
+ */
93
+ export function protocolPreflight(message, capabilities, identity = defaultServerIdentity()) {
94
+ const meta = metaOf(message.params);
95
+ const traceparent = isValidTraceparent(meta?.traceparent) ? meta.traceparent : undefined;
96
+ const tracestate = traceparent && typeof meta?.tracestate === 'string' && meta.tracestate.length <= 512
97
+ ? meta.tracestate
98
+ : undefined;
99
+ const declared = meta?.[META_PROTOCOL_VERSION];
100
+ const isNotification = message.id === undefined || message.id === null;
101
+ if (message.method === 'initialize') {
102
+ const requested = message.params?.protocolVersion;
103
+ return {
104
+ response: {
105
+ jsonrpc: '2.0',
106
+ id: message.id,
107
+ result: { protocolVersion: negotiateLegacyVersion(requested), serverInfo: identity, capabilities },
108
+ },
109
+ };
110
+ }
111
+ if (declared !== undefined && !isNotification) {
112
+ if (typeof declared !== 'string' || !SUPPORTED_PROTOCOL_VERSIONS.includes(declared)) {
113
+ return {
114
+ response: error(message.id, ERROR_UNSUPPORTED_PROTOCOL_VERSION, 'Unsupported protocol version', {
115
+ supported: [...SUPPORTED_PROTOCOL_VERSIONS],
116
+ requested: declared,
117
+ }),
118
+ };
119
+ }
120
+ const modern = MODERN_PROTOCOL_VERSIONS.includes(declared);
121
+ if (modern) {
122
+ const caps = meta?.[META_CLIENT_CAPABILITIES];
123
+ if (message.method !== 'server/discover' && (!caps || typeof caps !== 'object' || Array.isArray(caps))) {
124
+ return { response: error(message.id, ERROR_INVALID_PARAMS, `Missing required _meta field: ${META_CLIENT_CAPABILITIES}`) };
125
+ }
126
+ }
127
+ if (message.method === 'server/discover')
128
+ return { response: discoverResponse(message.id, capabilities, identity) };
129
+ return { context: { modern, version: declared, traceparent, tracestate } };
130
+ }
131
+ if (message.method === 'server/discover')
132
+ return { response: discoverResponse(message.id, capabilities, identity) };
133
+ return { context: { modern: false, traceparent, tracestate } };
134
+ }
135
+ function discoverResponse(id, capabilities, identity) {
136
+ return {
137
+ jsonrpc: '2.0',
138
+ id,
139
+ result: {
140
+ resultType: 'complete',
141
+ supportedVersions: [...SUPPORTED_PROTOCOL_VERSIONS],
142
+ capabilities,
143
+ _meta: { [META_SERVER_INFO]: identity },
144
+ ttlMs: DISCOVER_TTL_MS,
145
+ cacheScope: 'private',
146
+ },
147
+ };
148
+ }
149
+ /** The resource-not-found code the request's revision expects. */
150
+ export function resourceNotFoundCode(context) {
151
+ return context.modern ? ERROR_INVALID_PARAMS : ERROR_LEGACY_RESOURCE_NOT_FOUND;
152
+ }
153
+ /** Stable, name-ordered copy so `tools/list` is byte-identical across calls (prompt-cache friendly). */
154
+ export function sortToolsDeterministically(tools) {
155
+ return [...tools].sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0));
156
+ }
157
+ /** Tool-call context fields to forward, so handlers and logs can join the caller's trace. */
158
+ export function traceContextFields(context) {
159
+ const out = {};
160
+ if (context.traceparent)
161
+ out.traceparent = context.traceparent;
162
+ if (context.tracestate)
163
+ out.tracestate = context.tracestate;
164
+ return out;
165
+ }
166
+ /** Add the 2026-07-28 result fields to a handler's response. Legacy responses pass through untouched. */
167
+ export function finalizeResponse(response, method, context, identity = defaultServerIdentity()) {
168
+ if (!response || !context.modern || !response.result)
169
+ return response;
170
+ const result = { resultType: 'complete', ...response.result };
171
+ const priorMeta = result._meta && typeof result._meta === 'object' ? result._meta : {};
172
+ result._meta = { ...priorMeta, [META_SERVER_INFO]: identity };
173
+ if (method && LIST_METHODS.has(method)) {
174
+ result.ttlMs = TOOLS_LIST_TTL_MS;
175
+ result.cacheScope = 'private';
176
+ }
177
+ return { ...response, result };
178
+ }
179
+ //# sourceMappingURL=mcp-protocol.js.map
@@ -182,6 +182,7 @@ export declare class MCPServerManager extends EventEmitter {
182
182
  * Handle incoming MCP message
183
183
  */
184
184
  private handleMCPMessage;
185
+ private dispatchMCPMessage;
185
186
  /**
186
187
  * Start HTTP server in-process
187
188
  */
@@ -26,6 +26,7 @@ import * as os from 'os';
26
26
  import { fileURLToPath } from 'url';
27
27
  import { dirname } from 'path';
28
28
  import { trackRequest } from './mcp-tools/request-tracker.js';
29
+ import { defaultServerIdentity, finalizeResponse, protocolPreflight, resourceNotFoundCode, sortToolsDeterministically, traceContextFields, } from './mcp-protocol.js';
29
30
  import { isPolicyEnforcementEnabled, loadMcpPolicy, evaluateToolCall, } from './mcp-tools/policy-enforcer.js';
30
31
  /** A failed task can be valid data; only an explicit error denotes tool failure. */
31
32
  function hasToolError(result) {
@@ -275,6 +276,11 @@ export function assessMcpSchemaOverhead(tools, contextWindowTokens) {
275
276
  : 'normal',
276
277
  };
277
278
  }
279
+ /** Capabilities every ruflo stdio server advertises (initialize and server/discover). */
280
+ const MCP_STDIO_CAPABILITIES = {
281
+ tools: { listChanged: true },
282
+ resources: {},
283
+ };
278
284
  /**
279
285
  * MCP Server Manager
280
286
  *
@@ -616,7 +622,7 @@ export class MCPServerManager extends EventEmitter {
616
622
  });
617
623
  // Import the tool registry
618
624
  const { listMCPTools, callMCPTool, hasTool } = await import('./mcp-client.js');
619
- const VERSION = '3.0.0';
625
+ const VERSION = defaultServerIdentity().version;
620
626
  const sessionId = `mcp-${Date.now()}-${randomUUID().slice(0, 8)}`;
621
627
  // Log to stderr to not corrupt stdout
622
628
  console.error(`[${new Date().toISOString()}] INFO [claude-flow-mcp] (${sessionId}) Starting in stdio mode`);
@@ -663,10 +669,7 @@ export class MCPServerManager extends EventEmitter {
663
669
  serverInfo: {
664
670
  name: 'ruflo',
665
671
  version: VERSION,
666
- capabilities: {
667
- tools: { listChanged: true },
668
- resources: {},
669
- },
672
+ capabilities: MCP_STDIO_CAPABILITIES,
670
673
  },
671
674
  },
672
675
  });
@@ -722,7 +725,6 @@ export class MCPServerManager extends EventEmitter {
722
725
  * Handle incoming MCP message
723
726
  */
724
727
  async handleMCPMessage(message, sessionId) {
725
- const { listMCPTools, callMCPTool, hasTool } = await import('./mcp-client.js');
726
728
  if (!message.method) {
727
729
  return {
728
730
  jsonrpc: '2.0',
@@ -730,24 +732,20 @@ export class MCPServerManager extends EventEmitter {
730
732
  error: { code: -32600, message: 'Invalid Request: missing method' },
731
733
  };
732
734
  }
735
+ // ADR-524: one decision point for which MCP revision this message speaks.
736
+ const preflight = protocolPreflight(message, MCP_STDIO_CAPABILITIES);
737
+ if (preflight.response)
738
+ return preflight.response;
739
+ const response = await this.dispatchMCPMessage(message, sessionId, preflight.context);
740
+ return finalizeResponse(response, message.method, preflight.context);
741
+ }
742
+ async dispatchMCPMessage(message, sessionId, protocol) {
743
+ const { listMCPTools, callMCPTool, hasTool } = await import('./mcp-client.js');
733
744
  const params = (message.params || {});
734
745
  try {
735
746
  switch (message.method) {
736
- case 'initialize':
737
- return {
738
- jsonrpc: '2.0',
739
- id: message.id,
740
- result: {
741
- protocolVersion: '2024-11-05',
742
- serverInfo: { name: 'ruflo', version: '3.0.0' },
743
- capabilities: {
744
- tools: { listChanged: true },
745
- resources: {},
746
- },
747
- },
748
- };
749
747
  case 'tools/list':
750
- const tools = filterAdvertisedMcpTools(listMCPTools(), this.options.tools);
748
+ const tools = sortToolsDeterministically(filterAdvertisedMcpTools(listMCPTools(), this.options.tools));
751
749
  return {
752
750
  jsonrpc: '2.0',
753
751
  id: message.id,
@@ -781,7 +779,7 @@ export class MCPServerManager extends EventEmitter {
781
779
  }
782
780
  }
783
781
  try {
784
- const result = await callMCPTool(toolName, toolParams, { sessionId, transport: 'stdio' });
782
+ const result = await callMCPTool(toolName, toolParams, { sessionId, transport: 'stdio', ...traceContextFields(protocol) });
785
783
  const isError = hasToolError(result);
786
784
  trackRequest(toolName, !isError);
787
785
  return {
@@ -808,7 +806,7 @@ export class MCPServerManager extends EventEmitter {
808
806
  case 'resources/templates/list':
809
807
  return { jsonrpc: '2.0', id: message.id, result: { resourceTemplates: [] } };
810
808
  case 'resources/read':
811
- return { jsonrpc: '2.0', id: message.id, error: { code: -32002, message: 'Resource not found' } };
809
+ return { jsonrpc: '2.0', id: message.id, error: { code: resourceNotFoundCode(protocol), message: 'Resource not found' } };
812
810
  case 'notifications/initialized':
813
811
  // Client notification - no response needed
814
812
  console.error(`[${new Date().toISOString()}] INFO [claude-flow-mcp] (${sessionId}) Client initialized`);
@@ -147,10 +147,18 @@ export async function callAnthropicMessages(input) {
147
147
  // checked in that order — matching callOllamaCompat's own precedence).
148
148
  const resolvedBaseUrl = process.env.OLLAMA_BASE_URL || persistedOllama?.baseUrl;
149
149
  const isSelfHosted = !!resolvedBaseUrl && !/^https:\/\/ollama\.com\/?$/i.test(resolvedBaseUrl);
150
+ // The persisted baseUrl comes from project config, which a cloned repo
151
+ // can commit. Never hand the environment's OLLAMA_API_KEY to an endpoint
152
+ // the project chose: that endpoint gets only the key saved beside it (or
153
+ // none). The env key goes to OLLAMA_BASE_URL, or to Ollama Cloud itself.
154
+ const baseFromProject = !process.env.OLLAMA_BASE_URL && !!persistedOllama?.baseUrl && isSelfHosted;
155
+ const apiKey = baseFromProject
156
+ ? persistedOllama?.apiKey || 'local'
157
+ : ollamaKey || persistedOllama?.apiKey || 'local';
150
158
  if (ollamaKey || persistedOllama?.apiKey || isSelfHosted) {
151
159
  return callOllamaCompat({
152
160
  ...input,
153
- apiKey: ollamaKey || persistedOllama?.apiKey || 'local',
161
+ apiKey,
154
162
  baseUrl: resolvedBaseUrl,
155
163
  model: input.model,
156
164
  // Local default for tier aliases / Anthropic ids (see
@@ -5,5 +5,18 @@
5
5
  * Includes model routing integration for intelligent model selection.
6
6
  */
7
7
  import { type MCPTool } from './types.js';
8
+ /** Live canonical registry members, excluding stale or duplicate swarm IDs. */
9
+ export declare function getLiveAgentIds(agentIds: string[]): string[];
10
+ export declare const AGENT_STATUSES: readonly ["idle", "busy", "terminated"];
11
+ type AgentLifecycleStatus = (typeof AGENT_STATUSES)[number];
12
+ /** Canonical lifecycle status (trimmed, any case, known aliases), or null. */
13
+ export declare function agentStatusOf(value: unknown): AgentLifecycleStatus | null;
14
+ /**
15
+ * Statuses `agent_list` should keep. `null` means no status filter:
16
+ * omitted, empty, whitespace, or `all` (any case, including inside a comma list).
17
+ * The caller still hides terminated agents unless includeTerminated is set.
18
+ */
19
+ export declare function agentListStatusFilter(status: unknown): string[] | null;
8
20
  export declare const agentTools: MCPTool[];
21
+ export {};
9
22
  //# sourceMappingURL=agent-tools.d.ts.map