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
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
@@ -16,12 +16,13 @@ const {
16
16
  _mergeLegacyAgyClientRows
17
17
  } = require('./db_schema_repairs');
18
18
 
19
- const CURRENT_SCHEMA_VERSION = 9;
19
+ const CURRENT_SCHEMA_VERSION = 10;
20
20
  const _ensuredSchemaInodes = new Map();
21
21
  const REQUIRED_FAST_SCHEMA_TABLES = [
22
22
  'skills', 'skills_fts', 'persona_memories', 'persona_memories_fts',
23
23
  'memory_audit_events', 'memory_relations',
24
24
  'projects', 'active_sessions', 'tool_calls', 'agents',
25
+ 'provider_usage',
25
26
  'bridges', 'sdlc_tasks', 'code_edges', 'assets', 'generation_jobs'
26
27
  ];
27
28
 
@@ -92,6 +93,10 @@ function _hasAllRequiredTables(conn) {
92
93
  if (!REQUIRED_FAST_SCHEMA_TABLES.every((t) => existing.has(t))) return false;
93
94
  if (existing.has('code_chunks') && !hasCanonicalCodeChunksLayout(conn)) return false;
94
95
  if (existing.has('persona_memories') && !hasCanonicalMemoryBrainLayout(conn)) return false;
96
+ if (existing.has('bridges')) {
97
+ const bridgeCols = new Set(conn.prepare('PRAGMA table_info(bridges)').all().map((c) => c.name));
98
+ if (!bridgeCols.has('supports_stream_usage')) return false;
99
+ }
95
100
  return _hasRequiredAgentSchema(conn);
96
101
  }
97
102
 
@@ -409,7 +414,8 @@ function _applyCoreColumnAndIndexMigrations(conn, ftsSupported) {
409
414
  "ALTER TABLE projects ADD COLUMN agent_input_token_quota INTEGER DEFAULT 100000;",
410
415
  "ALTER TABLE tool_calls ADD COLUMN cached_tokens INTEGER;",
411
416
  "ALTER TABLE tool_calls ADD COLUMN input_tokens INTEGER;",
412
- "ALTER TABLE tool_calls ADD COLUMN output_tokens INTEGER;"
417
+ "ALTER TABLE tool_calls ADD COLUMN output_tokens INTEGER;",
418
+ "ALTER TABLE bridges ADD COLUMN supports_stream_usage INTEGER;"
413
419
  ];
414
420
  for (const sql of colSqls) _tryExecSql(conn, sql);
415
421
  _ensureAgentsColumns(conn);
@@ -421,6 +427,8 @@ function _applyCoreColumnAndIndexMigrations(conn, ftsSupported) {
421
427
  CREATE INDEX IF NOT EXISTS idx_tool_calls_agent ON tool_calls(agent);
422
428
  CREATE INDEX IF NOT EXISTS idx_tool_calls_client ON tool_calls(client);
423
429
  CREATE INDEX IF NOT EXISTS idx_tool_calls_timestamp ON tool_calls(timestamp);
430
+ CREATE INDEX IF NOT EXISTS idx_provider_usage_timestamp ON provider_usage(timestamp);
431
+ CREATE INDEX IF NOT EXISTS idx_provider_usage_source ON provider_usage(source);
424
432
  CREATE INDEX IF NOT EXISTS idx_projects_path ON projects(project_path);
425
433
  CREATE INDEX IF NOT EXISTS idx_mem_agent ON persona_memories(agent_name);
426
434
  CREATE INDEX IF NOT EXISTS idx_mem_type ON persona_memories(memory_type);
@@ -583,6 +591,7 @@ function validateCanonicalSchema(conn) {
583
591
  // Assert presence of mandatory canonical tables
584
592
  const requiredTables = [
585
593
  'skills', 'skill_chunks', 'tool_calls', 'active_sessions',
594
+ 'provider_usage',
586
595
  'agents', 'bridges', 'projects', 'sdlc_tasks', 'persona_memories',
587
596
  'memory_audit_events', 'memory_relations',
588
597
  'telegram_config', 'webhooks', 'prompt_queue', 'telegram_session_targets',
@@ -372,15 +372,23 @@ function loadBridgesFromMcp() {
372
372
  try {
373
373
  const db = require("./db");
374
374
  conn = db.getConnection();
375
- const rows = conn.prepare("SELECT name, port, provider, enabled, target_url AS targetUrl, api_key AS apiKey FROM bridges").all();
376
- const existing = rows.map(r => ({
377
- name: r.name,
378
- port: r.port,
379
- provider: r.provider,
380
- enabled: Boolean(r.enabled),
381
- targetUrl: r.targetUrl,
382
- apiKey: r.apiKey
383
- }));
375
+ const rows = conn.prepare("SELECT name, port, provider, enabled, target_url AS targetUrl, api_key AS apiKey, supports_stream_usage AS supportsStreamUsage FROM bridges").all();
376
+ const existing = rows.map(r => {
377
+ const bridge = {
378
+ name: r.name,
379
+ port: r.port,
380
+ provider: r.provider,
381
+ enabled: Boolean(r.enabled),
382
+ targetUrl: r.targetUrl,
383
+ apiKey: r.apiKey
384
+ };
385
+ // Only an explicit stored override becomes a boolean; `undefined` keeps
386
+ // the provider allowlist in charge.
387
+ if (r.supportsStreamUsage !== null && r.supportsStreamUsage !== undefined) {
388
+ bridge.supportsStreamUsage = Boolean(r.supportsStreamUsage);
389
+ }
390
+ return bridge;
391
+ });
384
392
  for (const b of existing) {
385
393
  validateBridgeTargetUrl(b);
386
394
  }
@@ -378,7 +378,9 @@ function syncAllGlobalClientSkills(options = {}) {
378
378
  clientsSynced: []
379
379
  };
380
380
 
381
- const requestedClients = Array.isArray(options.clients) && options.clients.length > 0 && !options.clients.includes('all')
381
+ // `undefined`/`null` = every target; an explicit array means exactly those
382
+ // clients (plus the shared `global` dir). An empty array is a valid "none".
383
+ const requestedClients = Array.isArray(options.clients) && !options.clients.includes('all')
382
384
  ? new Set(['global', ...options.clients])
383
385
  : null;
384
386
 
@@ -55,6 +55,9 @@ function dispatchRouter(state) {
55
55
  function executeRouter(state) {
56
56
  if (state.error || state.phase === 'error') return 'node_error';
57
57
  if (state.budgetExceeded) return 'node_budget_exceeded';
58
+ // No child ran, so there is nothing to review: end the turn and let the client
59
+ // spawn the directive and report back. Resuming re-enters node_execute.
60
+ if (state.spawnPending) return '__end__';
58
61
  if (state.phase === 'document') return 'node_dispatch';
59
62
  return 'node_review';
60
63
  }
@@ -7,6 +7,7 @@ const { KonohaCheckpointSaver } = require('./checkpointer');
7
7
  const { getDb } = require('../../db');
8
8
  const { normalizeTokenBudget } = require('./token_guard');
9
9
  const { wrapGuardedNode } = require('./node_guard');
10
+ const { setSliceExecutor, getSliceExecutor, clearSliceExecutor } = require('./slice_executor_registry');
10
11
 
11
12
  // macOS and Windows use case-insensitive filesystems, so a require('./nodes/Plan')
12
13
  // typed against a plan.js on disk resolves locally but fails on Linux CI and on
@@ -118,6 +119,7 @@ function createGraphBuilder() {
118
119
  node_budget_exceeded: 'node_budget_exceeded',
119
120
  node_dispatch: 'node_dispatch',
120
121
  node_review: 'node_review',
122
+ __end__: '__end__',
121
123
  })
122
124
 
123
125
  .addConditionalEdges('node_review', reviewRouter, {
@@ -272,7 +274,8 @@ async function runKonohaGraph(input, options = {}) {
272
274
 
273
275
  const turnIndex = await resolveTurnIndex(graph, config, threadId);
274
276
 
275
- const { resumeNode: _stripResume, ...restInput } = input || {};
277
+ // eslint-disable-next-line no-unused-vars
278
+ const { resumeNode: _stripResume, sliceExecutor: _stripExecutor, ...restInput } = input || {};
276
279
 
277
280
  const invokeInput = {
278
281
  ...restInput,
@@ -288,8 +291,24 @@ async function runKonohaGraph(input, options = {}) {
288
291
  invokeInput.tokenBudget = explicitBudget;
289
292
  }
290
293
 
291
- const rawResult = await graph.invoke(invokeInput, config);
292
- return formatGraphOutput(rawResult);
294
+ // A caller may hand the executor either beside the input or inside it; both are
295
+ // accepted because the state schema cannot carry a function through the
296
+ // checkpointer, so it never becomes a channel either way.
297
+ const executor = typeof options.sliceExecutor === 'function'
298
+ ? options.sliceExecutor
299
+ : (typeof input?.sliceExecutor === 'function' ? input.sliceExecutor : null);
300
+ const hasExecutor = executor !== null;
301
+ const priorExecutor = getSliceExecutor(threadId);
302
+ if (hasExecutor) setSliceExecutor(threadId, executor);
303
+ try {
304
+ const rawResult = await graph.invoke(invokeInput, config);
305
+ return formatGraphOutput(rawResult);
306
+ } finally {
307
+ if (hasExecutor) {
308
+ if (priorExecutor) setSliceExecutor(threadId, priorExecutor);
309
+ else clearSliceExecutor(threadId);
310
+ }
311
+ }
293
312
  }
294
313
 
295
314
  module.exports = {
@@ -68,6 +68,8 @@ async function dispatchNode(state) {
68
68
  skills,
69
69
  turn_budget: state.tokenBudget || 8192,
70
70
  spawn_directive: spawnDirective,
71
+ // The MCP runner prepares a directive; it never starts the child.
72
+ spawn_state: 'directive_only',
71
73
  advisor_steers: steerCtx.pending.length > 0 ? steerCtx.pending : undefined,
72
74
  todo: {
73
75
  id: d.task_id,
@@ -131,6 +133,7 @@ async function dispatchNode(state) {
131
133
  prompt: taskPrompt,
132
134
  worktree: parsed.worktree_path ? { worktree_path: parsed.worktree_path, branch: parsed.branch, base_sha: parsed.base_sha } : null
133
135
  });
136
+ parsed.spawn_state = 'directive_only';
134
137
  if (steerCtx.pending.length > 0) parsed.advisor_steers = steerCtx.pending;
135
138
  if (status.advisor_supervisor) parsed.advisor_supervisor = status.advisor_supervisor;
136
139
  if (parsed.task_id || parsed.task) {
@@ -10,6 +10,7 @@ const { normalizeAgentName } = require('../../../canonical_agents');
10
10
  const { getActiveClient } = require('../../runtime_state');
11
11
  const { detectActiveClient, resolveFirstSpawnClient } = require('../../client_detection');
12
12
  const { finalizeNodeResult } = require('../budget');
13
+ const { getSliceExecutor } = require('../slice_executor_registry');
13
14
  const { syncTodoAndWalkthrough } = require('../../todo_walkthrough_sync');
14
15
  const worktree = require('../../worktree_isolation');
15
16
 
@@ -21,6 +22,15 @@ function recordCompletedDispatch(status, dispatchId) {
21
22
  }
22
23
  }
23
24
 
25
+ function _branchFailed(branchResult) {
26
+ if (!branchResult) return false;
27
+ if (branchResult.spawn_state) return branchResult.spawn_state === 'failed';
28
+ return branchResult.status === 'failed'
29
+ || branchResult.status === 'error'
30
+ || branchResult.status === 'timeout'
31
+ || Boolean(branchResult.error_code);
32
+ }
33
+
24
34
  async function _executeTaskBranchConcurrently(task, idx, status, state, sliceExecutor) {
25
35
  const startedAt = Date.now();
26
36
  await new Promise((resolve) => setTimeout(resolve, 2));
@@ -28,6 +38,13 @@ async function _executeTaskBranchConcurrently(task, idx, status, state, sliceExe
28
38
  const targetAgent = normalizeAgentName(task.agent || status.assigned_agent || 'anbu');
29
39
  if (typeof sliceExecutor === 'function') {
30
40
  branchResult = await sliceExecutor(task, idx, status, state);
41
+ // A sliceExecutor is the caller's own trusted executor: it ran the work and
42
+ // reports the outcome. Absent an explicit denial, its documented `completed`
43
+ // status is the completion signal — the MCP runner path below is the one
44
+ // that never spawns anything and therefore never earns that status.
45
+ if (branchResult && branchResult.child_execution_verified === undefined) {
46
+ branchResult.child_execution_verified = branchResult.status === 'completed';
47
+ }
31
48
  } else {
32
49
  const projectPath = state.projectPath || status.project_path || process.cwd();
33
50
  const taskDir = state.taskDir || status.task_dir || '';
@@ -47,18 +64,27 @@ async function _executeTaskBranchConcurrently(task, idx, status, state, sliceExe
47
64
  });
48
65
  let parsedMcp = {};
49
66
  try { parsedMcp = JSON.parse(rawMcp); } catch (_) { parsedMcp = {}; }
67
+ // `runMcpAgentAsync` prepares a prompt and a spawn directive; it never starts
68
+ // a child process. Reporting the slice as completed with "exit 0" made an
69
+ // unspawned slice indistinguishable from a finished one, which is how a run
70
+ // could reach Gate 2 having executed nothing. Without a sliceExecutor there
71
+ // is no exit code to cite, so the slice stays pending and carries the
72
+ // directive the client must actually run.
50
73
  branchResult = {
51
74
  task_id: task.id,
52
75
  agent: parsedMcp.agent || targetAgent,
53
76
  model: parsedMcp.model || 'inherit',
54
77
  spawn_directive: parsedMcp.spawn_directive || null,
55
- summary: `Executed specialist @${targetAgent} slice (${task.id}): ${task.task || task.id}`,
56
- status: 'completed',
57
- child_execution_verified: true,
58
- validation: [`verified_specialist_slice:${targetAgent} (exit 0)`]
78
+ spawn_error: parsedMcp.spawn_error || null,
79
+ summary: `Spawn directive prepared for @${targetAgent} slice (${task.id}); no child process was started by the MCP runner`,
80
+ status: 'spawn_pending',
81
+ spawn_state: 'directive_only',
82
+ child_execution_verified: false,
83
+ validation: []
59
84
  };
60
85
  }
61
86
  const completedAt = Date.now();
87
+ const childVerified = branchResult?.child_execution_verified === true;
62
88
  const advisorEval = await evaluateWorkerTurnAsync({
63
89
  agent: task.agent || status.assigned_agent || 'anbu',
64
90
  taskId: task.id,
@@ -68,8 +94,8 @@ async function _executeTaskBranchConcurrently(task, idx, status, state, sliceExe
68
94
  ownedFiles: task.owned_files || [],
69
95
  filesModified: branchResult?.filesModified || [],
70
96
  worktreePath: task.worktree_path || null,
71
- status: 'completed',
72
- validation: branchResult?.validation || ['verified_specialist_slice (exit 0)']
97
+ status: childVerified ? 'completed' : 'spawn_pending',
98
+ validation: branchResult?.validation || []
73
99
  });
74
100
  return {
75
101
  task,
@@ -82,6 +108,7 @@ async function _executeTaskBranchConcurrently(task, idx, status, state, sliceExe
82
108
  completed_at: completedAt,
83
109
  elapsed_ms: Math.max(1, completedAt - startedAt),
84
110
  worktree_path: task.worktree_path || null,
111
+ child_execution_verified: childVerified,
85
112
  advisor_status: advisorEval.status,
86
113
  advisor_judge_tokens: (advisorEval.judge_usage && advisorEval.judge_usage.total_tokens) || 0
87
114
  }
@@ -91,6 +118,10 @@ async function _executeTaskBranchConcurrently(task, idx, status, state, sliceExe
91
118
  async function completePendingTasks(status, state, config) {
92
119
  const tasks = status.tasks || [];
93
120
  const pendingTasks = tasks.filter(t => t.status !== 'completed');
121
+ // The previous turn's directives are stale by definition: a slice that was
122
+ // reported complete is no longer waiting on a child, and leaving the old entry
123
+ // in place made the graph end on a spawn that had already happened.
124
+ status.spawn_pending = [];
94
125
  if (pendingTasks.length === 0) return tasks;
95
126
 
96
127
  const sliceResults = state.sliceResults;
@@ -105,7 +136,9 @@ async function completePendingTasks(status, state, config) {
105
136
  return tasks;
106
137
  }
107
138
 
108
- const sliceExecutor = state.sliceExecutor || config?.configurable?.sliceExecutor || null;
139
+ // `state.sliceExecutor` covers a direct node call; the registry covers a graph run,
140
+ // because LangGraph rebuilds `configurable` and would drop a caller's function.
141
+ const sliceExecutor = state.sliceExecutor || getSliceExecutor(state.threadId || config?.configurable?.thread_id);
109
142
  if ((state.requireExplicitDelegation || status.require_explicit_delegation) && !sliceExecutor) {
110
143
  return tasks;
111
144
  }
@@ -119,14 +152,43 @@ async function completePendingTasks(status, state, config) {
119
152
  : [];
120
153
 
121
154
  for (const outcome of branchOutcomes) {
122
- outcome.task.status = 'completed';
123
- outcome.task.result = outcome.branchResult;
155
+ const verified = outcome.branchResult && outcome.branchResult.child_execution_verified === true;
156
+ if (verified) {
157
+ outcome.task.status = 'completed';
158
+ outcome.task.spawn_state = 'completed';
159
+ outcome.task.result = outcome.branchResult;
160
+ recordCompletedDispatch(status, outcome.task.dispatch_id);
161
+ } else {
162
+ // No child process produced this slice. Keep it visible as pending work and
163
+ // hand the directive back so the client can actually spawn it; the review
164
+ // node's delegation guard then routes to dispatch instead of Gate 2.
165
+ outcome.task.status = 'spawn_pending';
166
+ // `failed` when the attempt actually ran and lost; `directive_only` when
167
+ // nothing was ever started and the client still owes the spawn.
168
+ outcome.task.spawn_state = _branchFailed(outcome.branchResult) ? 'failed' : 'directive_only';
169
+ outcome.task.spawn_directive = (outcome.branchResult && outcome.branchResult.spawn_directive) || null;
170
+ // The result stays attached so a caller can read the directive it must run;
171
+ // `status` on the task is what marks the slice as unfinished.
172
+ outcome.task.result = outcome.branchResult;
173
+ status.spawn_pending = Array.isArray(status.spawn_pending) ? status.spawn_pending : [];
174
+ status.spawn_pending.push({
175
+ task_id: outcome.task.id,
176
+ agent: outcome.task.agent || null,
177
+ spawn_directive: outcome.task.spawn_directive,
178
+ spawn_error: (outcome.branchResult && outcome.branchResult.spawn_error) || null
179
+ });
180
+ }
124
181
  outcome.task.started_at = outcome.telemetry.started_at;
125
- outcome.task.completed_at = outcome.telemetry.completed_at;
126
- recordCompletedDispatch(status, outcome.task.dispatch_id);
182
+ outcome.task.completed_at = verified ? outcome.telemetry.completed_at : null;
127
183
  status.parallel_execution_telemetry.push(outcome.telemetry);
128
184
  }
129
- if (branchOutcomes.length >= 2) {
185
+ // The status phase is what a resumed call and the delegation guard read; a slice
186
+ // waiting on its client belongs to the execute stage, not to whatever phase the
187
+ // previous node left behind.
188
+ if (status.spawn_pending.length > 0) {
189
+ status.phase = 'execute';
190
+ }
191
+ if (branchOutcomes.length >= 2 && branchOutcomes.every(o => o.branchResult && o.branchResult.child_execution_verified === true)) {
130
192
  status.parallel_execution_proof = {
131
193
  concurrent_count: branchOutcomes.length,
132
194
  branches: status.parallel_execution_telemetry.slice(-branchOutcomes.length),
@@ -233,6 +295,7 @@ async function executeNode(state, config) {
233
295
  const breakerStatus = breaker.getStatus();
234
296
  const circuitOpen = breakerStatus.state === 'OPEN';
235
297
 
298
+ const spawnPending = Array.isArray(status.spawn_pending) && status.spawn_pending.length > 0;
236
299
  const outputPayload = {
237
300
  status,
238
301
  phase: status.phase || 'review',
@@ -243,10 +306,20 @@ async function executeNode(state, config) {
243
306
  circuitOpen,
244
307
  circuitState: breakerStatus.state,
245
308
  error: executionError,
309
+ // A slice whose child was never started cannot be reviewed. Returning here
310
+ // hands the directive to the client, which spawns the child and reports back
311
+ // through `report_from_agent`; the next invoke resumes at this node with the
312
+ // tasks completed. Without this the graph bounced execute -> review ->
313
+ // dispatch until the remediation cap opened the circuit breaker.
314
+ spawnPending,
315
+ spawn_pending: spawnPending ? status.spawn_pending : undefined,
246
316
  };
247
317
 
248
- const nextNode = outputPayload.phase === 'document' ? 'node_dispatch' : 'node_review';
318
+ const nextNode = spawnPending
319
+ ? '__end__'
320
+ : (outputPayload.phase === 'document' ? 'node_dispatch' : 'node_review');
249
321
  return finalizeNodeResult(state, outputPayload, nextNode, {
322
+ resumeNode: spawnPending ? 'node_execute' : undefined,
250
323
  source: {
251
324
  status,
252
325
  phase: outputPayload.phase,
@@ -254,6 +327,7 @@ async function executeNode(state, config) {
254
327
  circuitOpen,
255
328
  circuitState: breakerStatus.state,
256
329
  error: executionError,
330
+ spawnPending,
257
331
  }
258
332
  });
259
333
  }
@@ -157,6 +157,14 @@ function _delegationGuard(state, status, taskDir) {
157
157
  status.hitl_gate = null;
158
158
  if (taskDir) saveWorkflowStatus(taskDir, status);
159
159
 
160
+ const pendingSpawns = pendingTasks
161
+ .filter((t) => t.status === 'spawn_pending' && t.spawn_directive)
162
+ .map((t) => ({
163
+ task_id: t.id,
164
+ agent: t.agent || null,
165
+ spawn_state: t.spawn_state || 'directive_only',
166
+ spawn_directive: t.spawn_directive
167
+ }));
160
168
  const payload = {
161
169
  status,
162
170
  phase: 'execute',
@@ -164,11 +172,15 @@ function _delegationGuard(state, status, taskDir) {
164
172
  hitlStage: null,
165
173
  delegationPending: true,
166
174
  pending_task_ids: pendingTasks.map((t) => t.id),
175
+ // A slice the MCP runner only prepared a directive for has to be spawned by
176
+ // the client. Without handing the directive back here the run bounced
177
+ // dispatch -> review with no way to see what was waiting on it.
178
+ spawn_pending: pendingSpawns.length > 0 ? pendingSpawns : undefined,
167
179
  error: null,
168
180
  };
169
181
  return finalizeNodeResult(state, payload, 'node_dispatch', {
170
182
  resumeNode: 'node_dispatch',
171
- source: { delegationPending: true, pending: payload.pending_task_ids },
183
+ source: { delegationPending: true, pending: payload.pending_task_ids, spawnPending: pendingSpawns.length },
172
184
  });
173
185
  }
174
186
 
@@ -0,0 +1,22 @@
1
+ 'use strict';
2
+
3
+ // LangGraph rebuilds `config.configurable` for its own runtime keys, so a caller's
4
+ // executor cannot ride along there. A function also cannot live in the state
5
+ // schema: the checkpointer serialises state. This registry is the one channel that
6
+ // survives both, keyed by thread so concurrent runs stay isolated.
7
+ const executors = new Map();
8
+
9
+ function setSliceExecutor(threadId, fn) {
10
+ if (!threadId || typeof fn !== 'function') return;
11
+ executors.set(threadId, fn);
12
+ }
13
+
14
+ function getSliceExecutor(threadId) {
15
+ return threadId ? executors.get(threadId) || null : null;
16
+ }
17
+
18
+ function clearSliceExecutor(threadId) {
19
+ if (threadId) executors.delete(threadId);
20
+ }
21
+
22
+ module.exports = { setSliceExecutor, getSliceExecutor, clearSliceExecutor };
@@ -100,6 +100,11 @@ const KonohaWorkflowState = Annotation.Root({
100
100
  hitlRefinement: Annotation({ default: () => null }),
101
101
  autoSignoff: Annotation({ default: () => false }),
102
102
 
103
+ // Declared as channels or LangGraph drops them: the execute node ends the turn
104
+ // here when a slice only has a spawn directive, and the router reads the flag.
105
+ spawnPending: Annotation({ default: () => false }),
106
+ spawn_pending: Annotation({ default: () => null }),
107
+
103
108
  result: Annotation({ default: () => null }),
104
109
  error: Annotation({ default: () => null }),
105
110
  });
@@ -2,6 +2,7 @@
2
2
 
3
3
  const { isReadOnlyAgent } = require('../agent_file_safety');
4
4
  const { hasPiSubagentSupport } = require('../pi_manager');
5
+ const { normalizeAgentName } = require('../canonical_agents');
5
6
 
6
7
  const SPAWNABLE_SUBAGENTS = Object.freeze([
7
8
  'genin',
@@ -109,6 +110,9 @@ function buildUnsupportedSpawnPayload(client, reason) {
109
110
  return {
110
111
  ok: false,
111
112
  supported: false,
113
+ // Nothing was started, so there is no child to report on. This is a
114
+ // capability gap, not a failed run.
115
+ spawn_state: 'directive_only',
112
116
  error_code: 'UNSUPPORTED_NATIVE_SPAWN',
113
117
  client: client || 'unknown',
114
118
  error: reason,
@@ -192,8 +196,14 @@ function _cliTaskExcerpt(prompt) {
192
196
  return _shellQuotePosix(truncateSpawnTask(raw).replace(/`/g, ''));
193
197
  }
194
198
 
199
+ // Agent tokens must survive to the deployed profile name verbatim. The previous
200
+ // sanitizer stripped every non `[a-z0-9-]` character, so `tokubetsu_jonin` became
201
+ // `tokubetsujonin` while the profile on disk is `tokubetsu-jonin.md`; the native
202
+ // spawn then named an agent no client could resolve and the CLI fallback failed
203
+ // the same way. normalizeAgentName is the single canonical mapping (`_`/space ->
204
+ // `-`, `@` stripped, lowercase), so every directive and the profile agree.
195
205
  function _safeAgentToken(raw) {
196
- const cleaned = String(raw || 'subagent').replace(/^mcp_/, '').toLowerCase().trim().replace(/[^a-z0-9-]/g, '');
206
+ const cleaned = normalizeAgentName(String(raw || 'subagent').replace(/^mcp_/, ''));
197
207
  return cleaned || 'subagent';
198
208
  }
199
209
 
@@ -316,7 +316,10 @@ function _reportFromAgent(delivery, rest, useModelJudge) {
316
316
  // `cleanAgent`, not `opts.agentName`: the dispatch guard below compares against
317
317
  // the normalized name, so `mcp_kage` and `Anbu` were rejected as mismatches.
318
318
  const { error: wfError, workflowStatus } = _updateWorkflowStatus(safeTaskDir || opts.taskDir, opts.dispatchId, cleanAgent, finalStatus, {
319
- summary: reportSummary, validation: opts.validation, verified, filesCreated: opts.filesCreated, filesModified: opts.filesModified
319
+ summary: reportSummary, validation: opts.validation, verified, filesCreated: opts.filesCreated, filesModified: opts.filesModified,
320
+ // A report may name the slice it belongs to; without it a parallel workflow
321
+ // attributes every child's result to whichever task happens to be open.
322
+ taskId: opts.taskId
320
323
  });
321
324
  if (wfError) return JSON.stringify({ status: 'error', message: wfError });
322
325
 
@@ -694,5 +694,6 @@ async function runMcpAgentAsync(agentName, task = null, context = null, constrai
694
694
  module.exports = {
695
695
  getMainModel, applyFileEdits, autoloadSkillsFromPrompt, buildSubagentMcpBlock,
696
696
  buildResearchFetchRule, truncateAtBoundary, cleanRedundantPersonaText,
697
- _loadBaseProjectContext, _prepareAgentRun, _finalizeAgentRun, runMcpAgent, runMcpAgentAsync
697
+ _loadBaseProjectContext, _prepareAgentRun, _finalizeAgentRun, runMcpAgent, runMcpAgentAsync,
698
+ PROMPT_CEILING_BYTES, SYSTEM_PROMPT_FLOOR_BYTES, MIN_SKILL_PREVIEW_BYTES
698
699
  };
@@ -363,6 +363,7 @@ function resolveFlowHashFromTask(flowHash, taskId) {
363
363
  // stays authoritative: the database is an index of them, never a replacement.
364
364
  const PROJECT_SKILL_SUBDIRS = [
365
365
  ['.agents', 'skills'],
366
+ ['.agents', 'dev-skills'],
366
367
  ['.agent', 'skills'],
367
368
  ['skills'],
368
369
  ['.skills'],
@@ -332,6 +332,8 @@ function _prepareSpawnSpec(options) {
332
332
  aborted: true,
333
333
  agent: normalizedAgent,
334
334
  client: capability.client,
335
+ // Cancelled before launch: no child ever existed.
336
+ spawn_state: 'directive_only',
335
337
  error_code: 'SPAWN_ABORTED',
336
338
  error: 'Subagent spawn cancelled before launch.'
337
339
  }
@@ -454,6 +456,9 @@ function _buildFailureExitResult({
454
456
  return {
455
457
  ok: false,
456
458
  status: kind.status,
459
+ // Fixed vocabulary: directive_only | completed | failed. A timeout or abort
460
+ // is a failure, not a state of its own.
461
+ spawn_state: 'failed',
457
462
  ...(kind.flagKey ? { [kind.flagKey]: true } : {}),
458
463
  agent: normalizedAgent,
459
464
  client,
@@ -566,6 +571,7 @@ function _executeSpawnSpec(spec, options, childEnv, startedAt) {
566
571
  client: capability.client,
567
572
  child_pid: childPid || null,
568
573
  elapsed_ms: Date.now() - startedAt,
574
+ spawn_state: 'failed',
569
575
  error_code: err.code === 'ENOENT' ? 'HARNESS_BINARY_NOT_FOUND' : 'SPAWN_PROCESS_ERROR',
570
576
  error: err.message
571
577
  });
@@ -609,6 +615,7 @@ function _executeSpawnSpec(spec, options, childEnv, startedAt) {
609
615
  ...parsed,
610
616
  ok: true,
611
617
  status: parsed.status || 'completed',
618
+ spawn_state: 'completed',
612
619
  agent: normalizedAgent,
613
620
  client: capability.client,
614
621
  child_pid: parsed.child_pid || childPid,