konoha-mcp 2.2.23 → 2.2.25

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 (132) hide show
  1. package/NOTICE +14 -8
  2. package/README.md +20 -5
  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.DtoBIrs4.js} +2 -2
  6. package/apps/web/build/client/_app/immutable/entry/app.DtoBIrs4.js.br +0 -0
  7. package/apps/web/build/client/_app/immutable/entry/app.DtoBIrs4.js.gz +0 -0
  8. package/apps/web/build/client/_app/immutable/nodes/{0.D7dPIEWA.js → 0.B8Iw7Xl1.js} +1 -1
  9. package/apps/web/build/client/_app/immutable/nodes/0.B8Iw7Xl1.js.br +0 -0
  10. package/apps/web/build/client/_app/immutable/nodes/{0.D7dPIEWA.js.gz → 0.B8Iw7Xl1.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/assets/demo-agy.webp +0 -0
  30. package/assets/demo-claude.webp +0 -0
  31. package/assets/demo-codex.webp +0 -0
  32. package/assets/demo-commandcode.webp +0 -0
  33. package/assets/demo-cursor.webp +0 -0
  34. package/assets/demo-opencode.webp +0 -0
  35. package/assets/demo-pi.webp +0 -0
  36. package/assets/demo-skill-embed.webp +0 -0
  37. package/assets/demo-skills.webp +0 -0
  38. package/assets/demo-web.webp +0 -0
  39. package/assets/demo.webp +0 -0
  40. package/assets/konoha-akatsuki-flow.webp +0 -0
  41. package/assets/konoha-anbu-flow.webp +0 -0
  42. package/assets/konoha-flow-12-cli-upgrade-progress-engine.webp +0 -0
  43. package/assets/konoha-jonin-flow.webp +0 -0
  44. package/assets/konoha-kage-gate.webp +0 -0
  45. package/assets/konoha-langgraph-flow.webp +0 -0
  46. package/assets/konoha-orchestration-flow.webp +0 -0
  47. package/assets/konoha-qa-flow.webp +0 -0
  48. package/assets/konoha-telegram-flow.webp +0 -0
  49. package/assets/testing.webp +0 -0
  50. package/bin/commands/bridge.js +62 -4
  51. package/bin/commands/doctor.js +2 -0
  52. package/bin/commands/doctor_services.js +57 -0
  53. package/bin/commands/init.js +29 -8
  54. package/bin/commands/init_clients.js +95 -8
  55. package/bin/commands/init_migration.js +32 -1
  56. package/bin/lib/config_defaults.js +3 -0
  57. package/bin/lib/runtime_install.js +147 -54
  58. package/node_modules/jszip/package.json +2 -2
  59. package/node_modules/string_decoder/package.json +1 -1
  60. package/package.json +10 -3
  61. package/patches/gpt-tokenizer@4.1.0.patch +15 -0
  62. package/patches/jszip@3.10.2.patch +11 -0
  63. package/patches/string_decoder@1.3.0.patch +12 -0
  64. package/src/agent_contract.js +2 -2
  65. package/src/agent_deployer.js +48 -35
  66. package/src/agent_file_safety.js +57 -0
  67. package/src/antigravity_subagent_hook.js +30 -12
  68. package/src/bridge/gateway.js +2 -0
  69. package/src/bridge/gateway_adapters.js +155 -29
  70. package/src/bridge/handlers/anthropic.js +95 -26
  71. package/src/bridge/handlers/openai.js +18 -5
  72. package/src/bridge/sidecar/raw.js +10 -2
  73. package/src/bridge/stream_usage.js +66 -0
  74. package/src/chunin_knowledge_ddl.js +95 -0
  75. package/src/client_commands.js +190 -0
  76. package/src/db_bridges.js +53 -7
  77. package/src/db_schema.js +14 -2
  78. package/src/deploy_installer.js +212 -11
  79. package/src/deploy_utils.js +4 -0
  80. package/src/file_tools/common.js +65 -3
  81. package/src/file_tools_mcp.js +17 -9
  82. package/src/file_tools_router.js +67 -6
  83. package/src/global_skill_sync.js +3 -1
  84. package/src/mcp/chunin_knowledge.js +509 -0
  85. package/src/mcp/langgraph/edges/router.js +3 -0
  86. package/src/mcp/langgraph/index.js +22 -3
  87. package/src/mcp/langgraph/nodes/dispatch.js +3 -0
  88. package/src/mcp/langgraph/nodes/execute.js +87 -13
  89. package/src/mcp/langgraph/nodes/review.js +13 -1
  90. package/src/mcp/langgraph/slice_executor_registry.js +22 -0
  91. package/src/mcp/langgraph/state.js +5 -0
  92. package/src/mcp/lazy_subagent.js +11 -1
  93. package/src/mcp/memory_project_context.js +4 -1
  94. package/src/mcp/memory_subagent_runner.js +2 -1
  95. package/src/mcp/skills_common.js +1 -0
  96. package/src/mcp/subagent_spawner.js +7 -0
  97. package/src/mcp/todo_walkthrough_sync.js +7 -0
  98. package/src/mcp/tool_dispatch.js +18 -1
  99. package/src/mcp/web_search.js +27 -3
  100. package/src/mcp/workflow_completion_helpers.js +6 -1
  101. package/src/mcp/workflow_gates.js +118 -5
  102. package/src/mcp/workflow_sannin.js +9 -3
  103. package/src/mcp_clients/common.js +31 -0
  104. package/src/mcp_tool_manifest.json +36 -1
  105. package/src/pi_fs_helpers.js +31 -0
  106. package/src/pi_manager.js +68 -28
  107. package/src/provider_usage_logger.js +92 -0
  108. package/src/schema_ddl.js +17 -1
  109. package/src/templates/AGENTS.md +1 -1
  110. package/src/templates/GEMINI.md +1 -1
  111. package/src/templates/skills/chunin-skill/SKILL.md +34 -0
  112. package/src/templates/skills/chunin-skill/references/deep-research-analyst.md +27 -10
  113. package/src/templates/skills/kage-skill/SKILL.md +1 -1
  114. package/src/templates/skills/konoha/SKILL.md +23 -165
  115. package/src/templates/skills/konoha/references/contract.md +2 -2
  116. package/src/templates/skills/konoha/references/peragent-usage.md +1 -1
  117. package/src/token_usage.js +57 -0
  118. package/src/tools_savings_logger.js +26 -8
  119. package/src/url_canonical.js +58 -0
  120. package/src/vector_pipeline.js +6 -4
  121. package/src/vector_search.js +4 -2
  122. package/src/web/controllers/core_controller.js +10 -1
  123. package/src/workflow/jonin-builder/live_browser_monitor.js +23 -7
  124. package/apps/web/build/client/_app/immutable/entry/app.TYH87iYy.js.br +0 -0
  125. package/apps/web/build/client/_app/immutable/entry/app.TYH87iYy.js.gz +0 -0
  126. package/apps/web/build/client/_app/immutable/nodes/0.D7dPIEWA.js.br +0 -0
  127. package/apps/web/build/client/_app/immutable/nodes/13.TOXVaTBr.js.br +0 -0
  128. package/src/templates/skills/konoha/references/architecture.md +0 -99
  129. package/src/templates/skills/konoha/references/benchmark.md +0 -123
  130. package/src/templates/skills/konoha/references/docs.md +0 -46
  131. package/src/templates/skills/konoha/references/test.md +0 -71
  132. package/src/templates/skills/konoha/references/workflow.md +0 -104
@@ -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,95 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * src/chunin_knowledge_ddl.js — Schema v11 DDL for the Chunin research knowledge store.
5
+ *
6
+ * Chunin re-runs the same research topics across sessions. This store keeps the
7
+ * verified learnings from earlier runs so a later run can retrieve the top-5
8
+ * relevant references before touching the network, then only search for what is
9
+ * genuinely new.
10
+ *
11
+ * The vector column follows the repository's existing convention: a BLOB
12
+ * `embedding` column registered with the bundled sqlite-vector extension via
13
+ * `vector_init()`, not a sqlite-vec `vec0` virtual table. Reusing the extension
14
+ * already vendored in `vendor/sqlite-vector` avoids a second vector engine and
15
+ * keeps one distance implementation (COSINE, normalized FLOAT32, 384 dims).
16
+ */
17
+
18
+ const CHUNIN_KNOWLEDGE_TABLE = 'chunin_knowledge';
19
+ const CHUNIN_KNOWLEDGE_FTS = 'chunin_knowledge_fts';
20
+
21
+ const CHUNIN_KNOWLEDGE_V11_DDL = `
22
+ CREATE TABLE IF NOT EXISTS chunin_knowledge (
23
+ id TEXT PRIMARY KEY,
24
+ query_topic TEXT NOT NULL,
25
+ learning_text TEXT NOT NULL,
26
+ canonical_url TEXT NOT NULL DEFAULT '',
27
+ source_title TEXT NOT NULL DEFAULT '',
28
+ content_hash TEXT NOT NULL,
29
+ citation_id TEXT NOT NULL DEFAULT '',
30
+ confidence_tier TEXT NOT NULL DEFAULT 'unverified',
31
+ created_at TEXT NOT NULL,
32
+ last_verified_at TEXT NOT NULL DEFAULT '',
33
+ embedding BLOB DEFAULT NULL
34
+ );
35
+
36
+ CREATE UNIQUE INDEX IF NOT EXISTS idx_chunin_knowledge_hash
37
+ ON chunin_knowledge(content_hash);
38
+
39
+ CREATE INDEX IF NOT EXISTS idx_chunin_knowledge_topic
40
+ ON chunin_knowledge(query_topic);
41
+
42
+ CREATE INDEX IF NOT EXISTS idx_chunin_knowledge_url
43
+ ON chunin_knowledge(canonical_url);
44
+
45
+ CREATE VIRTUAL TABLE IF NOT EXISTS chunin_knowledge_fts USING fts5(
46
+ learning_text,
47
+ source_title,
48
+ query_topic,
49
+ content='chunin_knowledge',
50
+ content_rowid='rowid'
51
+ );
52
+
53
+ CREATE TRIGGER IF NOT EXISTS chunin_knowledge_fts_ai AFTER INSERT ON chunin_knowledge BEGIN
54
+ INSERT INTO chunin_knowledge_fts(rowid, learning_text, source_title, query_topic)
55
+ VALUES (new.rowid, new.learning_text, new.source_title, new.query_topic);
56
+ END;
57
+
58
+ CREATE TRIGGER IF NOT EXISTS chunin_knowledge_fts_ad AFTER DELETE ON chunin_knowledge BEGIN
59
+ INSERT INTO chunin_knowledge_fts(chunin_knowledge_fts, rowid, learning_text, source_title, query_topic)
60
+ VALUES ('delete', old.rowid, old.learning_text, old.source_title, old.query_topic);
61
+ END;
62
+
63
+ CREATE TRIGGER IF NOT EXISTS chunin_knowledge_fts_au AFTER UPDATE ON chunin_knowledge BEGIN
64
+ INSERT INTO chunin_knowledge_fts(chunin_knowledge_fts, rowid, learning_text, source_title, query_topic)
65
+ VALUES ('delete', old.rowid, old.learning_text, old.source_title, old.query_topic);
66
+ INSERT INTO chunin_knowledge_fts(rowid, learning_text, source_title, query_topic)
67
+ VALUES (new.rowid, new.learning_text, new.source_title, new.query_topic);
68
+ END;
69
+ `;
70
+
71
+ const CHUNIN_KNOWLEDGE_COLUMNS = [
72
+ 'id',
73
+ 'query_topic',
74
+ 'learning_text',
75
+ 'canonical_url',
76
+ 'source_title',
77
+ 'content_hash',
78
+ 'citation_id',
79
+ 'confidence_tier',
80
+ 'created_at',
81
+ 'last_verified_at'
82
+ ];
83
+
84
+ function applyChuninKnowledgeSchema(conn) {
85
+ conn.exec(CHUNIN_KNOWLEDGE_V11_DDL);
86
+ return true;
87
+ }
88
+
89
+ module.exports = {
90
+ CHUNIN_KNOWLEDGE_TABLE,
91
+ CHUNIN_KNOWLEDGE_FTS,
92
+ CHUNIN_KNOWLEDGE_COLUMNS,
93
+ CHUNIN_KNOWLEDGE_V11_DDL,
94
+ applyChuninKnowledgeSchema
95
+ };
@@ -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
+ };
package/src/db_bridges.js CHANGED
@@ -69,6 +69,17 @@ function _isValidTargetUrl(targetUrl) {
69
69
  }
70
70
  }
71
71
 
72
+ function _parseStreamUsage(value) {
73
+ if (value === undefined || value === '') return null;
74
+ if (value === null) return null;
75
+ if (typeof value === 'boolean') return value;
76
+ if (value === 1 || value === 0) return value === 1;
77
+ const text = String(value).trim().toLowerCase();
78
+ if (text === 'always' || text === 'true' || text === '1' || text === 'on' || text === 'yes') return true;
79
+ if (text === 'never' || text === 'false' || text === '0' || text === 'off' || text === 'no') return false;
80
+ return null;
81
+ }
82
+
72
83
  function _insertSingleBridgeRow(stmt, b) {
73
84
  const name = b.name;
74
85
  if (!name) return;
@@ -89,7 +100,10 @@ function _insertSingleBridgeRow(stmt, b) {
89
100
  }
90
101
  const rawKey = b.apiKey || b.api_key || null;
91
102
  const apiKey = encryptApiKey(rawKey);
92
- stmt.run(name, port, provider, enabled, targetUrl, apiKey);
103
+ const streamUsage = _parseStreamUsage(
104
+ b.supportsStreamUsage !== undefined ? b.supportsStreamUsage : b.supports_stream_usage
105
+ );
106
+ stmt.run(name, port, provider, enabled, targetUrl, apiKey, streamUsage === null ? null : (streamUsage ? 1 : 0));
93
107
  }
94
108
 
95
109
  function autoMigrateJsonIfNeeded(conn) {
@@ -101,8 +115,8 @@ function autoMigrateJsonIfNeeded(conn) {
101
115
  const bridgesToInsert = _loadBridgesToInsert();
102
116
 
103
117
  const stmt = conn.prepare(`
104
- INSERT OR REPLACE INTO bridges (name, port, provider, enabled, target_url, api_key)
105
- VALUES (?, ?, ?, ?, ?, ?)
118
+ INSERT OR REPLACE INTO bridges (name, port, provider, enabled, target_url, api_key, supports_stream_usage)
119
+ VALUES (?, ?, ?, ?, ?, ?, ?)
106
120
  `);
107
121
 
108
122
  for (const b of bridgesToInsert) {
@@ -114,7 +128,7 @@ function listBridges(dbPath = null) {
114
128
  const conn = getDbConnection(dbPath);
115
129
  try {
116
130
  autoMigrateJsonIfNeeded(conn);
117
- const rows = conn.prepare("SELECT name, port, provider, enabled, target_url, api_key FROM bridges").all();
131
+ const rows = conn.prepare("SELECT name, port, provider, enabled, target_url, api_key, supports_stream_usage FROM bridges").all();
118
132
  const result = [];
119
133
  for (const r of rows) {
120
134
  const item = {
@@ -129,6 +143,9 @@ function listBridges(dbPath = null) {
129
143
  if (r.api_key) {
130
144
  item.apiKey = decryptApiKey(r.api_key);
131
145
  }
146
+ if (r.supports_stream_usage !== null && r.supports_stream_usage !== undefined) {
147
+ item.supportsStreamUsage = Boolean(r.supports_stream_usage);
148
+ }
132
149
  result.push(item);
133
150
  }
134
151
  return result;
@@ -164,11 +181,19 @@ function upsertBridge(bridgeDict, dbPath = null) {
164
181
  }
165
182
  const rawKey = bridgeDict.apiKey || bridgeDict.api_key || null;
166
183
  const apiKey = encryptApiKey(rawKey);
184
+ const streamUsage = _parseStreamUsage(
185
+ bridgeDict.supportsStreamUsage !== undefined ? bridgeDict.supportsStreamUsage : bridgeDict.supports_stream_usage
186
+ );
187
+ // A partial upsert (nothing said about stream usage) must not silently
188
+ // reset an operator's override: absence means "leave it as stored".
189
+ const storedStreamUsage = streamUsage === null
190
+ ? (conn.prepare("SELECT supports_stream_usage AS v FROM bridges WHERE name = ?").get(name) || {}).v ?? null
191
+ : (streamUsage ? 1 : 0);
167
192
 
168
193
  conn.prepare(`
169
- INSERT OR REPLACE INTO bridges (name, port, provider, enabled, target_url, api_key)
170
- VALUES (?, ?, ?, ?, ?, ?)
171
- `).run(name, port, provider, enabled, targetUrl, apiKey);
194
+ INSERT OR REPLACE INTO bridges (name, port, provider, enabled, target_url, api_key, supports_stream_usage)
195
+ VALUES (?, ?, ?, ?, ?, ?, ?)
196
+ `).run(name, port, provider, enabled, targetUrl, apiKey, storedStreamUsage);
172
197
  } finally {
173
198
  conn.close();
174
199
  }
@@ -254,6 +279,25 @@ function setEnabled(name, enabledBool, dbPath = null) {
254
279
  }
255
280
  }
256
281
 
282
+ /**
283
+ * Set a saved bridge's `stream_options.include_usage` override.
284
+ * `null`/`'auto'` clears it, handing the decision back to the provider allowlist.
285
+ */
286
+ function setStreamUsage(name, value, dbPath = null) {
287
+ const parsed = _parseStreamUsage(value);
288
+ const stored = parsed === null ? null : (parsed ? 1 : 0);
289
+ const conn = getDbConnection(dbPath);
290
+ try {
291
+ const info = conn.prepare("UPDATE bridges SET supports_stream_usage = ? WHERE name = ?").run(stored, name);
292
+ if (!info.changes) {
293
+ throw new Error(`Bridge "${name}" not found`);
294
+ }
295
+ return stored;
296
+ } finally {
297
+ conn.close();
298
+ }
299
+ }
300
+
257
301
  function _isCallerMcpSubprocess() {
258
302
  if (process.env.KONOHA_DAEMON === 'true') return false;
259
303
  try {
@@ -315,6 +359,8 @@ module.exports = {
315
359
  delete_bridge: deleteBridge,
316
360
  setEnabled,
317
361
  set_enabled: setEnabled,
362
+ setStreamUsage,
363
+ set_stream_usage: setStreamUsage,
318
364
  autoMigrateJsonIfNeeded,
319
365
  auto_migrate_json_if_needed: autoMigrateJsonIfNeeded,
320
366
  getDbConnection,
package/src/db_schema.js CHANGED
@@ -11,17 +11,19 @@ const {
11
11
  const { CORE_SCHEMA_DDL } = require('./schema_ddl');
12
12
  const { createAndVerifyPreMigrationBackup } = require('./db_migration_safety');
13
13
  const { hasCanonicalMemoryBrainLayout, applyMemoryBrainMigration } = require('./memory_brain_ddl');
14
+ const { applyChuninKnowledgeSchema } = require('./chunin_knowledge_ddl');
14
15
  const {
15
16
  _renameLegacyClaudeHarnessLabel,
16
17
  _mergeLegacyAgyClientRows
17
18
  } = require('./db_schema_repairs');
18
19
 
19
- const CURRENT_SCHEMA_VERSION = 9;
20
+ const CURRENT_SCHEMA_VERSION = 11;
20
21
  const _ensuredSchemaInodes = new Map();
21
22
  const REQUIRED_FAST_SCHEMA_TABLES = [
22
23
  'skills', 'skills_fts', 'persona_memories', 'persona_memories_fts',
23
24
  'memory_audit_events', 'memory_relations',
24
25
  'projects', 'active_sessions', 'tool_calls', 'agents',
26
+ 'provider_usage',
25
27
  'bridges', 'sdlc_tasks', 'code_edges', 'assets', 'generation_jobs'
26
28
  ];
27
29
 
@@ -92,6 +94,10 @@ function _hasAllRequiredTables(conn) {
92
94
  if (!REQUIRED_FAST_SCHEMA_TABLES.every((t) => existing.has(t))) return false;
93
95
  if (existing.has('code_chunks') && !hasCanonicalCodeChunksLayout(conn)) return false;
94
96
  if (existing.has('persona_memories') && !hasCanonicalMemoryBrainLayout(conn)) return false;
97
+ if (existing.has('bridges')) {
98
+ const bridgeCols = new Set(conn.prepare('PRAGMA table_info(bridges)').all().map((c) => c.name));
99
+ if (!bridgeCols.has('supports_stream_usage')) return false;
100
+ }
95
101
  return _hasRequiredAgentSchema(conn);
96
102
  }
97
103
 
@@ -409,7 +415,8 @@ function _applyCoreColumnAndIndexMigrations(conn, ftsSupported) {
409
415
  "ALTER TABLE projects ADD COLUMN agent_input_token_quota INTEGER DEFAULT 100000;",
410
416
  "ALTER TABLE tool_calls ADD COLUMN cached_tokens INTEGER;",
411
417
  "ALTER TABLE tool_calls ADD COLUMN input_tokens INTEGER;",
412
- "ALTER TABLE tool_calls ADD COLUMN output_tokens INTEGER;"
418
+ "ALTER TABLE tool_calls ADD COLUMN output_tokens INTEGER;",
419
+ "ALTER TABLE bridges ADD COLUMN supports_stream_usage INTEGER;"
413
420
  ];
414
421
  for (const sql of colSqls) _tryExecSql(conn, sql);
415
422
  _ensureAgentsColumns(conn);
@@ -421,6 +428,8 @@ function _applyCoreColumnAndIndexMigrations(conn, ftsSupported) {
421
428
  CREATE INDEX IF NOT EXISTS idx_tool_calls_agent ON tool_calls(agent);
422
429
  CREATE INDEX IF NOT EXISTS idx_tool_calls_client ON tool_calls(client);
423
430
  CREATE INDEX IF NOT EXISTS idx_tool_calls_timestamp ON tool_calls(timestamp);
431
+ CREATE INDEX IF NOT EXISTS idx_provider_usage_timestamp ON provider_usage(timestamp);
432
+ CREATE INDEX IF NOT EXISTS idx_provider_usage_source ON provider_usage(source);
424
433
  CREATE INDEX IF NOT EXISTS idx_projects_path ON projects(project_path);
425
434
  CREATE INDEX IF NOT EXISTS idx_mem_agent ON persona_memories(agent_name);
426
435
  CREATE INDEX IF NOT EXISTS idx_mem_type ON persona_memories(memory_type);
@@ -525,6 +534,8 @@ function setupSchema(conn, backupDatabaseFn = null) {
525
534
  _applyCodeIntelligenceMigration(conn, ftsSupported);
526
535
  // Migration v8: provenance-aware knowledge brain tables & additive columns.
527
536
  applyMemoryBrainMigration(conn);
537
+ // Migration v11: Chunin research knowledge store (FTS5 + vector column).
538
+ applyChuninKnowledgeSchema(conn);
528
539
  _verifyPostMigrationOrThrow(conn);
529
540
 
530
541
  setUserVersion(conn, CURRENT_SCHEMA_VERSION);
@@ -583,6 +594,7 @@ function validateCanonicalSchema(conn) {
583
594
  // Assert presence of mandatory canonical tables
584
595
  const requiredTables = [
585
596
  'skills', 'skill_chunks', 'tool_calls', 'active_sessions',
597
+ 'provider_usage',
586
598
  'agents', 'bridges', 'projects', 'sdlc_tasks', 'persona_memories',
587
599
  'memory_audit_events', 'memory_relations',
588
600
  'telegram_config', 'webhooks', 'prompt_queue', 'telegram_session_targets',