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
@@ -1,7 +1,10 @@
1
1
  'use strict';
2
2
 
3
+ const fs = require('fs');
3
4
  const path = require('path');
5
+ const crypto = require('crypto');
4
6
  const { saveWorkflowStatus, cleanupTransientScratchFiles } = require('./workflow_common');
7
+ const { extractModifiedFiles, formatTaskSummary } = require('./workflow_completion_helpers');
5
8
  const { syncTodoAndWalkthrough } = require('./todo_walkthrough_sync');
6
9
  const { buildPickerBinding } = require('./hitl_picker');
7
10
  const { slicePreservingHeadMiddleTail } = require('../context_budget');
@@ -129,6 +132,8 @@ function buildPromptPayload({
129
132
  title,
130
133
  question,
131
134
  choices,
135
+ implemented,
136
+ modified_files: modifiedFiles,
132
137
  options
133
138
  }) {
134
139
  return {
@@ -139,6 +144,8 @@ function buildPromptPayload({
139
144
  input_mode: 'reply_with_option_label',
140
145
  choices,
141
146
  refinement_option: CUSTOM_CHOICE_LABEL,
147
+ ...(implemented === undefined ? {} : { implemented }),
148
+ ...(modifiedFiles === undefined ? {} : { modified_files: modifiedFiles }),
142
149
  options
143
150
  };
144
151
  }
@@ -182,8 +189,95 @@ function _serializeHitlPromptEnvelope(baseFields, { stage, gateName, choices, st
182
189
  });
183
190
  }
184
191
 
192
+ /**
193
+ * Gate 1 is the only moment the approved plan exists as text before execution.
194
+ * Persist the compiled plan as the authoritative plan.md artifact next to
195
+ * `final_report.md` so it survives compaction and the approver can open it.
196
+ *
197
+ * Task dirs are shared with clients, so `plan.md` may be pre-created by someone
198
+ * else — possibly as a symlink or a hard link to a file outside the task dir.
199
+ * Validation-by-path alone is racy, so two rules apply: an existing artifact is
200
+ * only accepted after the opened descriptor proves it is the same regular,
201
+ * singly linked file that was inspected, and the new text is written to a fresh
202
+ * inode that is then renamed over `plan.md`. A rename replaces the directory
203
+ * entry without following it, so even a link that slipped past inspection can
204
+ * never carry the bytes into another file.
205
+ * Write failures must never block the gate itself.
206
+ */
207
+ const PLAN_ARTIFACT_NAME = 'plan.md';
208
+
209
+ /** True when `plan.md` is absent or a regular, singly linked file we may replace. */
210
+ function _isReplaceableArtifact(planPath, nofollow) {
211
+ let before;
212
+ try {
213
+ before = fs.lstatSync(planPath);
214
+ } catch (err) {
215
+ if (err.code === 'ENOENT') return true;
216
+ throw err;
217
+ }
218
+ // lstat does not follow the final component, so a symlink — dangling or not —
219
+ // and a directory or device all fail here instead of being written through.
220
+ if (!before.isFile()) return false;
221
+ const fd = fs.openSync(planPath, fs.constants.O_WRONLY | nofollow);
222
+ try {
223
+ const opened = fs.fstatSync(fd);
224
+ // Opening by path can land on a different inode than lstat inspected (a
225
+ // swap in between), so the descriptor has to prove its identity. O_NOFOLLOW
226
+ // makes the open itself refuse a link where the platform supports it; the
227
+ // inode comparison covers platforms that do not.
228
+ if (!opened.isFile() || opened.dev !== before.dev || opened.ino !== before.ino) return false;
229
+ // A reported inode of 0 is not an identity, and without O_NOFOLLOW nothing
230
+ // else proves the descriptor is the inspected file.
231
+ if (!nofollow && (before.ino === 0 || opened.ino === 0)) return false;
232
+ // A hard link shares the inode, so every check above still passes while a
233
+ // truncate would land in a file outside the task dir. The artifact is only
234
+ // ever created singly linked, so a second name belongs to someone else.
235
+ // Refusing is the conservative choice; the rename below would be safe even
236
+ // where a filesystem under-reports this count.
237
+ return opened.nlink === 1;
238
+ } finally {
239
+ fs.closeSync(fd);
240
+ }
241
+ }
242
+
243
+ /** Write `text` to a fresh inode and rename it over `planPath`. */
244
+ function _replacePlanArtifact(planPath, text) {
245
+ const tmpPath = `${planPath}.${process.pid}.${crypto.randomUUID()}.tmp`;
246
+ const fd = fs.openSync(tmpPath, fs.constants.O_WRONLY | fs.constants.O_CREAT | fs.constants.O_EXCL, 0o644);
247
+ try {
248
+ fs.writeFileSync(fd, text, 'utf8');
249
+ } finally {
250
+ fs.closeSync(fd);
251
+ }
252
+ try {
253
+ fs.renameSync(tmpPath, planPath);
254
+ } catch (err) {
255
+ try { fs.unlinkSync(tmpPath); } catch (_) { /* temp file already gone */ }
256
+ throw err;
257
+ }
258
+ }
259
+
260
+ function writePlanArtifact(resolvedTaskDir, planText) {
261
+ const text = String(planText === undefined || planText === null ? '' : planText);
262
+ if (!resolvedTaskDir || !text.trim()) return null;
263
+ const nofollow = fs.constants.O_NOFOLLOW || 0;
264
+ try {
265
+ fs.mkdirSync(resolvedTaskDir, { recursive: true });
266
+ // Canonicalize after creation so a directory symlink resolves to the real
267
+ // task dir and the artifact can never be placed relative to a link.
268
+ const taskDir = fs.realpathSync(resolvedTaskDir);
269
+ const planPath = path.join(taskDir, PLAN_ARTIFACT_NAME);
270
+ if (!_isReplaceableArtifact(planPath, nofollow)) return null;
271
+ _replacePlanArtifact(planPath, text);
272
+ return planPath;
273
+ } catch (_) {
274
+ return null;
275
+ }
276
+ }
277
+
185
278
  function buildGate1Prompt(status, resolvedTaskDir, rootTaskId, planContent, options = {}) {
186
279
  const planText = planContent || status.plan || '';
280
+ const planPath = writePlanArtifact(resolvedTaskDir, planText);
187
281
  const choices = [...GATE1_CHOICES, CUSTOM_CHOICE_LABEL];
188
282
  const promptPayload = buildPromptPayload({
189
283
  gate: 'gate_1',
@@ -214,14 +308,15 @@ function buildGate1Prompt(status, resolvedTaskDir, rootTaskId, planContent, opti
214
308
  ]
215
309
  });
216
310
 
217
- const message = 'Action plan compiled. Execution paused awaiting human plan approval (Gate 1).\n\n' +
218
- 'Reply with the option label (or its number):\n' +
311
+ const message = 'Action plan compiled. Execution paused awaiting human plan approval (Gate 1).\n' +
312
+ (planPath ? `\nFull plan written to ${planPath}\n\n${String(planText).trim()}\n` : '\n' + String(planText).trim() + '\n') +
313
+ '\nReply with the option label (or its number):\n' +
219
314
  renderChoiceList(choices) +
220
315
  '\n\nChoosing "' + CUSTOM_CHOICE_LABEL + '" lets you type any instruction, e.g.: ' +
221
316
  CUSTOM_CHOICE_LABEL + ': use Postgres instead of SQLite';
222
317
 
223
318
  return _serializeHitlPromptEnvelope(
224
- { status: 'pending_plan_approval', phase: 'plan_approval', plan: planText, tasks: status.tasks || [] },
319
+ { status: 'pending_plan_approval', phase: 'plan_approval', plan: planText, plan_path: planPath, tasks: status.tasks || [] },
225
320
  { stage: 'gate1', gateName: 'Gate 1 (Plan Approval)', choices, status, resolvedTaskDir, taskId: rootTaskId, message, promptPayload, client: options.client }
226
321
  );
227
322
  }
@@ -230,6 +325,16 @@ function buildGate2Prompt(status, resolvedTaskDir, rootId, options = {}) {
230
325
  const confidenceVal = options.confidence !== undefined ? options.confidence : 100;
231
326
  const reportPath = options.report;
232
327
  const finalReport = reportPath || status?.report || '';
328
+ // Gate 2 asks a human to accept shipped work. Enumerate what actually landed
329
+ // so the approval is about the delivery, not only the confidence number.
330
+ const tasks = Array.isArray(status && status.tasks) ? status.tasks : [];
331
+ const doneTasks = tasks.filter(t => {
332
+ const s = String((t && t.status) || '').toLowerCase();
333
+ return s === 'completed' || s === 'done';
334
+ });
335
+ const implemented = formatTaskSummary(doneTasks) || 'No completed tasks recorded.';
336
+ const modifiedFiles = extractModifiedFiles(doneTasks);
337
+ const fileList = modifiedFiles.length > 0 ? modifiedFiles.map(f => `- ${f}`).join('\n') : '- none reported';
233
338
  const choices = [...GATE2_CHOICES, CUSTOM_CHOICE_LABEL];
234
339
  const promptPayload = buildPromptPayload({
235
340
  gate: 'gate_2',
@@ -237,6 +342,8 @@ function buildGate2Prompt(status, resolvedTaskDir, rootId, options = {}) {
237
342
  title: 'Gate 2: Delivery Sign-Off Required',
238
343
  question: `Kage review completed (${confidenceVal}% Confidence). Delivery paused awaiting human sign-off (Gate 2). How would you like to proceed?`,
239
344
  choices,
345
+ implemented,
346
+ modified_files: modifiedFiles,
240
347
  options: [
241
348
  {
242
349
  id: '1',
@@ -261,13 +368,15 @@ function buildGate2Prompt(status, resolvedTaskDir, rootId, options = {}) {
261
368
  });
262
369
 
263
370
  const message = `Kage review completed (${confidenceVal}% Confidence). Delivery paused awaiting human sign-off (Gate 2).\n\n` +
371
+ `Implemented:\n${implemented}\n\n` +
372
+ `Modified files:\n${fileList}\n\n` +
264
373
  'Reply with the option label (or its number):\n' +
265
374
  renderChoiceList(choices) +
266
375
  '\n\nChoosing "' + CUSTOM_CHOICE_LABEL + '" lets you type the exact fix you want, e.g.: ' +
267
376
  CUSTOM_CHOICE_LABEL + ': add integration tests for the upload path';
268
377
 
269
378
  return _serializeHitlPromptEnvelope(
270
- { status: 'pending_human_signoff', phase: 'delivery_signoff', confidence: confidenceVal, report: finalReport },
379
+ { status: 'pending_human_signoff', phase: 'delivery_signoff', confidence: confidenceVal, report: finalReport, implemented, modified_files: modifiedFiles },
271
380
  { stage: 'gate2', gateName: 'Gate 2 (Delivery Sign-Off)', choices, status, resolvedTaskDir, taskId: rootId, message, promptPayload, client: options.client }
272
381
  );
273
382
  }
@@ -493,5 +602,9 @@ module.exports = {
493
602
  parseGateChoice,
494
603
  applyGate1Choice,
495
604
  applyGate2Choice,
496
- compactPostApprovalContext
605
+ compactPostApprovalContext,
606
+ // Internals, exported so the platform-specific branches can be exercised on a
607
+ // host that has O_NOFOLLOW (Windows coverage without a Windows runner).
608
+ _isReplaceableArtifact,
609
+ _replacePlanArtifact
497
610
  };
@@ -593,11 +593,17 @@ function _finalizeSanninDispatch(prep, envelope) {
593
593
  : '';
594
594
 
595
595
  const currentSt = loadWorkflowStatus(resolvedTaskDir);
596
+ // Tasks are owned by the plan (Gate 1) and by the slices that report into them.
597
+ // Re-seeding them from the route on every call reset finished work to pending, so
598
+ // a resumed call re-dispatched a slice whose child had already run.
599
+ const existingTasks = Array.isArray(currentSt.tasks) ? currentSt.tasks : [];
596
600
  const syncBundle = syncTodoAndWalkthrough(currentSt, {
597
601
  client: actClient, taskDir: resolvedTaskDir, taskId,
598
- tasks: parallelWorkstreams.length > 1
599
- ? parallelWorkstreams.map((ws, i) => ({ id: `task_${i + 1}`, task: `${effPrompt} (${ws.domain} slice)`, agent: ws.agent, status: 'pending' }))
600
- : [{ id: 'task_1', task: effPrompt, agent: selectedAgent, status: 'in_progress' }]
602
+ tasks: existingTasks.length > 0
603
+ ? undefined
604
+ : (parallelWorkstreams.length > 1
605
+ ? parallelWorkstreams.map((ws, i) => ({ id: `task_${i + 1}`, task: `${effPrompt} (${ws.domain} slice)`, agent: ws.agent, status: 'pending' }))
606
+ : [{ id: 'task_1', task: effPrompt, agent: selectedAgent, status: 'in_progress' }])
601
607
  });
602
608
  const advisorSupervisor = initAdvisorSessionSupervisor({ client: spawnClient, status: currentSt, goal: effPrompt, todos: syncBundle.todos });
603
609
  saveWorkflowStatus(resolvedTaskDir, currentSt);
@@ -297,6 +297,35 @@ function buildSubagentToolGrants(client = 'generic', agent = null) {
297
297
  ];
298
298
  }
299
299
 
300
+ const PI_READONLY_BUILTINS = Object.freeze(['read', 'grep', 'find', 'ls']);
301
+
302
+ const PI_WRITE_BUILTINS = Object.freeze(['read', 'write', 'edit', 'bash', 'grep', 'find', 'ls']);
303
+
304
+ /**
305
+ * Tool grants in the spelling Pi itself uses.
306
+ *
307
+ * Pi registers builtins in lowercase (`read`, `grep`, `find`, `ls`) and selects MCP
308
+ * tools as `mcp:server/tool`. pi-subagents treats `tools` as a strict allowlist and
309
+ * rejects the launch when a listed name does not resolve, so the `mcp__server__tool`
310
+ * form the other clients use would fail every Pi child.
311
+ */
312
+ function buildPiSubagentToolGrants(agent = null) {
313
+ const { isReadOnlyAgent } = require('../agent_file_safety');
314
+ const readOnly = isReadOnlyAgent(agent);
315
+ const { GENIN_BLOCKED_TOOLS } = readOnly
316
+ ? require('../mcp/genin_guard')
317
+ : { GENIN_BLOCKED_TOOLS: [] };
318
+ const blockedMcp = new Set(GENIN_BLOCKED_TOOLS);
319
+
320
+ const konoha = (deployUtils.KONOHA_CANONICAL_TOOLS || [])
321
+ .filter((t) => !readOnly || !blockedMcp.has(t))
322
+ .map((t) => `mcp:konoha/${t}`);
323
+ const aislopSource = readOnly ? READONLY_AISLOP_TOOLS : SUBAGENT_SAFE_MCP_GRANTS.aislop;
324
+ const aislop = aislopSource.map((t) => `mcp:aislop/${t}`);
325
+
326
+ return [...konoha, ...aislop, ...(readOnly ? PI_READONLY_BUILTINS : PI_WRITE_BUILTINS)];
327
+ }
328
+
300
329
  function buildCommandCodeTools(agent = null) {
301
330
  const { isReadOnlyAgent, isRouterAgent } = require('../agent_file_safety');
302
331
  const readOnly = isReadOnlyAgent(agent);
@@ -380,6 +409,8 @@ module.exports = {
380
409
  backupFile,
381
410
  buildClientToolGrants,
382
411
  buildBareToolGrants,
412
+ buildPiSubagentToolGrants,
413
+ PI_READONLY_BUILTINS,
383
414
  MAIN_AGENT_BUILTIN_TOOLS,
384
415
  SUBAGENT_SAFE_MCP_GRANTS,
385
416
  getKonohaMappedTools,
@@ -1043,7 +1043,8 @@
1043
1043
  ],
1044
1044
  "description": "Compute device preference; falls back to CPU when no GPU is available."
1045
1045
  }
1046
- }
1046
+ },
1047
+ "additionalProperties": false
1047
1048
  }
1048
1049
  },
1049
1050
  {
@@ -1138,6 +1139,30 @@
1138
1139
  },
1139
1140
  "flow_hash": {
1140
1141
  "type": "string"
1142
+ },
1143
+ "breadth": {
1144
+ "type": "number",
1145
+ "minimum": 1,
1146
+ "maximum": 5,
1147
+ "description": "Queries per level in the deep-research loop (default 3, max 5)."
1148
+ },
1149
+ "depth": {
1150
+ "type": "number",
1151
+ "minimum": 1,
1152
+ "maximum": 3,
1153
+ "description": "Levels to recurse (default 2, max 3). nextBreadth = ceil(breadth / 2)."
1154
+ },
1155
+ "output_mode": {
1156
+ "type": "string",
1157
+ "enum": [
1158
+ "report",
1159
+ "concise"
1160
+ ],
1161
+ "description": "Report keeps citations and follow-ups; concise returns learnings only."
1162
+ },
1163
+ "use_knowledge_cache": {
1164
+ "type": "boolean",
1165
+ "description": "Retrieve the top-5 stored references before searching the web (default true)."
1141
1166
  }
1142
1167
  },
1143
1168
  "additionalProperties": false
@@ -1290,6 +1315,9 @@
1290
1315
  "dispatch_id": {
1291
1316
  "type": "string"
1292
1317
  },
1318
+ "task_id": {
1319
+ "type": "string"
1320
+ },
1293
1321
  "validation": {
1294
1322
  "type": "array",
1295
1323
  "items": {
@@ -1388,6 +1416,13 @@
1388
1416
  "standard",
1389
1417
  "deep"
1390
1418
  ]
1419
+ },
1420
+ "exclude_urls": {
1421
+ "type": "array",
1422
+ "items": {
1423
+ "type": "string"
1424
+ },
1425
+ "description": "URLs the caller already knows. Canonicalized (tracking params, trailing slash, scheme and host case) and filtered out, so only net-new results are returned."
1391
1426
  }
1392
1427
  },
1393
1428
  "required": [
@@ -0,0 +1,31 @@
1
+ 'use strict';
2
+
3
+ // Small filesystem helpers shared by the Pi integration. They live here rather
4
+ // than in pi_manager.js so that module stays under the 700-line ceiling the repo
5
+ // lints at; none of them carry Pi-specific behaviour.
6
+
7
+ const fs = require('fs');
8
+
9
+ function fileExists(p) {
10
+ try {
11
+ return fs.existsSync(p);
12
+ } catch (_) {
13
+ return false;
14
+ }
15
+ }
16
+
17
+ function readJsonSafe(filePath) {
18
+ try {
19
+ return JSON.parse(fs.readFileSync(filePath, 'utf-8'));
20
+ } catch (_) {
21
+ return null;
22
+ }
23
+ }
24
+
25
+ function ensureDirSafe(dir) {
26
+ try {
27
+ fs.mkdirSync(dir, { recursive: true });
28
+ } catch (_) { /* best effort: a failed mkdir must never crash the CLI or MCP runtime */ }
29
+ }
30
+
31
+ module.exports = { fileExists, readJsonSafe, ensureDirSafe };
package/src/pi_manager.js CHANGED
@@ -13,6 +13,7 @@ const { buildPiBlockerExtensionSource } = require('./pi_blocker_template');
13
13
  */
14
14
 
15
15
  const fs = require('fs');
16
+ const { fileExists, readJsonSafe, ensureDirSafe } = require('./pi_fs_helpers');
16
17
  const path = require('path');
17
18
  const { AISLOP_PACKAGE } = require('./uvx_runtime');
18
19
  const os = require('os');
@@ -134,6 +135,43 @@ function buildPiManagedContract() {
134
135
  * Deploys the Konoha runtime contract + Pi workflow mandate into
135
136
  * ~/.pi/agent/AGENTS.md (Pi's global context file) using managed markers.
136
137
  */
138
+ /**
139
+ * Writes one Pi agent profile per deployable agent.
140
+ *
141
+ * Pi used to receive the advisor profile only, so `subagent(agent="chunin")` had no
142
+ * definition to resolve and every delegation failed with UNSUPPORTED_NATIVE_SPAWN even
143
+ * with pi-subagents installed. Tools are written as a YAML sequence: pi-subagents reads
144
+ * `tools: read, grep, find, ls` as a single tool name and then rejects the launch.
145
+ *
146
+ * @returns {string[]} agent names written
147
+ */
148
+ function deployPiAgentProfiles(piAgentsDir, options = {}) {
149
+ const silent = options.silent !== false;
150
+ const { getDeployableAgents } = require('./canonical_agents');
151
+ const { buildSubagentContract } = require('./agent_contract');
152
+ const { writeAgentFileSafe, AGENT_OWNERSHIP_MARKER, getRoleDescription } = require('./agent_file_safety');
153
+ const { buildPiSubagentToolGrants } = require('./mcp_clients/common');
154
+ const written = [];
155
+ for (const agent of getDeployableAgents()) {
156
+ const grants = buildPiSubagentToolGrants(agent);
157
+ const description = String(getRoleDescription(agent) || '').replace(/"/g, '\\"').replace(/\n/g, ' ');
158
+ const frontmatter = [
159
+ '---',
160
+ `name: ${agent.name}`,
161
+ `description: "${description}"`,
162
+ AGENT_OWNERSHIP_MARKER,
163
+ 'tools:',
164
+ ...grants.map((t) => ` - ${t}`),
165
+ '---',
166
+ ''
167
+ ].join('\n');
168
+ const body = `${agent.instructions}\n\n${buildSubagentContract('pi')}\n`;
169
+ writeAgentFileSafe(path.join(piAgentsDir, `${agent.name}.md`), frontmatter + body, agent.name, { silent });
170
+ written.push(agent.name);
171
+ }
172
+ return written;
173
+ }
174
+
137
175
  function deployPiContract(silent = true, targetFile = null, options = {}) {
138
176
  const opts = typeof targetFile === "object" && targetFile !== null ? targetFile : options;
139
177
  const explicitTarget = typeof targetFile === "string" ? targetFile : (opts && opts.targetFile);
@@ -323,14 +361,6 @@ function removePiBlockerExtension(silent = true) {
323
361
  }
324
362
  }
325
363
 
326
- function fileExists(p) {
327
- try {
328
- return fs.existsSync(p);
329
- } catch (_) {
330
- return false;
331
- }
332
- }
333
-
334
364
  function isPiInstalled() {
335
365
  if (fileExists(path.join(HOME, '.pi', 'agent'))) return true;
336
366
  try {
@@ -343,14 +373,6 @@ function isPiInstalled() {
343
373
  }
344
374
  }
345
375
 
346
- function readJsonSafe(filePath) {
347
- try {
348
- return JSON.parse(fs.readFileSync(filePath, 'utf-8'));
349
- } catch (_) {
350
- return null;
351
- }
352
- }
353
-
354
376
  function _handleCorruptPiSettings(settingsPath, isSilent) {
355
377
  try {
356
378
  fs.copyFileSync(settingsPath, settingsPath + '.corrupt-' + Date.now());
@@ -511,14 +533,9 @@ function ensurePiSetup(options = {}) {
511
533
  const rtk = deployPiRtkRule(silent);
512
534
  const contract = deployPiContract(silent, null, options);
513
535
  const blocker = deployPiBlockerExtension(silent, options);
514
- const { getAdvisorAgentDefinition } = require('./canonical_agents');
515
- const { buildSubagentContract } = require('./agent_contract');
516
- const { writeAgentFileSafe, AGENT_OWNERSHIP_MARKER, getRoleDescription } = require('./agent_file_safety');
517
- const adv = getAdvisorAgentDefinition();
518
536
  const piAgentsDir = path.join(agentDir, 'agents');
519
537
  ensureDirSafe(piAgentsDir);
520
- const advMd = `---\nname: advisor\ndescription: "${getRoleDescription(adv)}"\ntools: read, grep, find, ls\n${AGENT_OWNERSHIP_MARKER}\n---\n\n${adv.instructions}\n\n${buildSubagentContract('pi')}\n`;
521
- writeAgentFileSafe(path.join(piAgentsDir, 'advisor.md'), advMd, 'advisor', { silent });
538
+ const deployedAgents = deployPiAgentProfiles(piAgentsDir, { silent });
522
539
 
523
540
  const projectRoot = options.projectRoot || null;
524
541
  const projMcp = projectRoot ? path.join(projectRoot, '.pi', 'mcp.json') : null;
@@ -534,6 +551,7 @@ function ensurePiSetup(options = {}) {
534
551
  return {
535
552
  ok: true,
536
553
  changed: !!(adapter.changed || contract.changed || blocker.changed),
554
+ agentsDeployed: deployedAgents,
537
555
  rtkDeployed: !!rtk.ok,
538
556
  contractDeployed: !!contract.ok,
539
557
  blockerDeployed: !!blocker.ok
@@ -591,6 +609,22 @@ function _readPiAgentsContent() {
591
609
  }
592
610
  }
593
611
 
612
+ /**
613
+ * Agent profile names present in a Pi agents directory, without the extension.
614
+ *
615
+ * @returns {string[]} sorted names, empty when the directory is absent
616
+ */
617
+ function readPiAgentProfileNames(agentsDir) {
618
+ try {
619
+ return fs.readdirSync(agentsDir)
620
+ .filter((f) => f.endsWith('.md'))
621
+ .map((f) => f.slice(0, -3))
622
+ .sort();
623
+ } catch (_) { /* absent directory: no profiles deployed yet */
624
+ return [];
625
+ }
626
+ }
627
+
594
628
  function getPiStatus(options = {}) {
595
629
  const installed = isPiInstalled();
596
630
  const { mcpKonoha, mcpAislop } = _readPiMcpServerFlags();
@@ -600,6 +634,11 @@ function getPiStatus(options = {}) {
600
634
  const agentsContent = _readPiAgentsContent();
601
635
  const rtkRuleDeployed = fileExists(PI_RTK_EXTENSION) || agentsContent.includes(RTK_BLOCK_START);
602
636
  const contractDeployed = agentsContent.includes('<!-- KONOHA-CONTRACT-START -->');
637
+ const agentDir = options.agentDir || (options.home ? path.join(options.home, '.pi', 'agent') : PI_AGENT_DIR);
638
+ const agentProfiles = readPiAgentProfileNames(path.join(agentDir, 'agents'));
639
+ const missingAgentProfiles = require('./canonical_agents')
640
+ .getDeployableAgentNames()
641
+ .filter((name) => !agentProfiles.includes(name));
603
642
 
604
643
  return {
605
644
  installed,
@@ -611,16 +650,15 @@ function getPiStatus(options = {}) {
611
650
  contractDeployed,
612
651
  blockerDeployed,
613
652
  subagentExtensionInstalled,
653
+ // A subagent extension alone cannot spawn anything: the harness also needs a
654
+ // profile per agent, which is what this field makes visible.
655
+ agentProfiles,
656
+ missingAgentProfiles,
657
+ agentRosterComplete: missingAgentProfiles.length === 0,
614
658
  configPath: PI_MCP_CONFIG
615
659
  };
616
660
  }
617
661
 
618
- function ensureDirSafe(dir) {
619
- try {
620
- fs.mkdirSync(dir, { recursive: true });
621
- } catch (_) { /* intentional best-effort fallback: failure here must never crash the CLI/MCP runtime */ }
622
- }
623
-
624
662
  module.exports = {
625
663
  PI_AGENT_DIR,
626
664
  PI_SETTINGS,
@@ -639,6 +677,8 @@ module.exports = {
639
677
  registerPiMcp,
640
678
  deployPiRtkRule,
641
679
  deployPiContract,
680
+ deployPiAgentProfiles,
681
+ readPiAgentProfileNames,
642
682
  stripStalePiMandates,
643
683
  deployPiBlockerExtension,
644
684
  removePiBlockerExtension,
@@ -0,0 +1,92 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * src/provider_usage_logger.js — persist provider-reported token usage.
5
+ *
6
+ * `tool_calls` measures how much a Konoha tool saved in bytes; it is not a
7
+ * record of what an LLM provider billed. Gateway traffic (`/v1/messages` ->
8
+ * bridge `/v1/chat/completions`) never produced a tool row at all, so
9
+ * `tool_calls.input_tokens` was NULL for every real runtime write and the
10
+ * budget report could only ever print estimates.
11
+ *
12
+ * This writer fills that hole without touching tool-call accounting:
13
+ * `queryStats`/`getSavingsReport` count every `tool_calls` row as a call, so a
14
+ * pseudo-row per gateway request would have inflated savings and per-client
15
+ * attribution. Rows land in `provider_usage` instead, which no savings query
16
+ * reads.
17
+ *
18
+ * Only a provider payload is ever written. When the provider reported nothing,
19
+ * nothing is inserted — there is no byte-derived fallback, because a fabricated
20
+ * count is worse than a missing one.
21
+ */
22
+
23
+ const { getDb } = require('./db');
24
+ const { normalizeUsage } = require('./token_usage');
25
+
26
+ /**
27
+ * The `source` column enumerates writers, per the approved plan:
28
+ * `gateway` — one bridged provider response. Two writers produce it:
29
+ * `handleAnthropicMessages` (`src/bridge/gateway_adapters.js`) and the
30
+ * per-bridge `/v1/messages` handler (`src/bridge/handlers/anthropic.js`).
31
+ * Both answer the same request shape against the same upstream population, so
32
+ * they share the value; `bridge_name` distinguishes the two.
33
+ * `tool_call` — reserved for mirroring provider usage attached to a
34
+ * `tool_calls` row. Nothing writes it today.
35
+ */
36
+ const PROVIDER_USAGE_SOURCES = Object.freeze({ GATEWAY: 'gateway', TOOL_CALL: 'tool_call' });
37
+
38
+ function closeQuietly(conn) {
39
+ if (!conn) return;
40
+ try { conn.close(); } catch (_) { /* ignore close error */ }
41
+ }
42
+
43
+ function insertRow(conn, event, measured) {
44
+ conn.prepare(`
45
+ INSERT INTO provider_usage
46
+ (source, provider, model, client, bridge_name, stream,
47
+ input_tokens, output_tokens, cached_tokens, total_tokens)
48
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
49
+ `).run(
50
+ String(event.source || PROVIDER_USAGE_SOURCES.GATEWAY).slice(0, 40),
51
+ event.provider ? String(event.provider).slice(0, 100) : null,
52
+ event.model ? String(event.model).slice(0, 200) : null,
53
+ event.client ? String(event.client).slice(0, 100) : null,
54
+ event.bridgeName ? String(event.bridgeName).slice(0, 100) : null,
55
+ event.stream ? 1 : 0,
56
+ measured.input_tokens,
57
+ measured.output_tokens,
58
+ measured.cache_read_input_tokens,
59
+ measured.total_tokens
60
+ );
61
+ }
62
+
63
+ /**
64
+ * @param {object} event
65
+ * @param {string} event.source - `gateway` | `tool_call`
66
+ * @param {object|null} event.usage - raw provider usage payload
67
+ * @param {string} [event.provider]
68
+ * @param {string} [event.model]
69
+ * @param {string} [event.client]
70
+ * @param {string} [event.bridgeName]
71
+ * @param {boolean} [event.stream]
72
+ * @param {string|null} [dbPath]
73
+ * @returns {{recorded: boolean, reason?: string}}
74
+ */
75
+ function recordProviderUsage(event = {}, dbPath = null) {
76
+ const measured = normalizeUsage(event.usage);
77
+ if (!measured.available) return { recorded: false, reason: measured.reason };
78
+
79
+ let conn = null;
80
+ try {
81
+ conn = getDb(dbPath || undefined);
82
+ insertRow(conn, event, measured);
83
+ return { recorded: true };
84
+ } catch (_) {
85
+ // Telemetry must never break a response that is already being written.
86
+ return { recorded: false, reason: 'write_failed' };
87
+ } finally {
88
+ closeQuietly(conn);
89
+ }
90
+ }
91
+
92
+ module.exports = { recordProviderUsage, PROVIDER_USAGE_SOURCES };
package/src/schema_ddl.js CHANGED
@@ -45,6 +45,21 @@ const CORE_SCHEMA_DDL = `
45
45
  PRIMARY KEY (client, workspace_root, session_id)
46
46
  );
47
47
 
48
+ CREATE TABLE IF NOT EXISTS provider_usage (
49
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
50
+ timestamp DATETIME DEFAULT CURRENT_TIMESTAMP,
51
+ source TEXT NOT NULL,
52
+ provider TEXT,
53
+ model TEXT,
54
+ client TEXT,
55
+ bridge_name TEXT,
56
+ stream INTEGER NOT NULL DEFAULT 0,
57
+ input_tokens INTEGER,
58
+ output_tokens INTEGER,
59
+ cached_tokens INTEGER,
60
+ total_tokens INTEGER
61
+ );
62
+
48
63
  CREATE TABLE IF NOT EXISTS agents (
49
64
  name TEXT PRIMARY KEY,
50
65
  icon TEXT,
@@ -69,7 +84,8 @@ const CORE_SCHEMA_DDL = `
69
84
  provider TEXT NOT NULL,
70
85
  enabled INTEGER NOT NULL DEFAULT 1,
71
86
  target_url TEXT,
72
- api_key TEXT
87
+ api_key TEXT,
88
+ supports_stream_usage INTEGER
73
89
  );
74
90
 
75
91
  CREATE TABLE IF NOT EXISTS projects (
@@ -15,7 +15,7 @@
15
15
  NEVER run destructive commands (`rm -rf`, `DROP`, `git reset`) or view secrets (`.env*`).
16
16
 
17
17
  <!-- KONOHA-CONTRACT-START -->
18
- ## Konoha runtime contract (2.2.23)
18
+ ## Konoha runtime contract (2.2.25)
19
19
  main agent on Antigravity IDE/CLI. Mandatory every turn.
20
20
  - **Konoha is mandatory**: `find_skill`/`get_skill`; no raw cat/grep.
21
21
  - **Code intelligence is mandatory**: `code_search`/`code_symbol`/`code_impact`, absolute root.
@@ -15,7 +15,7 @@
15
15
  NEVER run destructive commands (`rm -rf`, `DROP`, `git reset`) or view secrets (`.env*`).
16
16
 
17
17
  <!-- KONOHA-CONTRACT-START -->
18
- ## Konoha runtime contract (2.2.23)
18
+ ## Konoha runtime contract (2.2.25)
19
19
  main agent on Antigravity IDE/CLI. Mandatory every turn.
20
20
  - **Konoha is mandatory**: `find_skill`/`get_skill`; no raw cat/grep.
21
21
  - **Code intelligence is mandatory**: `code_search`/`code_symbol`/`code_impact`, absolute root.