konoha-mcp 2.2.23 → 2.2.24

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 (90) hide show
  1. package/NOTICE +38 -0
  2. package/README.md +3 -3
  3. package/apps/web/build/adapter-node.js +1 -1
  4. package/apps/web/build/build-meta.json +2 -2
  5. package/apps/web/build/client/_app/immutable/entry/{app.TYH87iYy.js → app.CKJ0NhrX.js} +2 -2
  6. package/apps/web/build/client/_app/immutable/entry/app.CKJ0NhrX.js.br +0 -0
  7. package/apps/web/build/client/_app/immutable/entry/app.CKJ0NhrX.js.gz +0 -0
  8. package/apps/web/build/client/_app/immutable/nodes/{0.D7dPIEWA.js → 0.7A6fQJ6z.js} +1 -1
  9. package/apps/web/build/client/_app/immutable/nodes/0.7A6fQJ6z.js.br +0 -0
  10. package/apps/web/build/client/_app/immutable/nodes/{0.D7dPIEWA.js.gz → 0.7A6fQJ6z.js.gz} +0 -0
  11. package/apps/web/build/client/_app/immutable/nodes/{13.TOXVaTBr.js → 13.CQB_Ed6W.js} +1 -1
  12. package/apps/web/build/client/_app/immutable/nodes/13.CQB_Ed6W.js.br +0 -0
  13. package/apps/web/build/client/_app/immutable/nodes/{13.TOXVaTBr.js.gz → 13.CQB_Ed6W.js.gz} +0 -0
  14. package/apps/web/build/client/_app/version.json +1 -1
  15. package/apps/web/build/client/_app/version.json.br +0 -0
  16. package/apps/web/build/client/_app/version.json.gz +0 -0
  17. package/apps/web/build/server/chunks/instance.js +3 -3
  18. package/apps/web/build/server/chunks/internal.js +1 -1
  19. package/apps/web/build/server/entries/pages/_layout.svelte.js +1 -1
  20. package/apps/web/build/server/entries/pages/_layout.svelte.js.map +1 -1
  21. package/apps/web/build/server/entries/pages/docs/_page.svelte.js +1 -1
  22. package/apps/web/build/server/entries/pages/docs/_page.svelte.js.map +1 -1
  23. package/apps/web/build/server/manifest-full.js +1 -1
  24. package/apps/web/build/server/manifest.js +1 -1
  25. package/apps/web/build/server/nodes/0.js +1 -1
  26. package/apps/web/build/server/nodes/13.js +1 -1
  27. package/apps/web/build/server/server.js +1 -1
  28. package/apps/web/package.json +1 -1
  29. package/bin/commands/bridge.js +62 -4
  30. package/bin/commands/doctor.js +2 -0
  31. package/bin/commands/doctor_services.js +57 -0
  32. package/bin/commands/init.js +16 -5
  33. package/bin/commands/init_clients.js +95 -8
  34. package/bin/lib/config_defaults.js +3 -0
  35. package/bin/lib/runtime_install.js +141 -54
  36. package/package.json +2 -1
  37. package/patches/gpt-tokenizer@4.1.0.patch +15 -0
  38. package/src/agent_contract.js +1 -1
  39. package/src/agent_deployer.js +48 -35
  40. package/src/agent_file_safety.js +57 -0
  41. package/src/bridge/gateway.js +2 -0
  42. package/src/bridge/gateway_adapters.js +155 -29
  43. package/src/bridge/handlers/anthropic.js +95 -26
  44. package/src/bridge/handlers/openai.js +18 -5
  45. package/src/bridge/sidecar/raw.js +10 -2
  46. package/src/bridge/stream_usage.js +66 -0
  47. package/src/client_commands.js +190 -0
  48. package/src/db_bridges.js +53 -7
  49. package/src/db_schema.js +11 -2
  50. package/src/file_tools_mcp.js +17 -9
  51. package/src/global_skill_sync.js +3 -1
  52. package/src/mcp/langgraph/edges/router.js +3 -0
  53. package/src/mcp/langgraph/index.js +22 -3
  54. package/src/mcp/langgraph/nodes/dispatch.js +3 -0
  55. package/src/mcp/langgraph/nodes/execute.js +87 -13
  56. package/src/mcp/langgraph/nodes/review.js +13 -1
  57. package/src/mcp/langgraph/slice_executor_registry.js +22 -0
  58. package/src/mcp/langgraph/state.js +5 -0
  59. package/src/mcp/lazy_subagent.js +11 -1
  60. package/src/mcp/memory_project_context.js +4 -1
  61. package/src/mcp/memory_subagent_runner.js +2 -1
  62. package/src/mcp/skills_common.js +1 -0
  63. package/src/mcp/subagent_spawner.js +7 -0
  64. package/src/mcp/todo_walkthrough_sync.js +7 -0
  65. package/src/mcp/tool_dispatch.js +16 -0
  66. package/src/mcp/workflow_completion_helpers.js +6 -1
  67. package/src/mcp/workflow_gates.js +118 -5
  68. package/src/mcp/workflow_sannin.js +9 -3
  69. package/src/mcp_tool_manifest.json +5 -1
  70. package/src/provider_usage_logger.js +92 -0
  71. package/src/schema_ddl.js +17 -1
  72. package/src/templates/AGENTS.md +1 -1
  73. package/src/templates/GEMINI.md +1 -1
  74. package/src/templates/skills/kage-skill/SKILL.md +1 -1
  75. package/src/templates/skills/konoha/SKILL.md +23 -165
  76. package/src/templates/skills/konoha/references/contract.md +1 -1
  77. package/src/templates/skills/konoha/references/peragent-usage.md +1 -1
  78. package/src/token_usage.js +57 -0
  79. package/src/tools_savings_logger.js +26 -8
  80. package/src/web/controllers/core_controller.js +10 -1
  81. package/src/workflow/jonin-builder/live_browser_monitor.js +23 -7
  82. package/apps/web/build/client/_app/immutable/entry/app.TYH87iYy.js.br +0 -0
  83. package/apps/web/build/client/_app/immutable/entry/app.TYH87iYy.js.gz +0 -0
  84. package/apps/web/build/client/_app/immutable/nodes/0.D7dPIEWA.js.br +0 -0
  85. package/apps/web/build/client/_app/immutable/nodes/13.TOXVaTBr.js.br +0 -0
  86. package/src/templates/skills/konoha/references/architecture.md +0 -99
  87. package/src/templates/skills/konoha/references/benchmark.md +0 -123
  88. package/src/templates/skills/konoha/references/docs.md +0 -46
  89. package/src/templates/skills/konoha/references/test.md +0 -71
  90. package/src/templates/skills/konoha/references/workflow.md +0 -104
@@ -7,6 +7,33 @@ const { extractAllImages } = require('../images');
7
7
  const { callRawInference } = require('../sidecar/raw');
8
8
  const { sanitizeRequest } = require('../sanitize');
9
9
 
10
+ /**
11
+ * Anthropic wire usage for an inference result, or null when the provider did
12
+ * not report both counts. Lazy require keeps this module loadable on its own.
13
+ * The schema requires integer `input_tokens` and `output_tokens`, so an
14
+ * incomplete pair cannot be emitted as `{}` and must never become a zero.
15
+ */
16
+ function usageWire(raw) {
17
+ const { buildAnthropicUsage, anthropicUsageWire } = require('../gateway_adapters');
18
+ const wire = anthropicUsageWire(buildAnthropicUsage(raw));
19
+ if (typeof wire.input_tokens !== 'number' || typeof wire.output_tokens !== 'number') return null;
20
+ return wire;
21
+ }
22
+
23
+ /** Persist provider-reported counts from this path; best-effort only. */
24
+ function recordUsage(ctx, raw, stream) {
25
+ try {
26
+ const { recordProviderUsage, PROVIDER_USAGE_SOURCES } = require('../../provider_usage_logger');
27
+ recordProviderUsage({
28
+ source: PROVIDER_USAGE_SOURCES.GATEWAY,
29
+ usage: raw && raw.usage,
30
+ provider: (ctx.bridgeConfig && ctx.bridgeConfig.provider) || null,
31
+ model: ctx.requestedModel || null,
32
+ stream
33
+ });
34
+ } catch (_) { /* telemetry must never break a response */ }
35
+ }
36
+
10
37
  // Map numeric model enum values → GetModelResponse string enum (same as chat.js)
11
38
  const VALUE_TO_MODEL_ENUM = {
12
39
  1018: 'MODEL_PLACEHOLDER_M18', // Flash
@@ -129,7 +156,7 @@ function extractAnthropicText(content) {
129
156
 
130
157
  // Anthropic SSE response builders
131
158
 
132
- function buildAnthropicMessage(id, model) {
159
+ function buildAnthropicMessage(id, model, usage) {
133
160
  return {
134
161
  id: `msg_${id}`,
135
162
  type: 'message',
@@ -138,15 +165,52 @@ function buildAnthropicMessage(id, model) {
138
165
  content: [],
139
166
  stop_reason: null,
140
167
  stop_sequence: null,
141
- usage: { input_tokens: 0, output_tokens: 0 },
168
+ usage,
142
169
  };
143
170
  }
144
171
 
172
+ /** Open the SSE response without committing to a `message_start` yet. */
173
+ function ensureAnthropicStreamHeaders(res) {
174
+ if (res.headersSent) return;
175
+ res.setHeader('Content-Type', 'text/event-stream');
176
+ res.setHeader('Cache-Control', 'no-cache');
177
+ res.setHeader('Connection', 'keep-alive');
178
+ res.writeHead(200);
179
+ }
180
+
181
+ /**
182
+ * Fail the request in Anthropic's error shape. Before any response is written
183
+ * the stream still gets an `error` event, which the SDK yields verbatim; it
184
+ * must precede `message_start` because the accumulator rejects out-of-order
185
+ * events.
186
+ */
187
+ function sendUsageUnavailable(res, isStream) {
188
+ const { USAGE_UNAVAILABLE_MESSAGE } = require('../gateway_adapters');
189
+ const body = { type: 'error', error: { type: 'api_error', message: USAGE_UNAVAILABLE_MESSAGE } };
190
+ if (isStream) {
191
+ ensureAnthropicStreamHeaders(res);
192
+ writeAnthropicEvent(res, 'error', body);
193
+ res.end();
194
+ return;
195
+ }
196
+ sendJson(res, 502, body);
197
+ }
198
+
145
199
  function writeAnthropicEvent(res, event, data) {
146
200
  res.write(`event: ${event}\ndata: ${JSON.stringify(data)}\n\n`);
147
201
  }
148
202
 
149
- function streamRawAnthropicResponse(res, raw, responseText) {
203
+ function streamRawAnthropicResponse(res, raw, responseText, msgId, model) {
204
+ const wireUsage = usageWire(raw);
205
+ if (!wireUsage) {
206
+ sendUsageUnavailable(res, true);
207
+ return;
208
+ }
209
+ ensureAnthropicStreamHeaders(res);
210
+ writeAnthropicEvent(res, 'message_start', {
211
+ type: 'message_start',
212
+ message: buildAnthropicMessage(msgId, model, wireUsage),
213
+ });
150
214
  if (raw.toolCalls && raw.toolCalls.length > 0) {
151
215
  for (let i = 0; i < raw.toolCalls.length; i++) {
152
216
  const tc = raw.toolCalls[i];
@@ -165,7 +229,7 @@ function streamRawAnthropicResponse(res, raw, responseText) {
165
229
  writeAnthropicEvent(res, 'message_delta', {
166
230
  type: 'message_delta',
167
231
  delta: { stop_reason: 'tool_use', stop_sequence: null },
168
- usage: { output_tokens: 0 },
232
+ usage: wireUsage,
169
233
  });
170
234
  } else {
171
235
  writeAnthropicEvent(res, 'content_block_start', {
@@ -184,7 +248,7 @@ function streamRawAnthropicResponse(res, raw, responseText) {
184
248
  writeAnthropicEvent(res, 'message_delta', {
185
249
  type: 'message_delta',
186
250
  delta: { stop_reason: 'end_turn', stop_sequence: null },
187
- usage: { output_tokens: 0 },
251
+ usage: wireUsage,
188
252
  });
189
253
  }
190
254
  writeAnthropicEvent(res, 'message_stop', { type: 'message_stop' });
@@ -201,6 +265,11 @@ function sendNonStreamAnthropicResponse(res, raw, responseText, msgId, modelKey)
201
265
  }
202
266
  }
203
267
  if (responseText) content.push({ type: 'text', text: responseText });
268
+ const wireUsage = usageWire(raw);
269
+ if (!wireUsage) {
270
+ sendUsageUnavailable(res, false);
271
+ return;
272
+ }
204
273
  sendJson(res, 200, {
205
274
  id: `msg_${msgId}`,
206
275
  type: 'message',
@@ -209,7 +278,7 @@ function sendNonStreamAnthropicResponse(res, raw, responseText, msgId, modelKey)
209
278
  content,
210
279
  stop_reason: raw.toolCalls ? 'tool_use' : 'end_turn',
211
280
  stop_sequence: null,
212
- usage: { input_tokens: 0, output_tokens: 0 },
281
+ usage: wireUsage,
213
282
  });
214
283
  }
215
284
 
@@ -308,14 +377,7 @@ async function handleAnthropicMessages(ctx, req, res) {
308
377
 
309
378
  const initiateStream = () => {
310
379
  if (isStream && !headersSentForStream) {
311
- res.setHeader('Content-Type', 'text/event-stream');
312
- res.setHeader('Cache-Control', 'no-cache');
313
- res.setHeader('Connection', 'keep-alive');
314
- res.writeHead(200);
315
- writeAnthropicEvent(res, 'message_start', {
316
- type: 'message_start',
317
- message: buildAnthropicMessage(msgId, resolved.key),
318
- });
380
+ ensureAnthropicStreamHeaders(res);
319
381
  headersSentForStream = true;
320
382
  }
321
383
  };
@@ -344,10 +406,11 @@ async function handleAnthropicMessages(ctx, req, res) {
344
406
  }
345
407
  const responseText = raw.content || '';
346
408
  log(ctx, `✅ [Anthropic] Raw inference succeeded (${responseText.length} chars)`);
409
+ recordUsage(ctx, raw, isStream);
347
410
 
348
411
  if (isStream) {
349
412
  initiateStream();
350
- streamRawAnthropicResponse(res, raw, responseText);
413
+ streamRawAnthropicResponse(res, raw, responseText, msgId, resolved.key);
351
414
  } else {
352
415
  sendNonStreamAnthropicResponse(res, raw, responseText, msgId, resolved.key);
353
416
  }
@@ -362,8 +425,9 @@ async function handleAnthropicMessages(ctx, req, res) {
362
425
  }
363
426
 
364
427
  // POST /v1/messages/count_tokens (mock)
365
- // Claude CLI and Cherry Studio send this before every conversation.
366
- // Return a plausible mock so they don't abort.
428
+ // Claude CLI and Cherry Studio send this before every conversation and only
429
+ // check that it answers; no tokenizer exists here. The 0 is a liveness reply,
430
+ // not a provider measurement, and is never persisted as usage.
367
431
 
368
432
  async function handleCountTokens(ctx, req, res) {
369
433
  // Consume the body so the socket stays clean
@@ -379,15 +443,16 @@ async function handleCountTokens(ctx, req, res) {
379
443
  // Anthropic format adapter for OpenAI provider
380
444
  // Converts Anthropic → OpenAI → callRawInference → Anthropic response
381
445
 
382
- function streamAnthropicToOpenAi(res, responseText, msgId, model) {
383
- res.setHeader('Content-Type', 'text/event-stream');
384
- res.setHeader('Cache-Control', 'no-cache');
385
- res.setHeader('Connection', 'keep-alive');
386
- res.writeHead(200);
446
+ function streamAnthropicToOpenAi(res, responseText, msgId, model, usage) {
447
+ if (!usage) {
448
+ sendUsageUnavailable(res, true);
449
+ return;
450
+ }
451
+ ensureAnthropicStreamHeaders(res);
387
452
 
388
453
  writeAnthropicEvent(res, 'message_start', {
389
454
  type: 'message_start',
390
- message: buildAnthropicMessage(msgId, model),
455
+ message: buildAnthropicMessage(msgId, model, usage),
391
456
  });
392
457
  writeAnthropicEvent(res, 'content_block_start', {
393
458
  type: 'content_block_start', index: 0, content_block: { type: 'text', text: '' },
@@ -398,7 +463,7 @@ function streamAnthropicToOpenAi(res, responseText, msgId, model) {
398
463
  writeAnthropicEvent(res, 'content_block_stop', { type: 'content_block_stop', index: 0 });
399
464
  writeAnthropicEvent(res, 'message_delta', {
400
465
  type: 'message_delta', delta: { stop_reason: responseText ? 'end_turn' : 'tool_use', stop_sequence: null },
401
- usage: { output_tokens: 0 },
466
+ usage,
402
467
  });
403
468
  writeAnthropicEvent(res, 'message_stop', { type: 'message_stop' });
404
469
  res.end();
@@ -420,13 +485,17 @@ async function handleAnthropicToOpenAi(ctx, req, res, ...rest) {
420
485
  if (!raw || (!raw.content && !raw.toolCalls)) throw new Error('Empty response');
421
486
 
422
487
  const responseText = raw.content || '';
488
+ recordUsage(ctx, raw, isStream);
423
489
  if (isStream) {
424
- streamAnthropicToOpenAi(res, responseText, msgId, ctx.requestedModel);
490
+ streamAnthropicToOpenAi(res, responseText, msgId, ctx.requestedModel, usageWire(raw));
425
491
  } else {
426
492
  sendNonStreamAnthropicResponse(res, raw, responseText, msgId, ctx.requestedModel);
427
493
  }
428
494
  } catch (err) {
429
- sendJson(res, 500, { type: 'error', error: { type: 'api_error', message: err.message } });
495
+ // A stream may already have written headers and pings, so a JSON body here
496
+ // would be a second, invalid response on the same connection.
497
+ const { sendAnthropicErrorResponse } = require('../gateway_adapters');
498
+ sendAnthropicErrorResponse(res, 500, 'api_error', err.message, isStream);
430
499
  }
431
500
  }
432
501
 
@@ -13,6 +13,7 @@ const {
13
13
  const { extractText, extractAllImages } = require('../images');
14
14
  const { sanitizeRequest } = require('../sanitize');
15
15
  const { forwardWithRetry } = require('../request_retry');
16
+ const { supportsStreamUsage } = require('../stream_usage');
16
17
 
17
18
  // POST /v1/chat/completions
18
19
 
@@ -60,7 +61,7 @@ async function handleOpenAiDirect(ctx, req, res, messages, ...rest) {
60
61
  } catch { /* intentional best-effort fallback: failure here must never crash the runtime */ }
61
62
 
62
63
  if (isStream) {
63
- return streamOpenAiDirect(ctx, req, res, messages, completionId, tools, images);
64
+ return streamOpenAiDirect(ctx, req, res, messages, completionId, tools, images, payload.stream_options);
64
65
  }
65
66
 
66
67
  try {
@@ -153,8 +154,21 @@ async function _handleStreamFetchResponse(response, res) {
153
154
  await _pipeReaderToResponse(response.body.getReader(), res);
154
155
  }
155
156
 
157
+ /**
158
+ * The upstream body for a streamed request. `stream_options` is forwarded only
159
+ * to a provider whose contract defines it: a server that validates unknown
160
+ * parameters rejects the whole request over the field, so an unsupported
161
+ * upstream must never see it.
162
+ */
163
+ function buildStreamRequestBody(ctx, messages, tools, streamOptions) {
164
+ const reqBody = { model: ctx.requestedModel, messages, stream: true };
165
+ if (tools) reqBody.tools = tools;
166
+ if (streamOptions && supportsStreamUsage(ctx.bridgeConfig)) reqBody.stream_options = streamOptions;
167
+ return reqBody;
168
+ }
169
+
156
170
  function streamOpenAiDirect(ctx, req, res, messages, ...rest) {
157
- const [_completionId, tools, _] = rest;
171
+ const [_completionId, tools, _, streamOptions] = rest;
158
172
  setupStreamResponse(res);
159
173
 
160
174
  const bridgeConfig = ctx.bridgeConfig || {};
@@ -173,8 +187,7 @@ function streamOpenAiDirect(ctx, req, res, messages, ...rest) {
173
187
  const headers = { 'Content-Type': 'application/json' };
174
188
  if (bridgeConfig.apiKey) headers['Authorization'] = `Bearer ${bridgeConfig.apiKey}`;
175
189
 
176
- const reqBody = { model: ctx.requestedModel, messages, stream: true };
177
- if (tools) reqBody.tools = tools;
190
+ const reqBody = buildStreamRequestBody(ctx, messages, tools, streamOptions);
178
191
 
179
192
  let abortController = new AbortController();
180
193
  res.on('close', () => {
@@ -215,4 +228,4 @@ async function forwardJsonBody(response) {
215
228
  return JSON.parse(Buffer.concat(chunks).toString('utf8'));
216
229
  }
217
230
 
218
- module.exports = { handleChatCompletions, handleOpenAiDirect };
231
+ module.exports = { handleChatCompletions, handleOpenAiDirect, buildStreamRequestBody };
@@ -246,7 +246,12 @@ async function _resolveWorkingLsPort(info, mainCsrf) {
246
246
  * @param {string} modelEnum - Model enum string (e.g. 'MODEL_PLACEHOLDER_M18')
247
247
  * @param {Array|null} tools - OpenAI tool definitions
248
248
  * @param {Array} images - Array of extracted image objects
249
- * @returns {{ content: string|null, toolCalls: Array|null }}
249
+ * @returns {{ content: string|null, toolCalls: Array|null, usage?: object|null }}
250
+ *
251
+ * `usage` is present only when the upstream reported counts (the `openai`
252
+ * provider path). Text/cascade/fallback branches return no `usage` because no
253
+ * provider payload carries one; callers must treat absence as unknown rather
254
+ * than as zero.
250
255
  */
251
256
  async function callRawInference(ctx, messages, modelEnum, tools = null, images = []) {
252
257
  if (ctx.bridgeConfig && ctx.bridgeConfig.provider === 'openai') {
@@ -460,8 +465,11 @@ async function callOpenAiInference(ctx, messages, modelEnum, tools = null, _ = [
460
465
 
461
466
  const content = choice.message.content || null;
462
467
  const toolCalls = choice.message.tool_calls || null;
468
+ // The upstream may have reported counts; carry them so the Anthropic handler
469
+ // can emit and persist them instead of hardcoding zeros.
470
+ const usage = result.usage && typeof result.usage === 'object' ? result.usage : null;
463
471
 
464
- return { content, toolCalls };
472
+ return { content, toolCalls, usage };
465
473
  }
466
474
 
467
475
  module.exports = { callRawInference, formatMessagesAsPrompt, parseToolCalls };
@@ -0,0 +1,66 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * src/bridge/stream_usage.js — who may be sent `stream_options.include_usage`.
5
+ *
6
+ * `stream_options` belongs to the [OI] Chat Completions contract. A provider
7
+ * that does not implement that contract may reject the unknown parameter and
8
+ * fail the whole request, so support is never inferred from "it looks like an
9
+ * LLM endpoint": only a provider on the explicit allowlist is asked, and
10
+ * anything else is denied. The allowlist is config-driven
11
+ * (`bridge_stream_usage_providers`, default `openai`) so a verified provider can
12
+ * be added without a code change, and a single bridge can override the decision
13
+ * in either direction with `supportsStreamUsage`.
14
+ *
15
+ * Denying the field is not an error: the stream proceeds and the caller sees
16
+ * whatever usage the upstream volunteers. When it volunteers none, the
17
+ * Anthropic translation fails loudly rather than inventing counts.
18
+ */
19
+
20
+ const { getConfigValue } = require('../config_access');
21
+
22
+ /**
23
+ * Providers whose declared contract is the [OI] Chat Completions API, which is
24
+ * where `stream_options.include_usage` is defined. `openai-compatible` is the
25
+ * label this repository's `konoha bridge create` writes for "speaks that API"
26
+ * (OpenAI, Groq, vLLM, Ollama, LM Studio, llama.cpp), so it qualifies; an
27
+ * `antigravity-extension` or unrecognised provider does not.
28
+ *
29
+ * A server that validates unknown parameters rejects the whole request, so this
30
+ * list is the allowlist, not a guess: unknown providers are denied by default
31
+ * and a strict server is excluded with `bridge_stream_usage_providers` or a
32
+ * per-bridge `supportsStreamUsage: false`.
33
+ */
34
+ const DEFAULT_STREAM_USAGE_PROVIDERS = ['openai', 'openai-compatible', '9router'];
35
+
36
+ function parseAllowlist(raw) {
37
+ const source = Array.isArray(raw) ? raw : String(raw === undefined || raw === null ? '' : raw).split(',');
38
+ return new Set(
39
+ source
40
+ .map((value) => String(value).trim().toLowerCase())
41
+ .filter(Boolean)
42
+ );
43
+ }
44
+
45
+ function providerAllowlist(rawConfig) {
46
+ const configured = rawConfig === undefined ? getConfigValue('bridge_stream_usage_providers') : rawConfig;
47
+ const parsed = parseAllowlist(configured);
48
+ return parsed.size > 0 ? parsed : parseAllowlist(DEFAULT_STREAM_USAGE_PROVIDERS);
49
+ }
50
+
51
+ /**
52
+ * Decide whether this bridge may receive `stream_options.include_usage`.
53
+ *
54
+ * @param {object|null} bridgeConfig bridge row (`provider`, `supportsStreamUsage`)
55
+ * @param {string|string[]} [rawConfig] override for `bridge_stream_usage_providers`
56
+ * @returns {boolean}
57
+ */
58
+ function supportsStreamUsage(bridgeConfig, rawConfig) {
59
+ if (!bridgeConfig) return false;
60
+ if (typeof bridgeConfig.supportsStreamUsage === 'boolean') return bridgeConfig.supportsStreamUsage;
61
+ const provider = typeof bridgeConfig.provider === 'string' ? bridgeConfig.provider.trim().toLowerCase() : '';
62
+ if (!provider) return false;
63
+ return providerAllowlist(rawConfig).has(provider);
64
+ }
65
+
66
+ module.exports = { supportsStreamUsage, providerAllowlist, DEFAULT_STREAM_USAGE_PROVIDERS };
@@ -0,0 +1,190 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * `/konoha` slash command deployment.
5
+ *
6
+ * A slash command is a client-side prompt template, not a server route: the
7
+ * MCP server cannot register one. Each client reads prompt files from its own
8
+ * directory, so `/konoha` only exists in a client whose directory Konoha writes.
9
+ *
10
+ * Fail closed: a client is written only when its prompt-file contract is
11
+ * confirmed from that client's installed bundle and its config root already
12
+ * exists. Presence of the config root is the gate — a root that is absent is
13
+ * never created, so a client the user does not run receives nothing. `pi` and
14
+ * `antigravity` expose commands only through their own plugin/extension
15
+ * packaging, which Konoha cannot author safely, so they are reported as
16
+ * unsupported instead of being given a file that may never load.
17
+ */
18
+
19
+ const fs = require('fs');
20
+ const path = require('path');
21
+
22
+ const COMMAND_NAME = 'konoha';
23
+
24
+ // Ownership marker. Konoha rewrites only a file carrying this line, so a user
25
+ // file is never clobbered and a reworded body never makes our own file look
26
+ // user-authored. Same convention as agent profiles (`generated_by: konoha`).
27
+ const KONOHA_COMMAND_MARKER = /^generated_by:\s*konoha\s*$/m;
28
+
29
+ const KONOHA_COMMAND_BODY = `---
30
+ description: Run the Konoha multi-agent workflow for this request
31
+ generated_by: konoha
32
+ ---
33
+
34
+ Run the Konoha workflow for: $ARGUMENTS
35
+
36
+ 1. Classify the request. Website build intent (build/create/scaffold/make + website, web app, landing page, UI, frontend, dashboard, storefront, portfolio, or a named framework) is Branch B; everything else is Branch A.
37
+ 2. Branch A: \`konoha.sannin\` first for triage and the resolved task dir, then explore (\`genin\`), plan (\`kage\`), execute (\`jonin\`/\`anbu\`/\`chunin\`), document (\`tokubetsu_jonin\`), review (\`kage\`).
38
+ 3. Branch B: \`konoha.build_from_text\` (or \`build_from_source\` for mockups) first, then hand the directives to \`konoha.jonin\`. Skip Chunin, Genin, and Kage.
39
+ 4. Spawn each specialist with the \`spawn_directive\` the MCP tool returns, using this client's native subagent tool, or the CLI fallback \`rtk konoha run-agent\` when the client has none.
40
+ 5. A slice is complete only after \`konoha.report_from_agent\` records it with real validation evidence.
41
+
42
+ If the request is empty, ask what to build or fix and stop.
43
+ `;
44
+
45
+ // Migration: the first 2.2.23 build shipped this body without the marker, so a
46
+ // file it wrote would otherwise read as user-owned and never upgrade again.
47
+ // Derived, not duplicated; drop once no markerless file is in the field.
48
+ const LEGACY_COMMAND_BODY = KONOHA_COMMAND_BODY.replace('generated_by: konoha\n', '');
49
+
50
+ // Prompt-file contract per client, confirmed from the installed bundle:
51
+ // claudecode ~/.local/share/claude/versions/<v> -> `.claude/commands/`
52
+ // cursor cursor-agent bundle -> `.cursor/commands/`
53
+ // opencode opencode binary -> `<config>/opencode/command/`
54
+ // commandcode dist/bundled/.../custom-slash-commands.md -> `~/.commandcode/commands/`
55
+ // codex + omp omp's prompt loader reads `~/.codex/prompts`, so one file serves both
56
+ // Each client also has a project form. Two are documented in the installed
57
+ // bundle and were read there: command-code's reference lists
58
+ // `.commandcode/commands/` beside the user directory, and omp's loader lists
59
+ // `.codex/prompts/` beside `~/.codex/prompts`. The other three are the
60
+ // documented project path of the same client but were not read out of the
61
+ // bundle, so they carry the same assumption as the user path above.
62
+ // `projectDir` is set only where the project shape differs (opencode).
63
+ const COMMAND_TARGETS = Object.freeze([
64
+ { client: 'claudecode', configRoot: '.claude', dir: ['.claude', 'commands'] },
65
+ { client: 'cursor', configRoot: '.cursor', dir: ['.cursor', 'commands'] },
66
+ { client: 'opencode', configRoot: path.join('.config', 'opencode'), dir: ['.config', 'opencode', 'command'], projectDir: ['.opencode', 'command'] },
67
+ { client: 'commandcode', configRoot: '.commandcode', dir: ['.commandcode', 'commands'] },
68
+ { client: 'codex', configRoot: '.codex', dir: ['.codex', 'prompts'], alsoServes: ['omp'] }
69
+ ]);
70
+
71
+ const UNSUPPORTED_CLIENTS = Object.freeze([
72
+ { client: 'pi', reason: 'pi loads commands only through its extension packaging; no prompt directory is exposed' },
73
+ { client: 'antigravity', reason: 'antigravity loads commands only from installed plugins; no user prompt directory is exposed' }
74
+ ]);
75
+
76
+ function resolveHome(home) {
77
+ return home || process.env.HOME || process.env.USERPROFILE || require('os').homedir();
78
+ }
79
+
80
+ /**
81
+ * Classifies a command file without touching it.
82
+ * @returns {{present?:true, unchanged?:true, skip?:string}}
83
+ */
84
+ function _inspectCommandFile(file) {
85
+ if (!fs.existsSync(file)) return { present: false };
86
+ const current = fs.readFileSync(file, 'utf8');
87
+ if (current === KONOHA_COMMAND_BODY) return { present: true, unchanged: true };
88
+ if (current === LEGACY_COMMAND_BODY) return { present: true };
89
+ if (!KONOHA_COMMAND_MARKER.test(current)) return { skip: `user-owned ${file} left untouched` };
90
+ return { present: true };
91
+ }
92
+
93
+ /**
94
+ * Writes Konoha's command file unless a user authored one there. Konoha's own
95
+ * file is rewritten so upgrades land.
96
+ * @returns {{unchanged?:true, skip?:string}}
97
+ */
98
+ function _writeCommandFile(file) {
99
+ const state = _inspectCommandFile(file);
100
+ if (state.skip || state.unchanged) return state;
101
+ fs.writeFileSync(file, KONOHA_COMMAND_BODY, { encoding: 'utf8', mode: 0o644 });
102
+ return {};
103
+ }
104
+
105
+ function _recordDeployment(target, scope, file, outcome, ctx) {
106
+ if (outcome.skip) {
107
+ ctx.skipped.push({ client: target.client, scope, reason: outcome.skip });
108
+ return;
109
+ }
110
+ const unchanged = outcome.unchanged ? { unchanged: true } : {};
111
+ ctx.deployed.push({ client: target.client, scope, path: file, ...unchanged });
112
+ for (const alias of target.alsoServes || []) {
113
+ ctx.deployed.push({ client: alias, scope, path: file, sharedWith: target.client, ...unchanged });
114
+ }
115
+ }
116
+
117
+ // The client's own config root is the only signal that the client is installed,
118
+ // so it gates both scopes: a project copy is written only for a client whose
119
+ // global root exists. That keeps `--project` from scattering command files into
120
+ // repositories for clients the user does not run.
121
+ function _deployScope(target, { scope, base, segments }, ctx) {
122
+ const { options, home } = ctx;
123
+ if (!options.force && !fs.existsSync(path.join(home, target.configRoot))) {
124
+ ctx.skipped.push({ client: target.client, scope, reason: `${target.configRoot} not present for this user` });
125
+ return;
126
+ }
127
+ const file = path.join(base, ...segments, `${COMMAND_NAME}.md`);
128
+ if (options.statusOnly) {
129
+ const state = _inspectCommandFile(file);
130
+ _recordDeployment(target, scope, file, state.present ? state : { skip: `no command file at ${file}` }, ctx);
131
+ return;
132
+ }
133
+ try {
134
+ fs.mkdirSync(path.dirname(file), { recursive: true });
135
+ _recordDeployment(target, scope, file, _writeCommandFile(file), ctx);
136
+ } catch (err) {
137
+ ctx.skipped.push({ client: target.client, scope, reason: `${err.code || 'error'}: ${err.message}` });
138
+ }
139
+ }
140
+
141
+ // `--client=<x>` must narrow the command layer too. A target is selected when
142
+ // its own client, or a client it also serves, was requested.
143
+ function _isSelected(target, options) {
144
+ const wanted = options.clients;
145
+ if (!wanted) return true;
146
+ return [target.client, ...(target.alsoServes || [])].some((name) => wanted.includes(name));
147
+ }
148
+
149
+ function _deployTarget(target, ctx) {
150
+ const { options, home } = ctx;
151
+ if (!_isSelected(target, options)) return;
152
+ _deployScope(target, { scope: 'user', base: home, segments: target.dir }, ctx);
153
+ if (!options.projectRoot) return;
154
+ _deployScope(target, {
155
+ scope: 'project',
156
+ base: options.projectRoot,
157
+ segments: target.projectDir || target.dir
158
+ }, ctx);
159
+ }
160
+
161
+ /**
162
+ * @param {object} [options]
163
+ * @param {string} [options.home] overrides HOME (tests)
164
+ * @param {string[]|null} [options.clients] restrict to these client names (init's `--client`)
165
+ * @param {string|null} [options.projectRoot] also deploy the project-scoped copy
166
+ * @param {boolean} [options.force] write even when the client config root is missing
167
+ * @param {boolean} [options.statusOnly] report what is installed without writing (doctor)
168
+ * @returns {{deployed: Array<{client:string,scope:string,path:string}>, skipped: Array<{client:string,scope:string,reason:string}>}}
169
+ */
170
+ function deployKonohaCommands(options = {}) {
171
+ const home = resolveHome(options.home);
172
+ const deployed = [];
173
+ const skipped = [];
174
+ const ctx = { options, home, deployed, skipped };
175
+ for (const target of COMMAND_TARGETS) _deployTarget(target, ctx);
176
+ for (const entry of UNSUPPORTED_CLIENTS) {
177
+ if (options.clients && !options.clients.includes(entry.client)) continue;
178
+ skipped.push({ client: entry.client, scope: 'user', reason: entry.reason });
179
+ }
180
+ return { deployed, skipped };
181
+ }
182
+
183
+ module.exports = {
184
+ COMMAND_NAME,
185
+ KONOHA_COMMAND_BODY,
186
+ LEGACY_COMMAND_BODY,
187
+ COMMAND_TARGETS,
188
+ UNSUPPORTED_CLIENTS,
189
+ deployKonohaCommands
190
+ };