dsh-agent-router 1.9.0
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.
- package/LICENSE +21 -0
- package/README.en.md +304 -0
- package/README.md +304 -0
- package/client.js +3061 -0
- package/cordis.patch.yml +20 -0
- package/docs/ARCHITECTURE_DIAGNOSIS_AND_PLAN.md +414 -0
- package/docs/DETAIL.ja.md +1 -0
- package/docs/DETAIL.md +1 -0
- package/docs/DETAIL.zh.md +1 -0
- package/docs/IMPLEMENTATION_PLAN.md +99 -0
- package/docs/ITERATION_PLAN_2026-11.md +377 -0
- package/docs/RELEASE.md +133 -0
- package/docs/RELEASE_CHECKLIST.md +88 -0
- package/docs/preview.svg +69 -0
- package/docs/preview.zh.svg +63 -0
- package/icon.svg +16 -0
- package/index.js +24 -0
- package/lib/classifier.js +405 -0
- package/lib/cli/discover.js +187 -0
- package/lib/cli/invoke.js +294 -0
- package/lib/cli/parsers.js +234 -0
- package/lib/cli/shared.js +145 -0
- package/lib/cli-runners.js +39 -0
- package/lib/config-limits.js +67 -0
- package/lib/config-normalize.js +147 -0
- package/lib/config-presets.js +89 -0
- package/lib/config-schema.js +347 -0
- package/lib/defaults.js +117 -0
- package/lib/diagnose-fallback.js +96 -0
- package/lib/error-classify.js +160 -0
- package/lib/eval-routing.js +96 -0
- package/lib/guardrails.js +70 -0
- package/lib/integrations.js +173 -0
- package/lib/job-runner.js +287 -0
- package/lib/ledger.js +360 -0
- package/lib/legacy-config.js +34 -0
- package/lib/model-capabilities.js +135 -0
- package/lib/model-score.js +65 -0
- package/lib/plugin.js +184 -0
- package/lib/profile-mount.js +524 -0
- package/lib/route-edit.js +82 -0
- package/lib/router/candidates.js +194 -0
- package/lib/router/catalog.js +121 -0
- package/lib/router/cli-select.js +84 -0
- package/lib/router/config-manager.js +122 -0
- package/lib/router/doctor.js +159 -0
- package/lib/router/local-models.js +126 -0
- package/lib/router/policy.js +61 -0
- package/lib/router/rpc.js +263 -0
- package/lib/router/system-prompt.js +29 -0
- package/lib/router/tools.js +1028 -0
- package/lib/router/util.js +99 -0
- package/lib/rpc-contract.js +46 -0
- package/lib/sessions.js +59 -0
- package/lib/task-queue.js +201 -0
- package/lib/tier-presets.js +595 -0
- package/lib/typert.host.js +79 -0
- package/lib/update-check.js +205 -0
- package/lib/worktree-lock.js +86 -0
- package/lib/worktree.js +268 -0
- package/locale/en.json +7 -0
- package/locale/ja.json +7 -0
- package/locale/zh.json +7 -0
- package/package.json +136 -0
- package/scripts/profile-maintenance.mjs +287 -0
|
@@ -0,0 +1,1028 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Tool registrations for router_plan / router_dispatch / router_continue /
|
|
3
|
+
* router_status.
|
|
4
|
+
* @module dsh-agent-router/lib/router/tools
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
import { randomUUID } from 'node:crypto'
|
|
8
|
+
import { tmpdir } from 'node:os'
|
|
9
|
+
import { join, resolve } from 'node:path'
|
|
10
|
+
|
|
11
|
+
import { classifyTask, nextEscalationTier } from '../classifier.js'
|
|
12
|
+
import { discoverCliModels, executeCliAgent, probeLocalClis } from '../cli-runners.js'
|
|
13
|
+
import { CONFIG_LIMITS } from '../config-limits.js'
|
|
14
|
+
import { classifyError, shouldEscalateAfter } from '../error-classify.js'
|
|
15
|
+
import { assertPathWithin, redactSecrets } from '../guardrails.js'
|
|
16
|
+
import { applyCapabilityPolicy, inferTaskRequirements } from '../model-capabilities.js'
|
|
17
|
+
import { listSessions, pruneSessions } from '../sessions.js'
|
|
18
|
+
import { resolveTierRef, sortTierEntries, tierBand } from '../tier-presets.js'
|
|
19
|
+
import { acquireWorktreeLock } from '../worktree-lock.js'
|
|
20
|
+
import { readContextPressure, readCostMeterSnapshot } from '../integrations.js'
|
|
21
|
+
import {
|
|
22
|
+
cleanupIsolatedWorktree,
|
|
23
|
+
createIsolatedWorktree,
|
|
24
|
+
getRepoRoot,
|
|
25
|
+
inspectWorktreeDiff,
|
|
26
|
+
mergeIsolatedWorktree,
|
|
27
|
+
readWorktreePatch,
|
|
28
|
+
} from '../worktree.js'
|
|
29
|
+
import { buildCandidates } from './candidates.js'
|
|
30
|
+
import { readSubagentModelSelectionStatus } from './catalog.js'
|
|
31
|
+
import { buildDoctorReport } from './doctor.js'
|
|
32
|
+
import { applyEcosystemPolicies } from './policy.js'
|
|
33
|
+
import { ToolArgumentError, callerCwd, describeThrown, toLosslessJson, validateToolArguments } from './util.js'
|
|
34
|
+
|
|
35
|
+
export const PLAN_TOOL = 'router_plan'
|
|
36
|
+
export const DISPATCH_TOOL = 'router_dispatch'
|
|
37
|
+
export const CONTINUE_TOOL = 'router_continue'
|
|
38
|
+
export const STATUS_TOOL = 'router_status'
|
|
39
|
+
|
|
40
|
+
const PLAN_PARAMETERS = {
|
|
41
|
+
type: 'object',
|
|
42
|
+
additionalProperties: false,
|
|
43
|
+
required: ['task'],
|
|
44
|
+
properties: {
|
|
45
|
+
task: { type: 'string', description: 'Task description to classify and plan routing for.' },
|
|
46
|
+
tier: { type: 'string', description: 'Optional explicit tier id or name (defaults: T1-T4). Use router_status config to list configured tiers.' },
|
|
47
|
+
domain: { type: 'string', enum: ['general', 'code', 'research', 'review'], description: 'Optional task domain.' },
|
|
48
|
+
prefer_backend: { type: 'string', enum: ['auto', 'dsh', 'cli', 'claude', 'codex', 'gemini', 'opencode', 'antigravity'], description: 'Optional preferred execution backend.' },
|
|
49
|
+
},
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
const DISPATCH_PARAMETERS = {
|
|
53
|
+
type: 'object',
|
|
54
|
+
additionalProperties: false,
|
|
55
|
+
required: ['description', 'prompt'],
|
|
56
|
+
properties: {
|
|
57
|
+
description: { type: 'string', description: 'Short 3-8 word label for this task.' },
|
|
58
|
+
prompt: { type: 'string', description: 'Complete self-contained task prompt.' },
|
|
59
|
+
tier: { type: 'string', description: 'Tier id or name (defaults: T1-T4). Omit for automatic classification.' },
|
|
60
|
+
domain: { type: 'string', enum: ['general', 'code', 'research', 'review'], description: 'Optional domain hint.' },
|
|
61
|
+
backend: { type: 'string', enum: ['auto', 'dsh', 'cli', 'claude', 'codex', 'gemini', 'opencode', 'antigravity'], description: 'Backend preference (default: auto).' },
|
|
62
|
+
cwd: { type: 'string', description: 'Working directory (defaults to caller workspace).' },
|
|
63
|
+
use_worktree: { type: 'boolean', description: 'Isolate CLI edits in a dedicated Git worktree branch (default: false).' },
|
|
64
|
+
permission_mode: { type: 'string', enum: ['read-only', 'workspace-write', 'auto'], description: 'Execution permission level for CLI agents (default: workspace-write).' },
|
|
65
|
+
auto_escalate: { type: 'boolean', description: 'Escalate to the next difficulty tier if all candidates in the initial tier fail (default: true).' },
|
|
66
|
+
background: { type: 'boolean', description: 'Run external CLI dispatches asynchronously in the background queue and wake the parent on completion (default: false or config.defaultBackground).' },
|
|
67
|
+
timeout_ms: { type: 'integer', minimum: CONFIG_LIMITS.defaultTimeoutMs.min, maximum: CONFIG_LIMITS.defaultTimeoutMs.max, description: 'CLI timeout in milliseconds (default: 300000).' },
|
|
68
|
+
},
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
const CONTINUE_PARAMETERS = {
|
|
72
|
+
type: 'object',
|
|
73
|
+
additionalProperties: false,
|
|
74
|
+
required: ['run_id', 'message'],
|
|
75
|
+
properties: {
|
|
76
|
+
run_id: { type: 'string', description: 'The runId returned by router_dispatch (or a DSH subagent name/id).' },
|
|
77
|
+
message: { type: 'string', description: 'Follow-up instruction or steering message.' },
|
|
78
|
+
timeout_ms: { type: 'integer', minimum: CONFIG_LIMITS.defaultTimeoutMs.min, maximum: CONFIG_LIMITS.defaultTimeoutMs.max, description: 'Timeout for CLI continuation.' },
|
|
79
|
+
},
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
const STATUS_PARAMETERS = {
|
|
83
|
+
type: 'object',
|
|
84
|
+
additionalProperties: false,
|
|
85
|
+
properties: {
|
|
86
|
+
action: {
|
|
87
|
+
type: 'string',
|
|
88
|
+
enum: ['overview', 'runs', 'active_jobs', 'run_status', 'config', 'doctor', 'clear_cooldowns', 'cancel_run', 'rate_run', 'sessions', 'prune_sessions', 'inspect_worktree_diff', 'merge_worktree', 'cleanup_worktree', 'prune_worktrees'],
|
|
89
|
+
description: 'Status action (default: overview).',
|
|
90
|
+
},
|
|
91
|
+
run_id: { type: 'string', description: 'Run id for worktree/cancel actions, or route key for clear_cooldowns.' },
|
|
92
|
+
quality: { type: 'integer', minimum: 1, maximum: 5, description: 'Quality rating (1-5) for rate_run.' },
|
|
93
|
+
comment: { type: 'string', description: 'Optional feedback comment for rate_run.' },
|
|
94
|
+
keep: { type: 'integer', minimum: 1, maximum: 500, description: 'Number of recent sessions to keep for prune_sessions (default: 50).' },
|
|
95
|
+
max_age_ms: { type: 'integer', minimum: 0, description: 'Drop sessions older than this age in milliseconds for prune_sessions.' },
|
|
96
|
+
delete_branch: { type: 'boolean', description: 'Also delete the worktree branch on cleanup_worktree / prune_worktrees (default: false).' },
|
|
97
|
+
strategy: { type: 'string', enum: ['squash', 'ff-only', 'merge'], description: 'Git merge strategy for merge_worktree (default: squash).' },
|
|
98
|
+
commit_message: { type: 'string', description: 'Optional commit message for merge_worktree.' },
|
|
99
|
+
cleanup: { type: 'boolean', description: 'Automatically remove worktree and branch after merge_worktree (default: true).' },
|
|
100
|
+
max_bytes: { type: 'integer', minimum: 1024, maximum: 524288, description: 'Maximum diff bytes for inspect_worktree_diff (default: 32768).' },
|
|
101
|
+
limit: { type: 'integer', minimum: 1, maximum: 100, description: 'Number of recent runs to return (default: 15).' },
|
|
102
|
+
},
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
function tierLabelOf(tiers, id) {
|
|
106
|
+
const entry = tiers?.[id]
|
|
107
|
+
return entry?.name || entry?.label || id
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/**
|
|
111
|
+
* Resolve the CLI permission level for the tier that is actually executed.
|
|
112
|
+
* An explicit caller override wins; otherwise review tiers run read-only, so
|
|
113
|
+
* escalating into a review tier cannot silently gain write access.
|
|
114
|
+
* @param {string} tier
|
|
115
|
+
* @param {Record<string, any>} tiers
|
|
116
|
+
* @param {string} [explicit]
|
|
117
|
+
*/
|
|
118
|
+
export function permissionModeForTier(tier, tiers, explicit) {
|
|
119
|
+
if (explicit) return explicit
|
|
120
|
+
return tiers?.[tier]?.role === 'review' ? 'read-only' : 'workspace-write'
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
function resolveToolTier(ref, tiers, toolName) {
|
|
124
|
+
if (ref === undefined || ref === null || String(ref).trim() === '') return undefined
|
|
125
|
+
const id = resolveTierRef(ref, tiers)
|
|
126
|
+
if (!id) {
|
|
127
|
+
const available = sortTierEntries(tiers)
|
|
128
|
+
.map(([tierId]) => `${tierId} (${tierLabelOf(tiers, tierId)})`)
|
|
129
|
+
.join(', ')
|
|
130
|
+
throw new ToolArgumentError(toolName, [{
|
|
131
|
+
path: 'tier',
|
|
132
|
+
message: `unknown tier "${ref}"; available tiers: ${available || 'none'}`,
|
|
133
|
+
}])
|
|
134
|
+
}
|
|
135
|
+
return id
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
/**
|
|
139
|
+
* @param {{
|
|
140
|
+
* ctx: any,
|
|
141
|
+
* store: import('../ledger.js').RouterStore,
|
|
142
|
+
* queue: import('../job-runner.js').RouterJobRunner,
|
|
143
|
+
* currentConfig: () => Record<string, any>,
|
|
144
|
+
* getConfigSource: () => string,
|
|
145
|
+
* notifyParentAgent: (caller: any, text: string, source?: { kind: string, [key: string]: any }) => void,
|
|
146
|
+
* activeWriteDirs: Map<string, number>,
|
|
147
|
+
* }} runtime
|
|
148
|
+
*/
|
|
149
|
+
export function registerRouterTools(runtime) {
|
|
150
|
+
const {
|
|
151
|
+
ctx,
|
|
152
|
+
store,
|
|
153
|
+
queue,
|
|
154
|
+
currentConfig,
|
|
155
|
+
getConfigSource,
|
|
156
|
+
notifyParentAgent,
|
|
157
|
+
activeWriteDirs,
|
|
158
|
+
} = runtime
|
|
159
|
+
|
|
160
|
+
const continueDshChild = async (caller, childTarget, text, signal) => {
|
|
161
|
+
const root = ctx.subagents.rootOf(caller)
|
|
162
|
+
const rows = await ctx.subagents.listDescendants(root.id, signal)
|
|
163
|
+
const row = rows.find(r => (r.path ?? r.id) === childTarget || r.id === childTarget)
|
|
164
|
+
const targetId = row ? row.id : await ctx.subagents.resolveName(caller, childTarget, signal)
|
|
165
|
+
const liveBefore = ctx.agents.get(targetId) !== undefined
|
|
166
|
+
const messageId = await ctx.subagents.sendMessage(
|
|
167
|
+
caller,
|
|
168
|
+
targetId,
|
|
169
|
+
[{ type: 'text', text }],
|
|
170
|
+
{ signal: signal || AbortSignal.timeout(120_000) },
|
|
171
|
+
)
|
|
172
|
+
const child = ctx.agents.get(targetId)
|
|
173
|
+
if (child !== undefined) {
|
|
174
|
+
const parked = [...(child.inbox?.nextTurn || []), ...(child.inbox?.nextStep || [])]
|
|
175
|
+
.find(m => m.id === messageId)
|
|
176
|
+
if (parked !== undefined) {
|
|
177
|
+
if (child.status === 'running') child.steer(parked)
|
|
178
|
+
else child.followup(parked)
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
return { targetId, resumed: !liveBefore, messageId: String(messageId || targetId) }
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
// Worktrees are always created under the OS temp root; reject ledger paths
|
|
185
|
+
// that try to escape it before running destructive git commands.
|
|
186
|
+
const worktreeBase = join(tmpdir(), 'dsh-router-worktrees')
|
|
187
|
+
const requireWorktree = (run) => {
|
|
188
|
+
if (!run?.worktree) throw new Error(`No worktree recorded for run "${run?.runId || ''}"`)
|
|
189
|
+
assertPathWithin(worktreeBase, run.worktree.worktreePath, 'worktree path')
|
|
190
|
+
return run.worktree
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
// 1. router_plan
|
|
194
|
+
ctx.tools.register({
|
|
195
|
+
name: PLAN_TOOL,
|
|
196
|
+
description:
|
|
197
|
+
'Analyze task difficulty against the configured tiers (defaults: T1 Light, T2 Standard, T3 Hard, T4 Review) and preview the ranked candidate chain across DSH native models and local CLIs (claude, codex, gemini, opencode, antigravity) without executing anything.',
|
|
198
|
+
parameters: PLAN_PARAMETERS,
|
|
199
|
+
output: {
|
|
200
|
+
schema: {
|
|
201
|
+
type: 'object',
|
|
202
|
+
additionalProperties: true,
|
|
203
|
+
required: ['classification', 'policyLabel', 'candidates'],
|
|
204
|
+
properties: {
|
|
205
|
+
classification: { type: 'object' },
|
|
206
|
+
policyLabel: { type: 'string' },
|
|
207
|
+
candidates: { type: 'array' },
|
|
208
|
+
},
|
|
209
|
+
},
|
|
210
|
+
render: (_args, val) => [{
|
|
211
|
+
type: 'text',
|
|
212
|
+
text: [
|
|
213
|
+
`Tier: ${val.classification.tier} (${val.classification.tierName || val.policyLabel}) | Domain: ${val.classification.domain} | Reasons: ${val.classification.reasons.join('; ')}`,
|
|
214
|
+
`Confidence: ${val.classification.confidence}${typeof val.classification.confidenceScore === 'number' ? ` (${val.classification.confidenceScore})` : ''} | Score: ${val.classification.score}${val.classification.promoted ? ` | promoted from ${val.classification.tierBeforePromotion} by low confidence` : ''}`,
|
|
215
|
+
...(val.classification.signals?.length
|
|
216
|
+
? [`Signals: ${val.classification.signals.map(signal => `${signal.id}${signal.delta >= 0 ? '+' : ''}${signal.delta}`).join(', ')}`]
|
|
217
|
+
: []),
|
|
218
|
+
'Candidates:',
|
|
219
|
+
...val.candidates.map((c, i) => ` ${i + 1}. [${c.kind}] ${c.key}${c.note ? ` — ${c.note}` : ''}`),
|
|
220
|
+
...(val.blockedDshRoutes?.length ? [`Filtered DSH routes: ${val.blockedDshRoutes.map(b => `${b.route} (${b.reason})`).join('; ')}`] : []),
|
|
221
|
+
...(val.cooled?.length ? [`Cooled routes: ${val.cooled.map(c => `${c.key} (${Math.ceil(c.remainingMs / 1000)}s)`).join('; ')}`] : []),
|
|
222
|
+
...(val.ecosystemNotes?.length ? [`Ecosystem hints: ${val.ecosystemNotes.join(' | ')}`] : []),
|
|
223
|
+
val.escalationTier
|
|
224
|
+
? `Escalation target on failure: ${val.escalationTier}${val.escalationTierName ? ` (${val.escalationTierName})` : ''}`
|
|
225
|
+
: 'Escalation target: none (top tier)',
|
|
226
|
+
].join('\n'),
|
|
227
|
+
}],
|
|
228
|
+
},
|
|
229
|
+
isConcurrencySafe: () => true,
|
|
230
|
+
async execute(args, exec) {
|
|
231
|
+
validateToolArguments(PLAN_TOOL, PLAN_PARAMETERS, args)
|
|
232
|
+
const caller = exec.agent
|
|
233
|
+
if (!caller) throw new Error(`${PLAN_TOOL} requires a calling agent`)
|
|
234
|
+
const cfg = currentConfig()
|
|
235
|
+
const requestedTier = resolveToolTier(args.tier, cfg.tiers, PLAN_TOOL)
|
|
236
|
+
const classification = classifyTask({ task: args.task, tier: requestedTier, domain: args.domain, tiers: cfg.tiers })
|
|
237
|
+
const [plan, costSnap, contextSnap] = await Promise.all([
|
|
238
|
+
buildCandidates({
|
|
239
|
+
ctx,
|
|
240
|
+
caller,
|
|
241
|
+
tier: classification.tier,
|
|
242
|
+
preferBackend: args.prefer_backend || cfg.preferBackend,
|
|
243
|
+
policies: cfg.tiers,
|
|
244
|
+
store,
|
|
245
|
+
cfg,
|
|
246
|
+
}),
|
|
247
|
+
readCostMeterSnapshot(ctx),
|
|
248
|
+
readContextPressure(caller, ctx),
|
|
249
|
+
])
|
|
250
|
+
const adjusted = applyEcosystemPolicies(plan.candidates, {
|
|
251
|
+
tier: classification.tier,
|
|
252
|
+
band: tierBand(classification.tier, cfg.tiers),
|
|
253
|
+
costSnap,
|
|
254
|
+
contextSnap,
|
|
255
|
+
cfg,
|
|
256
|
+
routeMetrics: store.getRouteMetrics(),
|
|
257
|
+
})
|
|
258
|
+
const requirements = inferTaskRequirements(args.task)
|
|
259
|
+
const capability = applyCapabilityPolicy(adjusted.candidates, requirements)
|
|
260
|
+
const policy = cfg.tiers[classification.tier]
|
|
261
|
+
const escalationTier = nextEscalationTier(classification.tier, cfg.tiers)
|
|
262
|
+
return toLosslessJson({
|
|
263
|
+
classification,
|
|
264
|
+
policyLabel: policy?.name || policy?.label || classification.tier,
|
|
265
|
+
escalationTier,
|
|
266
|
+
escalationTierName: escalationTier ? tierLabelOf(cfg.tiers, escalationTier) : null,
|
|
267
|
+
allCooled: plan.allCooled,
|
|
268
|
+
subagentModelSelectionEnabled: plan.subagentModelSelectionEnabled,
|
|
269
|
+
parentFallbackUsed: plan.parentFallbackUsed,
|
|
270
|
+
cliSelection: plan.cliSelection,
|
|
271
|
+
localModelsEnabled: plan.localModelsEnabled,
|
|
272
|
+
localModelRoutes: plan.localModelRoutes.map(r => `${r.provider}/${r.model}`),
|
|
273
|
+
requirements,
|
|
274
|
+
candidates: capability.candidates.map(c => ({
|
|
275
|
+
kind: c.kind,
|
|
276
|
+
key: c.key,
|
|
277
|
+
...(c.provider !== undefined ? { provider: c.provider } : {}),
|
|
278
|
+
...(c.model !== undefined ? { model: c.model } : {}),
|
|
279
|
+
...(c.backend !== undefined ? { backend: c.backend } : {}),
|
|
280
|
+
...((c.reasoningEffort || c.effort) !== undefined ? { effort: c.reasoningEffort || c.effort } : {}),
|
|
281
|
+
...(c.note !== undefined ? { note: c.note } : {}),
|
|
282
|
+
})),
|
|
283
|
+
cooled: plan.cooled.map(c => ({ key: c.key, remainingMs: c.cooldownRemainingMs, reason: c.cooldownReason })),
|
|
284
|
+
blockedDshRoutes: plan.blockedDshRoutes,
|
|
285
|
+
ecosystemNotes: [
|
|
286
|
+
...adjusted.notes,
|
|
287
|
+
...capability.notes,
|
|
288
|
+
...plan.selectionNotes,
|
|
289
|
+
...(plan.parentFallbackUsed && !plan.subagentModelSelectionEnabled
|
|
290
|
+
? ['subagent-model-selection is disabled; enable subagent-model-selection-settings in DSH to allow native subagents to switch across tier models']
|
|
291
|
+
: []),
|
|
292
|
+
],
|
|
293
|
+
costMeter: costSnap,
|
|
294
|
+
contextPressure: contextSnap,
|
|
295
|
+
})
|
|
296
|
+
},
|
|
297
|
+
})
|
|
298
|
+
|
|
299
|
+
// 2. router_dispatch
|
|
300
|
+
ctx.tools.register({
|
|
301
|
+
name: DISPATCH_TOOL,
|
|
302
|
+
description:
|
|
303
|
+
'Route and execute a task across DSH subagents or local agent CLIs (claude, codex, gemini, opencode, antigravity) based on the configured difficulty tiers (defaults: T1 Light, T2 Standard, T3 Hard, T4 Review). Supports health-aware failover, optional failure escalation to a higher tier, session persistence for follow-ups, and optional Git worktree isolation.',
|
|
304
|
+
parameters: DISPATCH_PARAMETERS,
|
|
305
|
+
output: {
|
|
306
|
+
schema: {
|
|
307
|
+
type: 'object',
|
|
308
|
+
additionalProperties: true,
|
|
309
|
+
required: ['ok', 'mode'],
|
|
310
|
+
properties: {
|
|
311
|
+
ok: { type: 'boolean' },
|
|
312
|
+
mode: { type: 'string' },
|
|
313
|
+
},
|
|
314
|
+
},
|
|
315
|
+
render: (_args, val) => {
|
|
316
|
+
if (val.mode === 'dsh-subagent') {
|
|
317
|
+
return [{
|
|
318
|
+
type: 'text',
|
|
319
|
+
text: `[${val.runId}] Dispatched DSH subagent "${val.childName}" on ${val.route} (tier ${val.tier}). Result will arrive via completion notice.`,
|
|
320
|
+
}]
|
|
321
|
+
}
|
|
322
|
+
if (val.mode === 'cli-async') {
|
|
323
|
+
return [{
|
|
324
|
+
type: 'text',
|
|
325
|
+
text: `[${val.runId}] Queued async CLI dispatch on tier ${val.tier} (status=${val.status}). Use router_status or wait for completion notice.`,
|
|
326
|
+
}]
|
|
327
|
+
}
|
|
328
|
+
const header = `[${val.runId}] ${val.ok ? 'Completed' : 'Failed'} via ${val.backend}${val.model ? ` (${val.model})` : ''} [tier ${val.tier}, ${val.durationMs}ms]`
|
|
329
|
+
+ (val.escalatedFrom ? ` [escalated from ${val.escalatedFrom}]` : '')
|
|
330
|
+
+ (val.sessionId ? ` session=${val.sessionId}` : '')
|
|
331
|
+
const wt = val.worktreeDiff ? `\nWorktree branch: ${val.worktreeDiff.branch} (dirty=${val.worktreeDiff.dirty})\n${val.worktreeDiff.diffStat || val.worktreeDiff.statusShort}` : ''
|
|
332
|
+
const body = val.ok ? val.output : `Error: ${val.error}`
|
|
333
|
+
return [{ type: 'text', text: `${header}${wt}\n\n${body}` }]
|
|
334
|
+
},
|
|
335
|
+
},
|
|
336
|
+
presentCall: (args) => ({
|
|
337
|
+
card: 'generic',
|
|
338
|
+
kind: 'run',
|
|
339
|
+
title: `Route ${args.tier ? `${args.tier} ` : ''}${args.backend && args.backend !== 'auto' ? `(${args.backend}) ` : ''}task: ${args.description || 'dispatch'}`,
|
|
340
|
+
}),
|
|
341
|
+
presentResult: (_args, val) => ({
|
|
342
|
+
card: 'generic',
|
|
343
|
+
kind: 'run',
|
|
344
|
+
title: val?.mode === 'dsh-subagent'
|
|
345
|
+
? `Dispatched ${val.childName} (${val.route})`
|
|
346
|
+
: val?.mode === 'cli-async'
|
|
347
|
+
? `Queued async ${val.runId} (${val.tier})`
|
|
348
|
+
: `${val?.ok ? 'Completed' : 'Failed'} ${val?.backend || 'router'} (${val?.tier || '?'})`,
|
|
349
|
+
}),
|
|
350
|
+
isConcurrencySafe: () => true,
|
|
351
|
+
async execute(args, exec) {
|
|
352
|
+
validateToolArguments(DISPATCH_TOOL, DISPATCH_PARAMETERS, args)
|
|
353
|
+
const caller = exec.agent
|
|
354
|
+
if (!caller) throw new Error(`${DISPATCH_TOOL} requires a calling agent`)
|
|
355
|
+
|
|
356
|
+
const runId = `rt-${randomUUID().slice(0, 8)}`
|
|
357
|
+
const baseCwd = args.cwd ? resolve(callerCwd(caller), args.cwd) : callerCwd(caller)
|
|
358
|
+
const cfg = currentConfig()
|
|
359
|
+
const requestedTier = resolveToolTier(args.tier, cfg.tiers, DISPATCH_TOOL)
|
|
360
|
+
const classification = classifyTask({
|
|
361
|
+
task: `${args.description}\n${args.prompt}`,
|
|
362
|
+
tier: requestedTier,
|
|
363
|
+
domain: args.domain,
|
|
364
|
+
tiers: cfg.tiers,
|
|
365
|
+
})
|
|
366
|
+
const requirements = inferTaskRequirements(`${args.description}\n${args.prompt}`)
|
|
367
|
+
const preferBackend = args.backend || cfg.preferBackend
|
|
368
|
+
const allowEscalate = args.auto_escalate ?? cfg.autoEscalate
|
|
369
|
+
const timeoutMs = args.timeout_ms ?? cfg.defaultTimeoutMs
|
|
370
|
+
const explicitPermissionMode = args.permission_mode
|
|
371
|
+
const wantBackground = args.background ?? cfg.defaultBackground
|
|
372
|
+
|
|
373
|
+
const [costSnap, contextSnap] = await Promise.all([
|
|
374
|
+
readCostMeterSnapshot(ctx),
|
|
375
|
+
readContextPressure(caller, ctx),
|
|
376
|
+
])
|
|
377
|
+
|
|
378
|
+
const tryTier = async (tierName, escalatedFrom = null, { signal = exec.signal, onProgress } = {}) => {
|
|
379
|
+
const permissionMode = permissionModeForTier(tierName, cfg.tiers, explicitPermissionMode)
|
|
380
|
+
const plan = await buildCandidates({
|
|
381
|
+
ctx,
|
|
382
|
+
caller,
|
|
383
|
+
tier: tierName,
|
|
384
|
+
preferBackend,
|
|
385
|
+
policies: cfg.tiers,
|
|
386
|
+
store,
|
|
387
|
+
cfg,
|
|
388
|
+
})
|
|
389
|
+
if (plan.candidates.length === 0) {
|
|
390
|
+
return { ok: false, error: `No healthy or configured candidates available for tier ${tierName} (backend=${preferBackend})` }
|
|
391
|
+
}
|
|
392
|
+
const adjusted = applyEcosystemPolicies(plan.candidates, {
|
|
393
|
+
tier: tierName,
|
|
394
|
+
band: tierBand(tierName, cfg.tiers),
|
|
395
|
+
costSnap,
|
|
396
|
+
contextSnap,
|
|
397
|
+
cfg,
|
|
398
|
+
routeMetrics: store.getRouteMetrics(),
|
|
399
|
+
})
|
|
400
|
+
const capability = applyCapabilityPolicy(adjusted.candidates, requirements)
|
|
401
|
+
|
|
402
|
+
const attempts = []
|
|
403
|
+
for (const candidate of capability.candidates) {
|
|
404
|
+
if (candidate.kind === 'dsh') {
|
|
405
|
+
try {
|
|
406
|
+
const llm = ctx.get?.('llm')
|
|
407
|
+
if (llm && typeof llm.resolveCallConfig === 'function') {
|
|
408
|
+
await llm.resolveCallConfig({
|
|
409
|
+
provider: candidate.provider,
|
|
410
|
+
model: candidate.model,
|
|
411
|
+
...(candidate.reasoningEffort ? { reasoningEffort: candidate.reasoningEffort } : {}),
|
|
412
|
+
}, signal)
|
|
413
|
+
}
|
|
414
|
+
const maxDepth = typeof ctx.subagents?.resolveMaxDepth === 'function'
|
|
415
|
+
? ctx.subagents.resolveMaxDepth()
|
|
416
|
+
: undefined
|
|
417
|
+
const started = await ctx.subagents.startActivation({
|
|
418
|
+
provider: 'spawn',
|
|
419
|
+
label: args.description,
|
|
420
|
+
cwd: baseCwd,
|
|
421
|
+
prompt: [{ type: 'text', text: escalatedFrom
|
|
422
|
+
? `[Escalated from ${escalatedFrom} due to prior failure]\n\n${args.prompt}`
|
|
423
|
+
: args.prompt }],
|
|
424
|
+
parent: caller,
|
|
425
|
+
agentOptions: {
|
|
426
|
+
provider: candidate.provider,
|
|
427
|
+
model: candidate.model,
|
|
428
|
+
...(candidate.reasoningEffort ? { reasoningEffort: candidate.reasoningEffort } : {}),
|
|
429
|
+
},
|
|
430
|
+
...(maxDepth !== undefined ? { maxDepth } : {}),
|
|
431
|
+
signal,
|
|
432
|
+
delivery: 'parent',
|
|
433
|
+
})
|
|
434
|
+
started.result?.catch?.(() => {})
|
|
435
|
+
store.upsertRun({
|
|
436
|
+
runId,
|
|
437
|
+
description: args.description,
|
|
438
|
+
tier: tierName,
|
|
439
|
+
domain: classification.domain,
|
|
440
|
+
backend: 'dsh',
|
|
441
|
+
routeKey: candidate.key,
|
|
442
|
+
route: `${candidate.provider}/${candidate.model}`,
|
|
443
|
+
model: candidate.model,
|
|
444
|
+
cwd: baseCwd,
|
|
445
|
+
startedAt: Date.now(),
|
|
446
|
+
...(started.childId ? { childId: started.childId } : {}),
|
|
447
|
+
childName: started.name,
|
|
448
|
+
status: 'dispatched',
|
|
449
|
+
escalatedFrom,
|
|
450
|
+
attempts,
|
|
451
|
+
})
|
|
452
|
+
return {
|
|
453
|
+
ok: true,
|
|
454
|
+
mode: 'dsh-subagent',
|
|
455
|
+
runId,
|
|
456
|
+
tier: tierName,
|
|
457
|
+
domain: classification.domain,
|
|
458
|
+
backend: 'dsh',
|
|
459
|
+
route: `${candidate.provider}/${candidate.model}`,
|
|
460
|
+
childName: started.name,
|
|
461
|
+
...(started.childId ? { childId: started.childId } : {}),
|
|
462
|
+
escalatedFrom,
|
|
463
|
+
}
|
|
464
|
+
} catch (err) {
|
|
465
|
+
const msg = redactSecrets(describeThrown(err))
|
|
466
|
+
const errorClass = classifyError(err)
|
|
467
|
+
if (errorClass.cooldown) store.recordFailure(candidate.key, msg)
|
|
468
|
+
attempts.push({
|
|
469
|
+
key: candidate.key,
|
|
470
|
+
error: msg,
|
|
471
|
+
category: errorClass.category,
|
|
472
|
+
retryable: errorClass.retryable,
|
|
473
|
+
escalate: errorClass.escalate,
|
|
474
|
+
hint: errorClass.userHint,
|
|
475
|
+
})
|
|
476
|
+
if (errorClass.category === 'cancelled') {
|
|
477
|
+
return { ok: false, cancelled: true, attempts, error: msg }
|
|
478
|
+
}
|
|
479
|
+
continue
|
|
480
|
+
} }
|
|
481
|
+
|
|
482
|
+
// External CLI candidate (with automatic Git worktree protection if another write task is active in baseCwd)
|
|
483
|
+
let wt = null
|
|
484
|
+
let runCwd = baseCwd
|
|
485
|
+
let autoIsolatedWorktree = false
|
|
486
|
+
const isWriteMode = permissionMode !== 'read-only'
|
|
487
|
+
const activeCount = activeWriteDirs.get(baseCwd) ?? 0
|
|
488
|
+
let wantWorktree = args.use_worktree === true
|
|
489
|
+
if (!wantWorktree && isWriteMode && activeCount > 0) {
|
|
490
|
+
const repoRoot = await getRepoRoot(baseCwd)
|
|
491
|
+
if (repoRoot) {
|
|
492
|
+
wantWorktree = true
|
|
493
|
+
autoIsolatedWorktree = true
|
|
494
|
+
}
|
|
495
|
+
}
|
|
496
|
+
if (wantWorktree) {
|
|
497
|
+
try {
|
|
498
|
+
wt = await createIsolatedWorktree({ cwd: baseCwd, runId })
|
|
499
|
+
runCwd = wt.effectiveCwd || wt.worktreePath
|
|
500
|
+
} catch (wtErr) {
|
|
501
|
+
return { ok: false, error: describeThrown(wtErr) }
|
|
502
|
+
}
|
|
503
|
+
}
|
|
504
|
+
|
|
505
|
+
const effectivePrompt = escalatedFrom
|
|
506
|
+
? `[Escalated from ${escalatedFrom} after earlier failure; please verify assumptions carefully]\n\n${args.prompt}`
|
|
507
|
+
: args.prompt
|
|
508
|
+
|
|
509
|
+
if (isWriteMode && !wt) activeWriteDirs.set(baseCwd, activeCount + 1)
|
|
510
|
+
let res
|
|
511
|
+
try {
|
|
512
|
+
onProgress?.(`Running ${candidate.backend}${candidate.model ? ` (${candidate.model})` : ''}…`)
|
|
513
|
+
res = await executeCliAgent({
|
|
514
|
+
backend: candidate.backend,
|
|
515
|
+
prompt: effectivePrompt,
|
|
516
|
+
cwd: runCwd,
|
|
517
|
+
model: candidate.model,
|
|
518
|
+
effort: candidate.effort,
|
|
519
|
+
permissionMode,
|
|
520
|
+
timeoutMs,
|
|
521
|
+
signal,
|
|
522
|
+
onProgress: (ev) => onProgress?.(ev.text),
|
|
523
|
+
})
|
|
524
|
+
} finally {
|
|
525
|
+
if (isWriteMode && !wt) {
|
|
526
|
+
const cur = activeWriteDirs.get(baseCwd) ?? 1
|
|
527
|
+
if (cur <= 1) activeWriteDirs.delete(baseCwd)
|
|
528
|
+
else activeWriteDirs.set(baseCwd, cur - 1)
|
|
529
|
+
}
|
|
530
|
+
}
|
|
531
|
+
|
|
532
|
+
if (res.ok) {
|
|
533
|
+
store.recordSuccess(candidate.key)
|
|
534
|
+
store.recordRouteMetric(candidate.key, {
|
|
535
|
+
ok: true,
|
|
536
|
+
durationMs: res.durationMs,
|
|
537
|
+
costUsd: res.costUsd ?? null,
|
|
538
|
+
})
|
|
539
|
+
let worktreeDiff = wt ? await inspectWorktreeDiff(wt) : null
|
|
540
|
+
let persistedWt = wt
|
|
541
|
+
// Auto-clean unused worktree when no edits or commits were produced
|
|
542
|
+
if (wt && worktreeDiff && !worktreeDiff.error && !worktreeDiff.dirty && !worktreeDiff.aheadCount) {
|
|
543
|
+
await cleanupIsolatedWorktree({ ...wt, deleteBranch: true }).catch(() => {})
|
|
544
|
+
worktreeDiff = { ...worktreeDiff, cleaned: true }
|
|
545
|
+
persistedWt = null
|
|
546
|
+
}
|
|
547
|
+
const safeText = typeof res.text === 'string' ? res.text : ''
|
|
548
|
+
store.upsertRun({
|
|
549
|
+
runId,
|
|
550
|
+
description: args.description,
|
|
551
|
+
tier: tierName,
|
|
552
|
+
domain: classification.domain,
|
|
553
|
+
backend: candidate.backend,
|
|
554
|
+
routeKey: candidate.key,
|
|
555
|
+
model: res.resolvedModel || candidate.model || null,
|
|
556
|
+
cwd: baseCwd,
|
|
557
|
+
worktree: persistedWt,
|
|
558
|
+
...(persistedWt === null && wt ? { worktreeCleaned: true } : {}),
|
|
559
|
+
sessionId: res.sessionId ?? null,
|
|
560
|
+
status: 'completed',
|
|
561
|
+
durationMs: res.durationMs,
|
|
562
|
+
costUsd: res.costUsd ?? null,
|
|
563
|
+
usage: res.usage ?? null,
|
|
564
|
+
escalatedFrom,
|
|
565
|
+
summary: redactSecrets(safeText.slice(0, 500)),
|
|
566
|
+
})
|
|
567
|
+
return {
|
|
568
|
+
ok: true,
|
|
569
|
+
mode: 'cli',
|
|
570
|
+
runId,
|
|
571
|
+
tier: tierName,
|
|
572
|
+
domain: classification.domain,
|
|
573
|
+
backend: candidate.backend,
|
|
574
|
+
model: res.resolvedModel || candidate.model || null,
|
|
575
|
+
requestedModel: res.requestedModel || null,
|
|
576
|
+
sessionId: res.sessionId ?? null,
|
|
577
|
+
durationMs: res.durationMs,
|
|
578
|
+
costUsd: res.costUsd ?? null,
|
|
579
|
+
usage: res.usage ?? null,
|
|
580
|
+
worktreeDiff,
|
|
581
|
+
...(autoIsolatedWorktree ? { autoIsolatedWorktree: true } : {}),
|
|
582
|
+
escalatedFrom,
|
|
583
|
+
output: safeText,
|
|
584
|
+
}
|
|
585
|
+
}
|
|
586
|
+
|
|
587
|
+
// Candidate failed: classify before deciding cooldown/escalation.
|
|
588
|
+
const failureClass = classifyError(res)
|
|
589
|
+
const failureText = redactSecrets(failureClass.message || 'CLI execution failed')
|
|
590
|
+
if (failureClass.cooldown) store.recordFailure(candidate.key, failureText)
|
|
591
|
+
store.recordRouteMetric(candidate.key, { ok: false, durationMs: res.durationMs })
|
|
592
|
+
attempts.push({
|
|
593
|
+
key: candidate.key,
|
|
594
|
+
error: failureText,
|
|
595
|
+
category: failureClass.category,
|
|
596
|
+
retryable: failureClass.retryable,
|
|
597
|
+
escalate: failureClass.escalate,
|
|
598
|
+
hint: failureClass.userHint,
|
|
599
|
+
})
|
|
600
|
+
if (wt) {
|
|
601
|
+
const diff = await inspectWorktreeDiff(wt)
|
|
602
|
+
if (!diff.dirty && !diff.aheadCount) {
|
|
603
|
+
await cleanupIsolatedWorktree({ ...wt, deleteBranch: true })
|
|
604
|
+
}
|
|
605
|
+
}
|
|
606
|
+
if (failureClass.category === 'cancelled') {
|
|
607
|
+
return { ok: false, cancelled: true, attempts, error: failureText }
|
|
608
|
+
}
|
|
609
|
+
}
|
|
610
|
+
|
|
611
|
+
return {
|
|
612
|
+
ok: false,
|
|
613
|
+
attempts,
|
|
614
|
+
error: attempts.map(a => `${a.key}: ${a.error}`).join(' | '),
|
|
615
|
+
escalate: shouldEscalateAfter(attempts),
|
|
616
|
+
userHints: [...new Set(attempts.map(a => a.hint).filter(Boolean))],
|
|
617
|
+
}
|
|
618
|
+
}
|
|
619
|
+
|
|
620
|
+
const runFullAttempt = async ({ signal, onProgress } = {}) => {
|
|
621
|
+
let outcome = await tryTier(classification.tier, null, { signal, onProgress })
|
|
622
|
+
if (!outcome.ok && !outcome.cancelled && allowEscalate && !signal?.aborted) {
|
|
623
|
+
if (outcome.escalate === false) {
|
|
624
|
+
// Auth / invalid-argument / cancellation failures will not improve in a
|
|
625
|
+
// higher tier, so keep the run at the original tier and surface hints.
|
|
626
|
+
outcome.escalationSkipped = true
|
|
627
|
+
} else {
|
|
628
|
+
const escTier = nextEscalationTier(classification.tier, cfg.tiers)
|
|
629
|
+
if (escTier) {
|
|
630
|
+
outcome = await tryTier(escTier, classification.tier, { signal, onProgress })
|
|
631
|
+
}
|
|
632
|
+
}
|
|
633
|
+
}
|
|
634
|
+
return outcome
|
|
635
|
+
}
|
|
636
|
+
|
|
637
|
+
if (wantBackground) {
|
|
638
|
+
const peekPlan = await buildCandidates({
|
|
639
|
+
ctx,
|
|
640
|
+
caller,
|
|
641
|
+
tier: classification.tier,
|
|
642
|
+
preferBackend,
|
|
643
|
+
policies: cfg.tiers,
|
|
644
|
+
store,
|
|
645
|
+
cfg,
|
|
646
|
+
})
|
|
647
|
+
const firstCand = peekPlan.candidates[0]
|
|
648
|
+
if (!firstCand || firstCand.kind !== 'dsh') {
|
|
649
|
+
store.upsertRun({
|
|
650
|
+
runId,
|
|
651
|
+
description: args.description,
|
|
652
|
+
tier: classification.tier,
|
|
653
|
+
domain: classification.domain,
|
|
654
|
+
backend: firstCand?.backend || preferBackend,
|
|
655
|
+
model: firstCand?.model || null,
|
|
656
|
+
cwd: baseCwd,
|
|
657
|
+
status: 'queued',
|
|
658
|
+
startedAt: Date.now(),
|
|
659
|
+
})
|
|
660
|
+
const jobSnap = queue.enqueue({
|
|
661
|
+
runId,
|
|
662
|
+
parentSessionId: caller.session?.id || caller.id,
|
|
663
|
+
description: args.description,
|
|
664
|
+
tier: classification.tier,
|
|
665
|
+
backend: firstCand?.backend || preferBackend,
|
|
666
|
+
...(exec.callId ? { toolCall: { callId: exec.callId, rootCallId: exec.callId } } : {}),
|
|
667
|
+
execute: ({ signal, updateProgress }) => runFullAttempt({ signal, onProgress: updateProgress }),
|
|
668
|
+
onUpdate: (job) => {
|
|
669
|
+
store.upsertRun({
|
|
670
|
+
runId,
|
|
671
|
+
status: job.status,
|
|
672
|
+
progress: job.progress,
|
|
673
|
+
})
|
|
674
|
+
},
|
|
675
|
+
onDone: (job, outcome) => {
|
|
676
|
+
if (!outcome?.ok && job.status !== 'completed') {
|
|
677
|
+
store.upsertRun({
|
|
678
|
+
runId,
|
|
679
|
+
status: job.status === 'cancelled' ? 'cancelled' : 'failed',
|
|
680
|
+
error: outcome?.error || job.progress || 'async execution failed',
|
|
681
|
+
durationMs: job.elapsedMs,
|
|
682
|
+
})
|
|
683
|
+
}
|
|
684
|
+
const summaryText = outcome?.ok
|
|
685
|
+
? (outcome.mode === 'dsh-subagent'
|
|
686
|
+
? `[dsh-agent-router] Background run ${runId} handed off to DSH subagent "${outcome.childName}".`
|
|
687
|
+
: `[dsh-agent-router] Background CLI run ${runId} (${outcome.backend}${outcome.model ? '/' + outcome.model : ''}, ${outcome.tier}, ${outcome.durationMs}ms) completed.${outcome.worktreeDiff ? `\nWorktree branch: ${outcome.worktreeDiff.branch} (dirty=${outcome.worktreeDiff.dirty}, ahead=${outcome.worktreeDiff.aheadCount ?? 0})` : ''}\n\n${String(outcome.output || '').slice(0, 4000)}`)
|
|
688
|
+
: `[dsh-agent-router] Background CLI run ${runId} (${classification.tier}) ${job.status}: ${outcome?.error || job.progress || 'unknown error'}`
|
|
689
|
+
notifyParentAgent(
|
|
690
|
+
caller,
|
|
691
|
+
summaryText,
|
|
692
|
+
exec.callId ? { kind: 'tool', callId: exec.callId } : undefined,
|
|
693
|
+
)
|
|
694
|
+
},
|
|
695
|
+
})
|
|
696
|
+
return toLosslessJson({
|
|
697
|
+
ok: true,
|
|
698
|
+
mode: 'cli-async',
|
|
699
|
+
runId,
|
|
700
|
+
tier: classification.tier,
|
|
701
|
+
domain: classification.domain,
|
|
702
|
+
backend: firstCand?.backend || preferBackend,
|
|
703
|
+
status: jobSnap.status,
|
|
704
|
+
progress: jobSnap.progress,
|
|
705
|
+
})
|
|
706
|
+
}
|
|
707
|
+
}
|
|
708
|
+
|
|
709
|
+
let outcome = await runFullAttempt({ signal: exec.signal })
|
|
710
|
+
|
|
711
|
+
if (!outcome.ok) {
|
|
712
|
+
store.upsertRun({
|
|
713
|
+
runId,
|
|
714
|
+
description: args.description,
|
|
715
|
+
tier: classification.tier,
|
|
716
|
+
domain: classification.domain,
|
|
717
|
+
backend: preferBackend,
|
|
718
|
+
cwd: baseCwd,
|
|
719
|
+
status: 'failed',
|
|
720
|
+
error: outcome.error || 'routing failed',
|
|
721
|
+
})
|
|
722
|
+
return toLosslessJson({
|
|
723
|
+
ok: false,
|
|
724
|
+
mode: 'cli',
|
|
725
|
+
runId,
|
|
726
|
+
tier: classification.tier,
|
|
727
|
+
backend: preferBackend,
|
|
728
|
+
durationMs: 0,
|
|
729
|
+
error: outcome.error || 'routing failed',
|
|
730
|
+
cancelled: outcome.cancelled === true,
|
|
731
|
+
escalationSkipped: outcome.escalationSkipped === true,
|
|
732
|
+
attempts: outcome.attempts || [],
|
|
733
|
+
userHints: outcome.userHints || [],
|
|
734
|
+
})
|
|
735
|
+
}
|
|
736
|
+
|
|
737
|
+
return toLosslessJson(outcome)
|
|
738
|
+
},
|
|
739
|
+
})
|
|
740
|
+
|
|
741
|
+
// 3. router_continue
|
|
742
|
+
ctx.tools.register({
|
|
743
|
+
name: CONTINUE_TOOL,
|
|
744
|
+
description:
|
|
745
|
+
'Continue an existing routed session (DSH subagent or local CLI claude/codex/gemini/opencode/antigravity) using its recorded run_id or subagent name, preserving conversation thread and workspace/worktree.',
|
|
746
|
+
parameters: CONTINUE_PARAMETERS,
|
|
747
|
+
output: {
|
|
748
|
+
schema: {
|
|
749
|
+
type: 'object',
|
|
750
|
+
additionalProperties: true,
|
|
751
|
+
required: ['ok', 'mode', 'runId'],
|
|
752
|
+
properties: {
|
|
753
|
+
ok: { type: 'boolean' },
|
|
754
|
+
mode: { type: 'string' },
|
|
755
|
+
runId: { type: 'string' },
|
|
756
|
+
},
|
|
757
|
+
},
|
|
758
|
+
render: (_args, val) => [{
|
|
759
|
+
type: 'text',
|
|
760
|
+
text: val.mode === 'dsh-subagent'
|
|
761
|
+
? `[${val.runId}] Continuation delivered to DSH subagent ${val.target} (resumed=${val.resumed}).`
|
|
762
|
+
: `[${val.runId}] Continued ${val.backend} (${val.durationMs}ms)\n\n${val.ok ? val.output : `Error: ${val.error}`}`,
|
|
763
|
+
}],
|
|
764
|
+
},
|
|
765
|
+
isConcurrencySafe: () => true,
|
|
766
|
+
async execute(args, exec) {
|
|
767
|
+
validateToolArguments(CONTINUE_TOOL, CONTINUE_PARAMETERS, args)
|
|
768
|
+
const caller = exec.agent
|
|
769
|
+
if (!caller) throw new Error(`${CONTINUE_TOOL} requires a calling agent`)
|
|
770
|
+
|
|
771
|
+
const run = store.findRun(args.run_id)
|
|
772
|
+
if (!run || run.backend === 'dsh') {
|
|
773
|
+
const target = run?.childId || run?.childName || args.run_id
|
|
774
|
+
const res = await continueDshChild(caller, target, args.message, exec.signal)
|
|
775
|
+
if (run) {
|
|
776
|
+
store.upsertRun({ runId: run.runId, childId: res.targetId, status: 'dispatched' })
|
|
777
|
+
}
|
|
778
|
+
return toLosslessJson({
|
|
779
|
+
ok: true,
|
|
780
|
+
mode: 'dsh-subagent',
|
|
781
|
+
runId: run?.runId || args.run_id,
|
|
782
|
+
target,
|
|
783
|
+
resumed: res.resumed,
|
|
784
|
+
messageId: res.messageId,
|
|
785
|
+
})
|
|
786
|
+
}
|
|
787
|
+
|
|
788
|
+
if (!run.sessionId) {
|
|
789
|
+
throw new Error(`Run "${run.runId}" (${run.backend}) has no recorded sessionId and cannot be resumed`)
|
|
790
|
+
}
|
|
791
|
+
|
|
792
|
+
const workCwd = run.worktree?.effectiveCwd || run.worktree?.worktreePath || run.cwd || callerCwd(caller)
|
|
793
|
+
const res = await executeCliAgent({
|
|
794
|
+
backend: run.backend,
|
|
795
|
+
prompt: args.message,
|
|
796
|
+
cwd: workCwd,
|
|
797
|
+
model: run.model || undefined,
|
|
798
|
+
resumeSessionId: run.sessionId,
|
|
799
|
+
timeoutMs: args.timeout_ms ?? currentConfig().defaultTimeoutMs,
|
|
800
|
+
signal: exec.signal,
|
|
801
|
+
})
|
|
802
|
+
|
|
803
|
+
const worktreeDiff = run.worktree ? await inspectWorktreeDiff(run.worktree) : null
|
|
804
|
+
const safeText = typeof res.text === 'string' ? res.text : ''
|
|
805
|
+
if (run.routeKey) {
|
|
806
|
+
store.recordRouteMetric(run.routeKey, {
|
|
807
|
+
ok: res.ok,
|
|
808
|
+
durationMs: res.durationMs,
|
|
809
|
+
costUsd: res.costUsd ?? null,
|
|
810
|
+
})
|
|
811
|
+
}
|
|
812
|
+
store.upsertRun({
|
|
813
|
+
runId: run.runId,
|
|
814
|
+
sessionId: res.sessionId || run.sessionId,
|
|
815
|
+
status: res.ok ? 'completed' : 'failed',
|
|
816
|
+
durationMs: (run.durationMs || 0) + (res.durationMs || 0),
|
|
817
|
+
error: res.ok ? null : (res.error || 'CLI continuation failed'),
|
|
818
|
+
summary: res.ok ? redactSecrets(safeText.slice(0, 500)) : (run.summary ?? null),
|
|
819
|
+
})
|
|
820
|
+
|
|
821
|
+
return toLosslessJson({
|
|
822
|
+
ok: res.ok,
|
|
823
|
+
mode: 'cli',
|
|
824
|
+
runId: run.runId,
|
|
825
|
+
backend: run.backend,
|
|
826
|
+
sessionId: res.sessionId || run.sessionId,
|
|
827
|
+
durationMs: res.durationMs || 0,
|
|
828
|
+
worktreeDiff,
|
|
829
|
+
output: safeText,
|
|
830
|
+
error: res.error ?? null,
|
|
831
|
+
})
|
|
832
|
+
},
|
|
833
|
+
})
|
|
834
|
+
|
|
835
|
+
// 4. router_status
|
|
836
|
+
ctx.tools.register({
|
|
837
|
+
name: STATUS_TOOL,
|
|
838
|
+
description:
|
|
839
|
+
'Inspect router health, config, runs, and active background CLI jobs; run environment diagnostics with action "doctor"; inspect/merge/cleanup Worktree diffs; or cancel runs.',
|
|
840
|
+
parameters: STATUS_PARAMETERS,
|
|
841
|
+
output: {
|
|
842
|
+
schema: {
|
|
843
|
+
type: 'object',
|
|
844
|
+
additionalProperties: true,
|
|
845
|
+
required: ['action'],
|
|
846
|
+
properties: { action: { type: 'string' } },
|
|
847
|
+
},
|
|
848
|
+
render: (_args, val) => [{ type: 'text', text: JSON.stringify(val, null, 2) }],
|
|
849
|
+
},
|
|
850
|
+
isConcurrencySafe: () => true,
|
|
851
|
+
async execute(args) {
|
|
852
|
+
validateToolArguments(STATUS_TOOL, STATUS_PARAMETERS, args)
|
|
853
|
+
const action = args.action || 'overview'
|
|
854
|
+
if (action === 'config') {
|
|
855
|
+
return toLosslessJson({
|
|
856
|
+
action,
|
|
857
|
+
configSource: getConfigSource(),
|
|
858
|
+
config: currentConfig(),
|
|
859
|
+
})
|
|
860
|
+
}
|
|
861
|
+
if (action === 'active_jobs') {
|
|
862
|
+
return toLosslessJson({ action, jobs: queue.listActive() })
|
|
863
|
+
}
|
|
864
|
+
if (action === 'run_status') {
|
|
865
|
+
if (!args.run_id) throw new Error('run_status requires run_id')
|
|
866
|
+
const run = store.findRun(args.run_id)
|
|
867
|
+
const job = queue.get(args.run_id)
|
|
868
|
+
return toLosslessJson({
|
|
869
|
+
action,
|
|
870
|
+
runId: run?.runId || args.run_id,
|
|
871
|
+
status: job?.status || run?.status || 'unknown',
|
|
872
|
+
progress: job?.progress || run?.progress || null,
|
|
873
|
+
elapsedMs: job?.elapsedMs ?? null,
|
|
874
|
+
tier: job?.tier || run?.tier || null,
|
|
875
|
+
backend: job?.backend || run?.backend || null,
|
|
876
|
+
routeKey: run?.routeKey || null,
|
|
877
|
+
sessionId: run?.sessionId || null,
|
|
878
|
+
attempts: Array.isArray(run?.attempts) ? run.attempts : [],
|
|
879
|
+
})
|
|
880
|
+
}
|
|
881
|
+
if (action === 'doctor') {
|
|
882
|
+
const report = await buildDoctorReport({ ctx, cfg: currentConfig(), store, queue })
|
|
883
|
+
return toLosslessJson({ action, ...report })
|
|
884
|
+
}
|
|
885
|
+
if (action === 'cancel_run') {
|
|
886
|
+
if (!args.run_id) throw new Error('cancel_run requires run_id')
|
|
887
|
+
const res = queue.cancel(args.run_id, 'cancelled via router_status')
|
|
888
|
+
if (res.cancelled) {
|
|
889
|
+
store.upsertRun({ runId: args.run_id, status: 'cancelled', progress: 'cancelled via router_status' })
|
|
890
|
+
}
|
|
891
|
+
return toLosslessJson({ action, runId: args.run_id, ...res })
|
|
892
|
+
}
|
|
893
|
+
if (action === 'clear_cooldowns') {
|
|
894
|
+
const cleared = store.clearCooldowns(args.run_id)
|
|
895
|
+
return toLosslessJson({ action, cleared })
|
|
896
|
+
}
|
|
897
|
+
if (action === 'rate_run') {
|
|
898
|
+
if (!args.run_id) throw new Error('rate_run requires run_id')
|
|
899
|
+
const updated = store.addFeedback(args.run_id, { rating: args.quality, comment: args.comment })
|
|
900
|
+
if (!updated) throw new Error(`No run "${args.run_id}"`)
|
|
901
|
+
return toLosslessJson({ action, runId: args.run_id, quality: updated.quality || null })
|
|
902
|
+
}
|
|
903
|
+
if (action === 'sessions') {
|
|
904
|
+
return toLosslessJson({ action, sessions: listSessions(store.listRuns(500)) })
|
|
905
|
+
}
|
|
906
|
+
if (action === 'prune_sessions') {
|
|
907
|
+
const pruned = pruneSessions(store.listRuns(500), {
|
|
908
|
+
keep: args.keep ?? 50,
|
|
909
|
+
maxAgeMs: typeof args.max_age_ms === 'number' ? args.max_age_ms : null,
|
|
910
|
+
})
|
|
911
|
+
store.replaceRuns(pruned.kept)
|
|
912
|
+
return toLosslessJson({
|
|
913
|
+
action,
|
|
914
|
+
removedCount: pruned.removed.length,
|
|
915
|
+
keptCount: pruned.kept.length,
|
|
916
|
+
sessionCount: pruned.sessions.length,
|
|
917
|
+
})
|
|
918
|
+
}
|
|
919
|
+
if (action === 'inspect_worktree_diff') {
|
|
920
|
+
if (!args.run_id) throw new Error('inspect_worktree_diff requires run_id')
|
|
921
|
+
const run = store.findRun(args.run_id)
|
|
922
|
+
const wt = requireWorktree(run)
|
|
923
|
+
const diff = await readWorktreePatch(wt, { maxBytes: args.max_bytes })
|
|
924
|
+
return toLosslessJson({ action, runId: run.runId, ...diff })
|
|
925
|
+
}
|
|
926
|
+
if (action === 'merge_worktree') {
|
|
927
|
+
if (!args.run_id) throw new Error('merge_worktree requires run_id')
|
|
928
|
+
const run = store.findRun(args.run_id)
|
|
929
|
+
const wt = requireWorktree(run)
|
|
930
|
+
const lock = acquireWorktreeLock(wt.repoRoot)
|
|
931
|
+
if (!lock.acquired) {
|
|
932
|
+
return toLosslessJson({
|
|
933
|
+
action,
|
|
934
|
+
runId: run.runId,
|
|
935
|
+
merged: false,
|
|
936
|
+
error: `Another worktree operation is already running for "${wt.repoRoot}"`,
|
|
937
|
+
lockReason: lock.reason || 'held',
|
|
938
|
+
})
|
|
939
|
+
}
|
|
940
|
+
let res
|
|
941
|
+
try {
|
|
942
|
+
res = await mergeIsolatedWorktree(wt, {
|
|
943
|
+
strategy: args.strategy,
|
|
944
|
+
commitMessage: args.commit_message,
|
|
945
|
+
cleanup: args.cleanup !== false,
|
|
946
|
+
})
|
|
947
|
+
} finally {
|
|
948
|
+
lock.release()
|
|
949
|
+
}
|
|
950
|
+
if (res.merged) {
|
|
951
|
+
store.upsertRun({
|
|
952
|
+
runId: run.runId,
|
|
953
|
+
mergedAt: Date.now(),
|
|
954
|
+
mergeCommit: res.mergeCommit,
|
|
955
|
+
...(res.cleaned ? { worktreeCleaned: true } : {}),
|
|
956
|
+
})
|
|
957
|
+
} else if (res.cleaned) {
|
|
958
|
+
store.upsertRun({ runId: run.runId, worktreeCleaned: true })
|
|
959
|
+
}
|
|
960
|
+
return toLosslessJson({ action, runId: run.runId, ...res })
|
|
961
|
+
}
|
|
962
|
+
if (action === 'cleanup_worktree') {
|
|
963
|
+
if (!args.run_id) throw new Error('cleanup_worktree requires run_id')
|
|
964
|
+
const run = store.findRun(args.run_id)
|
|
965
|
+
const wt = requireWorktree(run)
|
|
966
|
+
await cleanupIsolatedWorktree({ ...wt, deleteBranch: args.delete_branch === true })
|
|
967
|
+
store.upsertRun({ runId: run.runId, worktreeCleaned: true })
|
|
968
|
+
return toLosslessJson({ action, runId: run.runId, cleaned: true, branchDeleted: args.delete_branch === true })
|
|
969
|
+
}
|
|
970
|
+
if (action === 'prune_worktrees') {
|
|
971
|
+
const cleaned = []
|
|
972
|
+
const skipped = []
|
|
973
|
+
for (const run of store.listRuns(200)) {
|
|
974
|
+
if (!run.worktree || run.worktreeCleaned || run.status === 'dispatched' || run.status === 'running' || run.status === 'queued') continue
|
|
975
|
+
try {
|
|
976
|
+
assertPathWithin(worktreeBase, run.worktree.worktreePath, 'worktree path')
|
|
977
|
+
} catch (err) {
|
|
978
|
+
skipped.push({ runId: run.runId, reason: describeThrown(err) })
|
|
979
|
+
continue
|
|
980
|
+
}
|
|
981
|
+
const lock = acquireWorktreeLock(run.worktree.repoRoot)
|
|
982
|
+
if (!lock.acquired) {
|
|
983
|
+
skipped.push({ runId: run.runId, reason: `merge lock ${lock.reason || 'held'}` })
|
|
984
|
+
continue
|
|
985
|
+
}
|
|
986
|
+
try {
|
|
987
|
+
await cleanupIsolatedWorktree({ ...run.worktree, deleteBranch: args.delete_branch === true }).catch(() => {})
|
|
988
|
+
} finally {
|
|
989
|
+
lock.release()
|
|
990
|
+
}
|
|
991
|
+
store.upsertRun({ runId: run.runId, worktreeCleaned: true })
|
|
992
|
+
cleaned.push(run.runId)
|
|
993
|
+
}
|
|
994
|
+
return toLosslessJson({ action, cleanedCount: cleaned.length, cleaned, skipped })
|
|
995
|
+
}
|
|
996
|
+
if (action === 'runs') {
|
|
997
|
+
return toLosslessJson({ action, runs: store.listRuns(args.limit ?? 15) })
|
|
998
|
+
}
|
|
999
|
+
return toLosslessJson({
|
|
1000
|
+
action: 'overview',
|
|
1001
|
+
configSource: getConfigSource(),
|
|
1002
|
+
localClis: probeLocalClis(),
|
|
1003
|
+
cliModels: discoverCliModels(),
|
|
1004
|
+
subagentModelSelection: readSubagentModelSelectionStatus(ctx),
|
|
1005
|
+
costMeter: await readCostMeterSnapshot(ctx),
|
|
1006
|
+
doctor: await buildDoctorReport({ ctx, cfg: currentConfig(), store, queue }),
|
|
1007
|
+
cooldowns: store.activeCooldowns(),
|
|
1008
|
+
activeJobs: queue.listActive(),
|
|
1009
|
+
routeMetrics: store.getRouteMetrics(),
|
|
1010
|
+
stats: store.stats(),
|
|
1011
|
+
recentRuns: store.listRuns(args.limit ?? 10),
|
|
1012
|
+
tierSummary: Object.fromEntries(
|
|
1013
|
+
sortTierEntries(currentConfig().tiers).map(([tierId, cur]) => [
|
|
1014
|
+
tierId,
|
|
1015
|
+
{
|
|
1016
|
+
name: cur.name || cur.label || tierId,
|
|
1017
|
+
role: cur.role,
|
|
1018
|
+
minScore: cur.minScore,
|
|
1019
|
+
maxScore: cur.maxScore,
|
|
1020
|
+
preferBackend: cur.preferBackend,
|
|
1021
|
+
escalateTo: cur.escalateTo,
|
|
1022
|
+
},
|
|
1023
|
+
]),
|
|
1024
|
+
),
|
|
1025
|
+
})
|
|
1026
|
+
},
|
|
1027
|
+
})
|
|
1028
|
+
}
|