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
@@ -47,6 +47,10 @@ function normalizeTodoItems(tasks = [], status = {}) {
47
47
  if (rawStatus === 'completed' || rawStatus === 'done') mappedStatus = 'completed';
48
48
  else if (rawStatus === 'in_progress' || rawStatus === 'running') mappedStatus = 'in_progress';
49
49
  else if (['unverified', 'failed', 'rejected', 'blocked'].includes(rawStatus)) mappedStatus = rawStatus;
50
+ // `spawn_pending` is a real state, not a typo: the slice has a directive the
51
+ // client must run and is only completed by `report_from_agent`. Mapping it to
52
+ // `pending` here erased the marker on every sync and hid the waiting spawn.
53
+ else if (rawStatus === 'spawn_pending') mappedStatus = 'spawn_pending';
50
54
  const text = base.task || base.content || base.description || `Step ${idx + 1}`;
51
55
  return {
52
56
  ...base,
@@ -196,6 +200,9 @@ function applyAgentReportToTodos(workflowStatus, cleanAgent, dispatchId, finalSt
196
200
 
197
201
  if (finalStatus === 'completed' || finalStatus === 'unverified') {
198
202
  task.status = finalStatus;
203
+ // A report without passing validation evidence cannot have produced a
204
+ // finished child: `completed` requires the evidence gate to have passed.
205
+ task.spawn_state = finalStatus === 'completed' ? 'completed' : 'directive_only';
199
206
  task.result = updateData.summary || '';
200
207
  task.validation = updateData.validation || [];
201
208
  task.verified = updateData.verified;
@@ -326,6 +326,22 @@ function _mergeSanninGraphResponse(parsedSannin, graphInitRes, threadId) {
326
326
  };
327
327
  }
328
328
 
329
+ // A slice that only has a spawn directive is not routed work: the client has to
330
+ // run the directive and report back. Answering it with the routing envelope made
331
+ // the caller believe a subagent had been dispatched.
332
+ if (graphInitRes.spawnPending) {
333
+ return {
334
+ ...parsedSannin,
335
+ status: 'spawn_pending',
336
+ phase: graphInitRes.phase,
337
+ spawn_pending: graphInitRes.spawn_pending || (wfStatus && wfStatus.spawn_pending) || [],
338
+ next_action: 'spawn_and_report',
339
+ resume_node: 'node_execute',
340
+ langgraph_checkpoint: checkpoint,
341
+ workflow_state: typeof graphInitRes.status === 'object' ? graphInitRes.status : undefined
342
+ };
343
+ }
344
+
329
345
  if (parsedSannin.status === 'routed') {
330
346
  return {
331
347
  ...graphInitRes,
@@ -150,7 +150,12 @@ function extractModifiedFiles(tasks) {
150
150
  function formatTaskSummary(tasks) {
151
151
  const list = (tasks || []).slice(0, 5);
152
152
  return list.map(t => {
153
- const res = (t.result || 'Completed').replace(/\n+/g, ' ').trim();
153
+ // Executor slices report `summary`; agent reports use `result`. Either may
154
+ // arrive as a non-string (object payload), which used to throw here and
155
+ // took the whole review node down.
156
+ const raw = typeof t.result === 'string' ? t.result
157
+ : (typeof t.summary === 'string' ? t.summary : 'Completed');
158
+ const res = raw.replace(/\n+/g, ' ').trim();
154
159
  const short = res.length > 60 ? res.slice(0, 57) + '...' : res;
155
160
  return `• [${t.agent || 'agent'}] ${t.task}: ${short}`;
156
161
  }).join('\n');
@@ -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);
@@ -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
  {
@@ -1290,6 +1291,9 @@
1290
1291
  "dispatch_id": {
1291
1292
  "type": "string"
1292
1293
  },
1294
+ "task_id": {
1295
+ "type": "string"
1296
+ },
1293
1297
  "validation": {
1294
1298
  "type": "array",
1295
1299
  "items": {
@@ -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.24)
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.24)
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.
@@ -36,7 +36,7 @@ In the Konoha workflow, Kage exercises executive technical authority across two
36
36
  - **Two-Step Zero-AI-Slop Review (TARGET 100/100)**:
37
37
  - **Step 1 — `aislop_scan`**: Scans changed files via CLI `rtk aislop scan --changes` (or MCP tool with explicit paths). Zero findings of any severity are permitted.
38
38
  - **Step 2 — `anti-slop` Rule Review**: Loads the vendored `antislop` skill via `konoha.get_skill("antislop")` and verifies adherence to craftmanship standards and Delivery Gate rules.
39
- - **Socket Supply Chain Security Gate**: When maintaining Konoha itself, Kage verifies that `rtk socket ci` or `rtk socket scan create ./package.json --report` is 100% clean of High and Medium risk alerts (0 High/Error, 0 Medium/Warn).
39
+ - **Supply Chain Dependency Audit Gate**: When maintaining Konoha itself, Kage verifies that `rtk node tests/test_dependency_audit.js` passes: `pnpm audit --json` over the root and `apps/web` workspaces with zero unapproved advisories, no Socket account or token involved. The optional Socket.dev scan (`rtk node scripts/socket_audit_optional.js`, needs `SOCKET_CLI_API_TOKEN`) is advisory only and its `SKIPPED`/`UNVERIFIED` output is never a delivery blocker.
40
40
  - **Test Directory Discovery & Single-Directory Invariant**: Explore existing test directories (`tests/`, `test/`, `spec/`) using `find_files_clean`. Always place new tests within the established directory. NEVER create duplicate or conflicting test folders.
41
41
  - **Workspace Hygiene & Post-Approval Cleanup**: All temporary debug scripts (`debug_*`, `temp_*`, `test_patch.py`, `scratch/*`) must be removed upon final approval so the repository remains production-clean.
42
42