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
@@ -36,6 +36,11 @@ function ensureAgentDir() {
36
36
  function loadAgentStore() {
37
37
  return readRecordStore(getAgentPath(), 'agents', () => ({ agents: {}, version: '3.0.0' }));
38
38
  }
39
+ /** Live canonical registry members, excluding stale or duplicate swarm IDs. */
40
+ export function getLiveAgentIds(agentIds) {
41
+ const { agents } = loadAgentStore();
42
+ return [...new Set(agentIds)].filter(id => agents[id] && agents[id].status !== 'terminated');
43
+ }
39
44
  function saveAgentStore(store) {
40
45
  ensureAgentDir();
41
46
  writeFileSync(getAgentPath(), JSON.stringify(store, null, 2), 'utf-8');
@@ -67,6 +72,40 @@ function loadHiveAgents() {
67
72
  function loadAllAgents() {
68
73
  return Object.assign(nullPrototypeRecords(undefined), loadHiveAgents(), loadAgentStore().agents);
69
74
  }
75
+ export const AGENT_STATUSES = ['idle', 'busy', 'terminated'];
76
+ // Spellings callers write for the three stored states. v2 `agent/list` used
77
+ // "active" for a working agent; hive liveness folds running/working into busy.
78
+ const AGENT_STATUS_ALIASES = {
79
+ active: 'busy', running: 'busy', working: 'busy',
80
+ ready: 'idle', waiting: 'idle',
81
+ stopped: 'terminated', inactive: 'terminated', offline: 'terminated',
82
+ };
83
+ /** Canonical lifecycle status (trimmed, any case, known aliases), or null. */
84
+ export function agentStatusOf(value) {
85
+ if (typeof value !== 'string')
86
+ return null;
87
+ const key = value.trim().toLowerCase();
88
+ if (AGENT_STATUSES.includes(key))
89
+ return key;
90
+ return Object.hasOwn(AGENT_STATUS_ALIASES, key) ? AGENT_STATUS_ALIASES[key] : null;
91
+ }
92
+ /**
93
+ * Statuses `agent_list` should keep. `null` means no status filter:
94
+ * omitted, empty, whitespace, or `all` (any case, including inside a comma list).
95
+ * The caller still hides terminated agents unless includeTerminated is set.
96
+ */
97
+ export function agentListStatusFilter(status) {
98
+ if (typeof status !== 'string' || status.trim() === '')
99
+ return null;
100
+ const canonical = status.split(',').map(part => part.trim()).filter(Boolean).map(part => {
101
+ if (part.toLowerCase() === 'all')
102
+ return 'all';
103
+ return agentStatusOf(part) ?? part.toLowerCase();
104
+ });
105
+ if (canonical.length === 0 || canonical.includes('all'))
106
+ return null;
107
+ return canonical;
108
+ }
70
109
  // Default model mappings for agent types (can be overridden)
71
110
  const AGENT_TYPE_MODEL_DEFAULTS = {
72
111
  // Complex agents → opus
@@ -568,17 +607,24 @@ export const agentTools = [
568
607
  inputSchema: {
569
608
  type: 'object',
570
609
  properties: {
571
- status: { type: 'string', description: 'Filter by status' },
610
+ status: { type: 'string', description: 'Filter by status (idle, busy, terminated; case-insensitive, aliases such as active/running/stopped). "all" or empty applies no status filter. Comma-separated values match any of them.' },
572
611
  domain: { type: 'string', description: 'Filter by domain' },
573
612
  agentType: { type: 'string', description: 'Filter by agent type' },
574
613
  includeTerminated: { type: 'boolean', description: 'Include terminated agents' },
575
614
  },
576
615
  },
577
616
  handler: async (input) => {
578
- if (input.status) {
579
- const v = validateIdentifier(input.status, 'status');
580
- if (!v.valid)
581
- return { agents: [], total: 0, error: `Input validation failed: ${v.error}` };
617
+ // Validate each status token. Commas separate values (`active,idle`);
618
+ // the whole string is not one identifier.
619
+ if (typeof input.status === 'string' && input.status.trim() !== '') {
620
+ for (const part of input.status.split(',')) {
621
+ const token = part.trim();
622
+ if (!token || token.toLowerCase() === 'all')
623
+ continue;
624
+ const v = validateIdentifier(token, 'status');
625
+ if (!v.valid)
626
+ return { agents: [], total: 0, error: `Input validation failed: ${v.error}` };
627
+ }
582
628
  }
583
629
  if (input.domain) {
584
630
  const v = validateIdentifier(input.domain, 'domain');
@@ -591,9 +637,14 @@ export const agentTools = [
591
637
  return { agents: [], total: 0, error: `Input validation failed: ${v.error}` };
592
638
  }
593
639
  let agents = Object.values(loadAllAgents()); // #1916: includes hive-mind-spawned workers
594
- // Filter by status
595
- if (input.status) {
596
- agents = agents.filter(a => a.status === input.status);
640
+ // Filter by status. `all` and empty mean no status filter (#4732),
641
+ // matching task_list: comma-separated, case-insensitive, known aliases.
642
+ const statuses = agentListStatusFilter(input.status);
643
+ if (statuses) {
644
+ agents = agents.filter(a => {
645
+ const stored = agentStatusOf(a.status) ?? String(a.status).trim().toLowerCase();
646
+ return statuses.includes(stored);
647
+ });
597
648
  }
598
649
  else if (!input.includeTerminated) {
599
650
  agents = agents.filter(a => a.status !== 'terminated');
@@ -1502,6 +1502,8 @@ export const agentdbGraphPathfinder = {
1502
1502
  }
1503
1503
  const edges = rawEdges;
1504
1504
  let paths = [];
1505
+ let mincutInfo;
1506
+ let approximation;
1505
1507
  // Check millisecond budget before heavy computation
1506
1508
  if (Date.now() - t0 > budget.maxMillis) {
1507
1509
  return { success: true, paths: [], count: 0, message: `complexityBudget.maxMillis (${budget.maxMillis}ms) exceeded before solver dispatch`, seedNodeId, algorithm, elapsedMs: Date.now() - t0 };
@@ -1557,10 +1559,38 @@ export const agentdbGraphPathfinder = {
1557
1559
  paths = witnessChain.slice(0, topK);
1558
1560
  break;
1559
1561
  }
1562
+ case 'dynamic-mincut': {
1563
+ // Exact minimum cut of the seed's depth-hop neighbourhood: the
1564
+ // weakest boundary around the seed, and the nodes on its side of it.
1565
+ // Wasm solver via ruvector (@ruvector/mincut-wasm), JS Stoer-Wagner
1566
+ // fallback for small neighbourhoods.
1567
+ const edgeTuples = edges.map(r => [String(r[0]), String(r[1]), Number(r[2]) || 1.0]);
1568
+ const { seedLocalMinCut } = await import('../ruvector/mincut-bridge.js');
1569
+ const { fallbackMinCut } = await import('../ruvector/graph-analyzer.js');
1570
+ const cut = await seedLocalMinCut(seedNodeId, edgeTuples, depth, budget.maxNodesVisited, fallbackMinCut);
1571
+ if (!cut) {
1572
+ mincutInfo = { backend: 'none', message: 'seed neighbourhood too large for the JS fallback and the wasm solver is unavailable (install ruvector)' };
1573
+ break;
1574
+ }
1575
+ paths = cut.seedSide
1576
+ .map(r => ({ nodeId: r.nodeId, score: 1 / (1 + r.depth), depth: r.depth }))
1577
+ .filter(r => r.score >= threshold)
1578
+ .slice(0, topK);
1579
+ mincutInfo = {
1580
+ backend: cut.backend,
1581
+ cutValue: cut.cutValue,
1582
+ seedSideSize: cut.seedSide.length + 1,
1583
+ otherSideSize: cut.otherSide.length,
1584
+ subgraphNodes: cut.subgraphNodes,
1585
+ cutEdges: cut.cutEdges.slice(0, 50),
1586
+ };
1587
+ break;
1588
+ }
1560
1589
  case 'connected-component-churn':
1561
- case 'dynamic-mincut':
1562
1590
  case 'spectral-sparsify': {
1563
- // Simplified implementations: return k-hop neighbors with basic score
1591
+ // Not implemented natively yet: approximated by k-hop neighbours with
1592
+ // a rank-decay score. The response says so via `implementation`.
1593
+ approximation = 'k-hop';
1564
1594
  const edgeTuples = edges.map(r => [r[0], r[1], Number(r[2]) || 1.0]);
1565
1595
  const khopResult = await agentdbGraphQuery.handler({
1566
1596
  nodeId: seedNodeId, mode: 'k-hop', depth, complexityBudget: budget,
@@ -1582,6 +1612,8 @@ export const agentdbGraphPathfinder = {
1582
1612
  count: paths.length,
1583
1613
  elapsedMs,
1584
1614
  budgetUsed: { millis: elapsedMs, nodes: rawEdges.length },
1615
+ ...(mincutInfo && { mincut: mincutInfo }),
1616
+ ...(approximation && { implementation: `${approximation} approximation` }),
1585
1617
  ...(depthWarning && { warning: depthWarning }),
1586
1618
  };
1587
1619
  }
@@ -15,4 +15,13 @@ export declare function launchArgsError(value: unknown): string | null;
15
15
  * pass — for example a selector or typed text of "--executable-path".
16
16
  */
17
17
  export declare function commandArgvError(args: readonly string[]): string | null;
18
+ /**
19
+ * Returns an error when a navigation target is not a web page. The browser
20
+ * tools return page text to the caller, so a `file:` URL (or `view-source:`,
21
+ * `chrome:`, `data:` and the like) would read local files or browser state
22
+ * that `http_fetch` never serves. Only http(s) URLs, `about:blank`, and
23
+ * scheme-less targets such as `example.com/path` or `localhost:3000` (which
24
+ * agent-browser opens over http(s)) are accepted.
25
+ */
26
+ export declare function browserUrlError(value: unknown): string | null;
18
27
  //# sourceMappingURL=browser-argv.d.ts.map
@@ -42,6 +42,11 @@ export function launchArgsError(value) {
42
42
  * pass — for example a selector or typed text of "--executable-path".
43
43
  */
44
44
  export function commandArgvError(args) {
45
+ if (args[0] === 'open') {
46
+ const urlError = browserUrlError(args[1]);
47
+ if (urlError)
48
+ return urlError;
49
+ }
45
50
  for (const arg of args) {
46
51
  if (typeof arg !== 'string')
47
52
  return 'browser command arguments must be strings';
@@ -56,4 +61,32 @@ export function commandArgvError(args) {
56
61
  }
57
62
  return null;
58
63
  }
64
+ /**
65
+ * Returns an error when a navigation target is not a web page. The browser
66
+ * tools return page text to the caller, so a `file:` URL (or `view-source:`,
67
+ * `chrome:`, `data:` and the like) would read local files or browser state
68
+ * that `http_fetch` never serves. Only http(s) URLs, `about:blank`, and
69
+ * scheme-less targets such as `example.com/path` or `localhost:3000` (which
70
+ * agent-browser opens over http(s)) are accepted.
71
+ */
72
+ export function browserUrlError(value) {
73
+ if (typeof value !== 'string' || !value.trim())
74
+ return 'url must be a non-empty string';
75
+ // Chromium drops tabs and newlines anywhere in a URL and trims leading
76
+ // control characters and spaces, so check what it would actually parse.
77
+ const url = value.replace(/[\t\n\r]/g, '').replace(/^[\u0000- ]+/, '');
78
+ const scheme = /^([a-z][a-z0-9+.-]*):/i.exec(url);
79
+ if (!scheme)
80
+ return null;
81
+ const name = scheme[1].toLowerCase();
82
+ if (name === 'http' || name === 'https')
83
+ return null;
84
+ if (url.toLowerCase() === 'about:blank')
85
+ return null;
86
+ // `host:port` with no scheme, e.g. `localhost:3000/app`. The host must be
87
+ // `localhost` or contain a dot, so `file:1/...` is not mistaken for one.
88
+ if ((name === 'localhost' || name.includes('.')) && /^[a-z0-9.-]+:\d{1,5}(?:[/?#]|$)/i.test(url))
89
+ return null;
90
+ return `url scheme not allowed: ${JSON.stringify(name.slice(0, 40))} (use http or https)`;
91
+ }
59
92
  //# sourceMappingURL=browser-argv.js.map
@@ -22,6 +22,7 @@
22
22
  * rather than a process crash.
23
23
  */
24
24
  import { validateIdentifier, validateText } from './validate-input.js';
25
+ import { browserUrlError } from './browser-argv.js';
25
26
  // Pin matches the version in this package's own dependency tree so the npx
26
27
  // fallback never downloads a second ruvector. Subcommand surface verified
27
28
  // against ruvector@0.2.27 --help: `rvf create/compact/status/derive/segments`
@@ -144,6 +145,9 @@ export const browserSessionTools = [
144
145
  const vUrl = validateText(input.url, 'url');
145
146
  if (!vUrl.valid)
146
147
  return fail(vUrl.error || 'invalid url');
148
+ const urlError = browserUrlError(input.url);
149
+ if (urlError)
150
+ return fail(urlError);
147
151
  const vTask = validateText(input.task, 'task');
148
152
  if (!vTask.valid)
149
153
  return fail(vTask.error || 'invalid task');
@@ -8,6 +8,8 @@ import { readFileSync, existsSync } from 'node:fs';
8
8
  import { validateIdentifier, validateText } from './validate-input.js';
9
9
  import { resolveAgentBrowserLaunch, resolveNpxLaunch } from '../runtime/browser-command.js';
10
10
  import { commandArgvError, launchArgsError } from './browser-argv.js';
11
+ import { containedWritePath } from './path-containment.js';
12
+ const SCREENSHOT_EXTENSIONS = ['.png', '.jpg', '.jpeg'];
11
13
  // Session registry for multi-session support
12
14
  const browserSessions = new Map();
13
15
  /** Preserve agent-browser's JSON error on non-zero exit without echoing other process output. */
@@ -324,8 +326,16 @@ export const browserTools = [
324
326
  }
325
327
  const { session, path, fullPage } = input;
326
328
  const args = ['screenshot'];
327
- if (path)
328
- args.push(path);
329
+ if (path) {
330
+ // The browser writes the image wherever it is told and replaces what
331
+ // is there, so a caller-named path must stay inside the project.
332
+ const target = containedWritePath(path, SCREENSHOT_EXTENSIONS);
333
+ if (!target) {
334
+ const error = `path must be a new or regular file inside the project ending in ${SCREENSHOT_EXTENSIONS.join(', ')}`;
335
+ return { content: [{ type: 'text', text: JSON.stringify({ success: false, error }) }], isError: true };
336
+ }
337
+ args.push(target);
338
+ }
329
339
  if (fullPage)
330
340
  args.push('--full');
331
341
  return execBrowserCommand(args, session);
@@ -346,11 +346,12 @@ export const coordinationTools = [
346
346
  }
347
347
  if (action === 'heartbeat') {
348
348
  const nodeId = input.nodeId;
349
- if (store.nodes[nodeId]) {
350
- store.nodes[nodeId].lastHeartbeat = new Date().toISOString();
351
- store.nodes[nodeId].status = 'active';
352
- saveCoordStore(store);
349
+ if (!store.nodes[nodeId]) {
350
+ return { success: false, error: 'Node not found' };
353
351
  }
352
+ store.nodes[nodeId].lastHeartbeat = new Date().toISOString();
353
+ store.nodes[nodeId].status = 'active';
354
+ saveCoordStore(store);
354
355
  return {
355
356
  success: true,
356
357
  action: 'heartbeat',
@@ -50,11 +50,14 @@ async function getRealEmbeddingFunction() {
50
50
  }
51
51
  return realEmbeddingFn;
52
52
  }
53
- async function generateRealEmbedding(text, dimension) {
53
+ async function generateRealEmbedding(text, dimension, normalize = true) {
54
54
  const realFn = await getRealEmbeddingFunction();
55
55
  if (realFn) {
56
56
  try {
57
- const result = await realFn(text);
57
+ // Default callers stay a single-argument call so existing mocks and
58
+ // the unit-norm path are unchanged. Only an explicit opt-out asks the
59
+ // generator for the pre-L2 vector.
60
+ const result = normalize ? await realFn(text) : await realFn(text, { normalize: false });
58
61
  return {
59
62
  embedding: result.embedding,
60
63
  backend: result.backend ?? 'onnx',
@@ -76,7 +79,10 @@ async function generateRealEmbedding(text, dimension) {
76
79
  const seed = hash + i * 1337;
77
80
  embedding.push(Math.sin(seed) * Math.cos(seed * 0.5));
78
81
  }
79
- // L2 normalize
82
+ // L2 normalize unless the caller opted out (#4724).
83
+ if (!normalize) {
84
+ return { embedding, backend: 'mock', model: 'hash-fallback' };
85
+ }
80
86
  const norm = Math.sqrt(embedding.reduce((sum, x) => sum + x * x, 0));
81
87
  return {
82
88
  embedding: embedding.map(x => x / norm),
@@ -256,8 +262,10 @@ export const embeddingsTools = [
256
262
  return { success: false, error: v.error };
257
263
  }
258
264
  const useHyperbolic = input.hyperbolic === true && config.hyperbolic.enabled;
265
+ // Default true: omitted and explicit true keep the historical unit vector.
266
+ const shouldNormalize = input.normalize !== false;
259
267
  // Generate real ONNX embedding
260
- const generated = await generateRealEmbedding(text, config.dimension);
268
+ const generated = await generateRealEmbedding(text, config.dimension, shouldNormalize);
261
269
  const embedding = generated.embedding;
262
270
  let result;
263
271
  let geometry;
@@ -0,0 +1,4 @@
1
+ import { type MCPTool } from './types.js';
2
+ export declare const hooksFastApply: MCPTool;
3
+ export declare const fastApplyTools: MCPTool[];
4
+ //# sourceMappingURL=fast-apply-tools.d.ts.map
@@ -0,0 +1,85 @@
1
+ /**
2
+ * hooks_fast-apply — merge a code snippet into a file or string with
3
+ * agent-booster (~ms, no LLM). The caller supplies the target code; for
4
+ * deterministic intents with no snippet use hooks_codemod instead.
5
+ */
6
+ import { existsSync, readFileSync, writeFileSync } from 'fs';
7
+ import { resolve, sep } from 'path';
8
+ import { getProjectCwd } from './types.js';
9
+ import { validatePath } from './validate-input.js';
10
+ import { realpathNearest, isInsideRealRoot } from './realpath-containment.js';
11
+ const MAX_INPUT_BYTES = 1_000_000;
12
+ function langForPath(p) {
13
+ const ext = p.slice(p.lastIndexOf('.') + 1).toLowerCase();
14
+ const map = {
15
+ ts: 'typescript', tsx: 'typescript', mts: 'typescript', cts: 'typescript',
16
+ js: 'javascript', jsx: 'javascript', mjs: 'javascript', cjs: 'javascript',
17
+ py: 'python', rs: 'rust', go: 'go', java: 'java', c: 'c', cpp: 'cpp', h: 'c',
18
+ };
19
+ return map[ext];
20
+ }
21
+ export const hooksFastApply = {
22
+ name: 'hooks_fast-apply',
23
+ description: 'Merge an edit SNIPPET (the rewritten code, e.g. a whole new version of one function) into a file or raw code using agent-booster — a local fast-apply engine (~1-10 ms, no LLM, $0). `edit` must be code, not an instruction: "make add typed" fails, "function add(a: number, b: number): number { return a + b; }" works. Use when you already have the replacement code and the surrounding file is large, instead of re-sending the whole file. Deterministic intents (var-to-const, remove-console, add-logging) belong to hooks_codemod. Returns confidence + strategy; below minConfidence nothing is written.',
24
+ inputSchema: {
25
+ type: 'object',
26
+ properties: {
27
+ edit: { type: 'string', description: 'Target code snippet to merge (code, not an instruction)' },
28
+ file: { type: 'string', description: 'Existing file inside the project to patch in place' },
29
+ code: { type: 'string', description: 'Raw source to patch instead of a file (returns output, writes nothing)' },
30
+ language: { type: 'string', description: 'Language hint (inferred from the file extension when omitted)' },
31
+ minConfidence: { type: 'number', description: 'Minimum merge confidence 0-1 required to apply (default 0.5)' },
32
+ dryRun: { type: 'boolean', description: 'Report the merge result without writing the file' },
33
+ },
34
+ required: ['edit'],
35
+ },
36
+ handler: async (params) => {
37
+ const edit = params.edit;
38
+ if (typeof edit !== 'string' || edit.trim() === '')
39
+ return { success: false, error: 'edit (non-empty code snippet) is required' };
40
+ if (edit.length > MAX_INPUT_BYTES)
41
+ return { success: false, error: 'edit too large' };
42
+ const minConfidence = typeof params.minConfidence === 'number'
43
+ ? Math.min(Math.max(params.minConfidence, 0), 1) : 0.5;
44
+ const dryRun = params.dryRun === true;
45
+ const { fastApply } = await import('../ruvector/fast-apply.js');
46
+ if (typeof params.code === 'string') {
47
+ if (params.code.length > MAX_INPUT_BYTES)
48
+ return { success: false, error: 'code too large' };
49
+ const r = await fastApply({ code: params.code, edit, language: params.language, minConfidence });
50
+ return { ...r, mode: 'code', cost: 0 };
51
+ }
52
+ if (typeof params.file !== 'string')
53
+ return { success: false, error: 'Provide `file` or `code`.' };
54
+ const v = validatePath(params.file, 'file');
55
+ if (!v.valid)
56
+ return { success: false, error: v.error };
57
+ const cwd = getProjectCwd();
58
+ const abs = resolve(cwd, v.sanitized);
59
+ if (abs !== cwd && !abs.startsWith(cwd + sep))
60
+ return { success: false, error: `path escapes project root: ${params.file}` };
61
+ let realRoot;
62
+ try {
63
+ realRoot = realpathNearest(cwd);
64
+ }
65
+ catch (err) {
66
+ return { success: false, error: `cannot resolve project root: ${err.message}` };
67
+ }
68
+ if (!isInsideRealRoot(realRoot, abs))
69
+ return { success: false, error: `path escapes project root via symlink: ${params.file}` };
70
+ if (!existsSync(abs))
71
+ return { success: false, error: `file not found: ${params.file}` };
72
+ const before = readFileSync(abs, 'utf-8');
73
+ if (before.length > MAX_INPUT_BYTES)
74
+ return { success: false, error: 'file too large' };
75
+ const language = params.language ?? langForPath(abs);
76
+ const r = await fastApply({ code: before, edit, language, minConfidence });
77
+ const written = r.success && !dryRun;
78
+ if (written)
79
+ writeFileSync(abs, r.output, 'utf-8');
80
+ const { output, ...meta } = r;
81
+ return { ...meta, mode: dryRun ? 'dry-run' : 'file', file: params.file, written, ...(dryRun && { output }), cost: 0 };
82
+ },
83
+ };
84
+ export const fastApplyTools = [hooksFastApply];
85
+ //# sourceMappingURL=fast-apply-tools.js.map
@@ -0,0 +1,6 @@
1
+ /** Bounded glob matching for caller-provided memory-import exclusions. */
2
+ export declare const MAX_EXCLUDE_PATTERNS = 64;
3
+ export declare const MAX_EXCLUDE_PATTERN_LENGTH = 1024;
4
+ export declare const MAX_EXCLUDE_WILDCARDS = 32;
5
+ export declare function compileExclusionPatterns(input: unknown): Array<(path: string) => boolean>;
6
+ //# sourceMappingURL=glob-exclusions.d.ts.map
@@ -0,0 +1,81 @@
1
+ /** Bounded glob matching for caller-provided memory-import exclusions. */
2
+ export const MAX_EXCLUDE_PATTERNS = 64;
3
+ export const MAX_EXCLUDE_PATTERN_LENGTH = 1024;
4
+ export const MAX_EXCLUDE_WILDCARDS = 32;
5
+ function tokenize(pattern) {
6
+ const tokens = [];
7
+ let wildcards = 0;
8
+ for (let i = 0; i < pattern.length; i++) {
9
+ const char = pattern[i];
10
+ if (char === '*') {
11
+ let end = i + 1;
12
+ while (pattern[end] === '*')
13
+ end++;
14
+ tokens.push({ kind: end - i > 1 ? 'globstar' : 'star' });
15
+ // Preserve the trailing segment-star in odd runs, including its newline behavior.
16
+ if (end - i > 1 && (end - i) % 2 === 1) {
17
+ tokens.push({ kind: 'star' });
18
+ wildcards++;
19
+ }
20
+ i = end - 1;
21
+ wildcards++;
22
+ }
23
+ else if (char === '?') {
24
+ tokens.push({ kind: 'question' });
25
+ wildcards++;
26
+ }
27
+ else {
28
+ tokens.push({ kind: 'literal', value: char });
29
+ }
30
+ }
31
+ if (wildcards > MAX_EXCLUDE_WILDCARDS) {
32
+ throw new Error(`excludeFilePatterns entries may contain at most ${MAX_EXCLUDE_WILDCARDS} wildcard operators`);
33
+ }
34
+ return tokens;
35
+ }
36
+ function matches(tokens, path) {
37
+ // Each path character visits each token once; wildcard placement cannot cause backtracking.
38
+ let previous = new Uint8Array(tokens.length + 1);
39
+ let current = new Uint8Array(tokens.length + 1);
40
+ previous[0] = 1;
41
+ for (let j = 1; j <= tokens.length; j++) {
42
+ const token = tokens[j - 1];
43
+ if (token.kind === 'star' || token.kind === 'globstar')
44
+ previous[j] = previous[j - 1];
45
+ }
46
+ for (let i = 0; i < path.length; i++) {
47
+ current[0] = 0;
48
+ const char = path[i];
49
+ const inSegment = char !== '/' && char !== '\\';
50
+ for (let j = 1; j <= tokens.length; j++) {
51
+ const token = tokens[j - 1];
52
+ if (token.kind === 'star' || token.kind === 'globstar') {
53
+ const canConsume = token.kind === 'globstar'
54
+ ? !'\n\r\u2028\u2029'.includes(char)
55
+ : inSegment;
56
+ current[j] = current[j - 1] || (canConsume ? previous[j] : 0);
57
+ }
58
+ else {
59
+ const canConsume = token.kind === 'literal' ? token.value === char : inSegment;
60
+ current[j] = canConsume ? previous[j - 1] : 0;
61
+ }
62
+ }
63
+ [previous, current] = [current, previous];
64
+ }
65
+ return previous[tokens.length] === 1;
66
+ }
67
+ export function compileExclusionPatterns(input) {
68
+ if (input === undefined)
69
+ return [];
70
+ if (!Array.isArray(input) || input.length > MAX_EXCLUDE_PATTERNS) {
71
+ throw new Error(`excludeFilePatterns must be an array of at most ${MAX_EXCLUDE_PATTERNS} patterns`);
72
+ }
73
+ return Array.from(input, (pattern) => {
74
+ if (typeof pattern !== 'string' || pattern.length > MAX_EXCLUDE_PATTERN_LENGTH) {
75
+ throw new Error(`excludeFilePatterns entries must be strings of at most ${MAX_EXCLUDE_PATTERN_LENGTH} characters`);
76
+ }
77
+ const tokens = tokenize(pattern);
78
+ return (path) => matches(tokens, path);
79
+ });
80
+ }
81
+ //# sourceMappingURL=glob-exclusions.js.map