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,187 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Local agent CLI detection and configured model discovery.
|
|
3
|
+
* @module dsh-agent-router/lib/cli/discover
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
import { homedir } from 'node:os'
|
|
7
|
+
import { join } from 'node:path'
|
|
8
|
+
|
|
9
|
+
import { findOnPath, safeReadJson, safeReadJsonc, safeReadText } from './shared.js'
|
|
10
|
+
|
|
11
|
+
export const SUPPORTED_CLIS = ['claude', 'codex', 'gemini', 'opencode', 'antigravity']
|
|
12
|
+
|
|
13
|
+
/** Backend id -> executable name when they differ (Antigravity ships as `agy`). */
|
|
14
|
+
export const CLI_BINARIES = Object.freeze({
|
|
15
|
+
antigravity: 'agy',
|
|
16
|
+
})
|
|
17
|
+
|
|
18
|
+
export function cliBinaryName(backend) {
|
|
19
|
+
return CLI_BINARIES[backend] || backend
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* Probe which supported local CLIs are currently installed.
|
|
24
|
+
* @returns {Record<string, { installed: boolean, path: string|null }>}
|
|
25
|
+
*/
|
|
26
|
+
export function probeLocalClis() {
|
|
27
|
+
const result = {}
|
|
28
|
+
for (const name of SUPPORTED_CLIS) {
|
|
29
|
+
const path = findOnPath(cliBinaryName(name))
|
|
30
|
+
result[name] = { installed: path !== null, path }
|
|
31
|
+
}
|
|
32
|
+
return result
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* Discover each local CLI's configured default model and available model IDs
|
|
37
|
+
* from local config files (without exposing credentials or API keys).
|
|
38
|
+
* @param {string} [home]
|
|
39
|
+
*/
|
|
40
|
+
export function discoverCliModels(home = homedir()) {
|
|
41
|
+
const out = {
|
|
42
|
+
claude: { defaultModel: null, models: [] },
|
|
43
|
+
codex: { defaultModel: null, providers: [], models: [] },
|
|
44
|
+
gemini: { defaultModel: null, models: [] },
|
|
45
|
+
opencode: { defaultModel: null, models: [] },
|
|
46
|
+
antigravity: { defaultModel: null, models: [] },
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
// 1. Claude Code (~/.claude/settings.json or CLAUDE_CONFIG_DIR)
|
|
50
|
+
const claudeDir = process.env.CLAUDE_CONFIG_DIR || join(home, '.claude')
|
|
51
|
+
const claudeCfg = safeReadJson(join(claudeDir, 'settings.json'))
|
|
52
|
+
if (claudeCfg && typeof claudeCfg === 'object') {
|
|
53
|
+
const seen = new Set()
|
|
54
|
+
const pushClaude = (m) => {
|
|
55
|
+
if (typeof m === 'string' && m.trim() && !seen.has(m.trim())) {
|
|
56
|
+
seen.add(m.trim())
|
|
57
|
+
out.claude.models.push(m.trim())
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
if (typeof claudeCfg.model === 'string') {
|
|
61
|
+
out.claude.defaultModel = claudeCfg.model
|
|
62
|
+
pushClaude(claudeCfg.model)
|
|
63
|
+
}
|
|
64
|
+
const env = claudeCfg.env && typeof claudeCfg.env === 'object' ? claudeCfg.env : {}
|
|
65
|
+
if (typeof env.EASYCLIPROXY_CLAUDE_CODE_MODEL_SETTINGS === 'string') {
|
|
66
|
+
try {
|
|
67
|
+
const list = JSON.parse(env.EASYCLIPROXY_CLAUDE_CODE_MODEL_SETTINGS)
|
|
68
|
+
if (Array.isArray(list)) list.forEach(pushClaude)
|
|
69
|
+
} catch {}
|
|
70
|
+
}
|
|
71
|
+
if (claudeCfg.modelSettings && typeof claudeCfg.modelSettings === 'object') {
|
|
72
|
+
Object.keys(claudeCfg.modelSettings).forEach(pushClaude)
|
|
73
|
+
}
|
|
74
|
+
for (const k of ['ANTHROPIC_DEFAULT_OPUS_MODEL', 'ANTHROPIC_DEFAULT_SONNET_MODEL', 'ANTHROPIC_DEFAULT_HAIKU_MODEL', 'ANTHROPIC_DEFAULT_FABLE_MODEL']) {
|
|
75
|
+
if (typeof env[k] === 'string') pushClaude(env[k])
|
|
76
|
+
}
|
|
77
|
+
for (const alias of ['opus', 'sonnet', 'haiku']) pushClaude(alias)
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
// 2. Codex (~/.codex/config.toml or CODEX_HOME + cpa-gui-model-catalog.json / models_cache.json)
|
|
81
|
+
const codexDir = process.env.CODEX_HOME || join(home, '.codex')
|
|
82
|
+
const codexToml = safeReadText(join(codexDir, 'config.toml'))
|
|
83
|
+
if (codexToml) {
|
|
84
|
+
const seen = new Set()
|
|
85
|
+
const pushCodex = (m) => {
|
|
86
|
+
if (typeof m === 'string' && m.trim() && !seen.has(m.trim())) {
|
|
87
|
+
seen.add(m.trim())
|
|
88
|
+
out.codex.models.push(m.trim())
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
const defModel = codexToml.match(/^\s*model\s*=\s*"([^"]+)"/m)?.[1]
|
|
92
|
+
const defProv = codexToml.match(/^\s*model_provider\s*=\s*"([^"]+)"/m)?.[1]
|
|
93
|
+
if (defModel) {
|
|
94
|
+
out.codex.defaultModel = defProv ? `${defProv}/${defModel}` : defModel
|
|
95
|
+
pushCodex(defModel)
|
|
96
|
+
}
|
|
97
|
+
const provMatches = codexToml.matchAll(/^\s*\[model_providers\.([A-Za-z0-9_-]+)\]/gm)
|
|
98
|
+
for (const m of provMatches) {
|
|
99
|
+
if (!out.codex.providers.includes(m[1])) out.codex.providers.push(m[1])
|
|
100
|
+
}
|
|
101
|
+
for (const file of ['cpa-gui-model-catalog.json', 'models_cache.json']) {
|
|
102
|
+
const cat = safeReadJson(join(codexDir, file))
|
|
103
|
+
const list = Array.isArray(cat?.models) ? cat.models : []
|
|
104
|
+
for (const item of list.slice(0, 40)) {
|
|
105
|
+
const slug = item?.slug || item?.id
|
|
106
|
+
if (typeof slug === 'string') pushCodex(slug)
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
// 3. Gemini CLI (~/.gemini/settings.json or GEMINI_CLI_HOME)
|
|
112
|
+
const geminiDir = process.env.GEMINI_CLI_HOME ? join(process.env.GEMINI_CLI_HOME, '.gemini') : join(home, '.gemini')
|
|
113
|
+
const geminiCfg = safeReadJson(join(geminiDir, 'settings.json'))
|
|
114
|
+
if (geminiCfg && typeof geminiCfg === 'object') {
|
|
115
|
+
const seen = new Set()
|
|
116
|
+
const pushGemini = (m) => {
|
|
117
|
+
if (typeof m === 'string' && m.trim() && !seen.has(m.trim())) {
|
|
118
|
+
seen.add(m.trim())
|
|
119
|
+
out.gemini.models.push(m.trim())
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
if (typeof geminiCfg.model === 'string') {
|
|
123
|
+
out.gemini.defaultModel = geminiCfg.model
|
|
124
|
+
pushGemini(geminiCfg.model)
|
|
125
|
+
}
|
|
126
|
+
for (const alias of ['auto', 'pro', 'flash', 'flash-lite']) pushGemini(alias)
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
// 4. OpenCode (OPENCODE_CONFIG, XDG_CONFIG_HOME/opencode/opencode.json[c], ~/.config/opencode/opencode.json[c])
|
|
130
|
+
const ocCandidates = [
|
|
131
|
+
process.env.OPENCODE_CONFIG,
|
|
132
|
+
process.env.XDG_CONFIG_HOME ? join(process.env.XDG_CONFIG_HOME, 'opencode', 'opencode.jsonc') : null,
|
|
133
|
+
process.env.XDG_CONFIG_HOME ? join(process.env.XDG_CONFIG_HOME, 'opencode', 'opencode.json') : null,
|
|
134
|
+
join(home, '.config', 'opencode', 'opencode.jsonc'),
|
|
135
|
+
join(home, '.config', 'opencode', 'opencode.json'),
|
|
136
|
+
].filter(Boolean)
|
|
137
|
+
let ocCfg = null
|
|
138
|
+
for (const p of ocCandidates) {
|
|
139
|
+
ocCfg = p.endsWith('.jsonc') ? safeReadJsonc(p) : (safeReadJson(p) || safeReadJsonc(p))
|
|
140
|
+
if (ocCfg && typeof ocCfg === 'object') break
|
|
141
|
+
}
|
|
142
|
+
if (ocCfg && typeof ocCfg === 'object') {
|
|
143
|
+
const seen = new Set()
|
|
144
|
+
const pushOc = (m) => {
|
|
145
|
+
if (typeof m === 'string' && m.trim() && !seen.has(m.trim())) {
|
|
146
|
+
seen.add(m.trim())
|
|
147
|
+
out.opencode.models.push(m.trim())
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
if (typeof ocCfg.model === 'string') {
|
|
151
|
+
out.opencode.defaultModel = ocCfg.model
|
|
152
|
+
pushOc(ocCfg.model)
|
|
153
|
+
}
|
|
154
|
+
if (ocCfg.provider && typeof ocCfg.provider === 'object') {
|
|
155
|
+
for (const [provId, prov] of Object.entries(ocCfg.provider)) {
|
|
156
|
+
if (!prov || typeof prov !== 'object' || !prov.models || typeof prov.models !== 'object') continue
|
|
157
|
+
for (const modelId of Object.keys(prov.models)) {
|
|
158
|
+
pushOc(`${provId}/${modelId}`)
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
// 5. Antigravity CLI (~/.gemini/antigravity-cli/settings.json)
|
|
165
|
+
const agCfg = safeReadJson(join(home, '.gemini', 'antigravity-cli', 'settings.json'))
|
|
166
|
+
if (agCfg && typeof agCfg === 'object') {
|
|
167
|
+
const seen = new Set()
|
|
168
|
+
const pushAg = (m) => {
|
|
169
|
+
if (typeof m === 'string' && m.trim() && !seen.has(m.trim())) {
|
|
170
|
+
seen.add(m.trim())
|
|
171
|
+
out.antigravity.models.push(m.trim())
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
if (typeof agCfg.model === 'string') {
|
|
175
|
+
out.antigravity.defaultModel = agCfg.model
|
|
176
|
+
pushAg(agCfg.model)
|
|
177
|
+
}
|
|
178
|
+
const custom = agCfg.customModelsConfig?.customModels
|
|
179
|
+
if (custom && typeof custom === 'object') {
|
|
180
|
+
for (const [key, value] of Object.entries(custom)) {
|
|
181
|
+
pushAg(value?.modelId || value?.modelName || key)
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
return out
|
|
187
|
+
}
|
|
@@ -0,0 +1,294 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Local CLI process invocation: argv construction, bounded spawning, and parsing
|
|
3
|
+
* of the backend-specific output into a normalized result.
|
|
4
|
+
* @module dsh-agent-router/lib/cli/invoke
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
import { spawn } from 'node:child_process'
|
|
8
|
+
import { randomUUID } from 'node:crypto'
|
|
9
|
+
import { existsSync, readFileSync, rmSync } from 'node:fs'
|
|
10
|
+
import { tmpdir } from 'node:os'
|
|
11
|
+
import { join } from 'node:path'
|
|
12
|
+
|
|
13
|
+
import { discoverCliModels, cliBinaryName } from './discover.js'
|
|
14
|
+
import {
|
|
15
|
+
extractProgressLine,
|
|
16
|
+
mapClaudePermission,
|
|
17
|
+
mapCodexSandbox,
|
|
18
|
+
mapGeminiApproval,
|
|
19
|
+
parseAntigravityOutput,
|
|
20
|
+
parseClaudeOutput,
|
|
21
|
+
parseCodexOutput,
|
|
22
|
+
parseGeminiOutput,
|
|
23
|
+
parseOpencodeOutput,
|
|
24
|
+
} from './parsers.js'
|
|
25
|
+
import { findOnPath, resolveWindowsCmdShim } from './shared.js'
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* Spawn one CLI subprocess cleanly with bounded output, optional stdin prompt, progress callback, and timeout abort.
|
|
29
|
+
*/
|
|
30
|
+
function runSpawned({ command, args, cwd, env, stdinText, timeoutMs, signal, backend, onProgress }) {
|
|
31
|
+
return new Promise((resolvePromise) => {
|
|
32
|
+
let settled = false
|
|
33
|
+
let timedOut = false
|
|
34
|
+
const startedAt = Date.now()
|
|
35
|
+
const stdoutChunks = []
|
|
36
|
+
const stderrChunks = []
|
|
37
|
+
let stdoutBytes = 0
|
|
38
|
+
let stderrBytes = 0
|
|
39
|
+
const MAX_BYTES = 8 * 1024 * 1024
|
|
40
|
+
|
|
41
|
+
const child = spawn(command, args, {
|
|
42
|
+
cwd,
|
|
43
|
+
env,
|
|
44
|
+
windowsHide: true,
|
|
45
|
+
stdio: [stdinText !== undefined ? 'pipe' : 'ignore', 'pipe', 'pipe'],
|
|
46
|
+
})
|
|
47
|
+
|
|
48
|
+
const finish = (outcome) => {
|
|
49
|
+
if (settled) return
|
|
50
|
+
settled = true
|
|
51
|
+
clearTimeout(timer)
|
|
52
|
+
signal?.removeEventListener?.('abort', onAbort)
|
|
53
|
+
resolvePromise({
|
|
54
|
+
...outcome,
|
|
55
|
+
stdout: Buffer.concat(stdoutChunks).toString('utf8'),
|
|
56
|
+
stderr: Buffer.concat(stderrChunks).toString('utf8'),
|
|
57
|
+
timedOut,
|
|
58
|
+
})
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
const terminate = () => {
|
|
62
|
+
try {
|
|
63
|
+
if (process.platform === 'win32' && child.pid) {
|
|
64
|
+
spawn('taskkill', ['/pid', String(child.pid), '/T', '/F'], {
|
|
65
|
+
windowsHide: true,
|
|
66
|
+
stdio: 'ignore',
|
|
67
|
+
}).unref?.()
|
|
68
|
+
}
|
|
69
|
+
child.kill('SIGTERM')
|
|
70
|
+
setTimeout(() => {
|
|
71
|
+
try { child.kill('SIGKILL') } catch {}
|
|
72
|
+
}, 2500).unref?.()
|
|
73
|
+
} catch {}
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
const onAbort = () => terminate()
|
|
77
|
+
if (signal?.aborted) {
|
|
78
|
+
terminate()
|
|
79
|
+
finish({ exitCode: null, signal: 'ABORTED', error: 'aborted by caller' })
|
|
80
|
+
return
|
|
81
|
+
}
|
|
82
|
+
signal?.addEventListener?.('abort', onAbort, { once: true })
|
|
83
|
+
|
|
84
|
+
const timer = setTimeout(() => {
|
|
85
|
+
timedOut = true
|
|
86
|
+
terminate()
|
|
87
|
+
}, Math.max(5000, timeoutMs || 300_000))
|
|
88
|
+
timer.unref?.()
|
|
89
|
+
|
|
90
|
+
child.stdout?.on('data', (chunk) => {
|
|
91
|
+
if (stdoutBytes < MAX_BYTES) {
|
|
92
|
+
stdoutChunks.push(chunk)
|
|
93
|
+
stdoutBytes += chunk.length
|
|
94
|
+
}
|
|
95
|
+
if (typeof onProgress === 'function') {
|
|
96
|
+
const line = extractProgressLine(backend || 'cli', chunk.toString('utf8'))
|
|
97
|
+
if (line) onProgress({ text: line, elapsedMs: Date.now() - startedAt })
|
|
98
|
+
}
|
|
99
|
+
})
|
|
100
|
+
child.stderr?.on('data', (chunk) => {
|
|
101
|
+
if (stderrBytes < MAX_BYTES) {
|
|
102
|
+
stderrChunks.push(chunk)
|
|
103
|
+
stderrBytes += chunk.length
|
|
104
|
+
}
|
|
105
|
+
})
|
|
106
|
+
child.on('error', (err) => {
|
|
107
|
+
finish({ exitCode: null, signal: null, error: err.message })
|
|
108
|
+
})
|
|
109
|
+
child.on('close', (code, sig) => {
|
|
110
|
+
finish({ exitCode: code, signal: sig, error: null })
|
|
111
|
+
})
|
|
112
|
+
|
|
113
|
+
if (stdinText !== undefined && child.stdin) {
|
|
114
|
+
child.stdin.on('error', () => {})
|
|
115
|
+
child.stdin.end(stdinText, 'utf8')
|
|
116
|
+
}
|
|
117
|
+
})
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
/**
|
|
121
|
+
* Execute or resume a local CLI agent task.
|
|
122
|
+
* @param {{
|
|
123
|
+
* backend: 'claude'|'codex'|'gemini'|'opencode'|'antigravity',
|
|
124
|
+
* prompt: string,
|
|
125
|
+
* cwd: string,
|
|
126
|
+
* model?: string,
|
|
127
|
+
* effort?: string,
|
|
128
|
+
* permissionMode?: 'read-only'|'workspace-write'|'auto',
|
|
129
|
+
* resumeSessionId?: string,
|
|
130
|
+
* timeoutMs?: number,
|
|
131
|
+
* signal?: AbortSignal,
|
|
132
|
+
* }} opts
|
|
133
|
+
*/
|
|
134
|
+
export async function executeCliAgent(opts) {
|
|
135
|
+
const binPath = findOnPath(cliBinaryName(opts.backend))
|
|
136
|
+
if (!binPath) {
|
|
137
|
+
return {
|
|
138
|
+
ok: false,
|
|
139
|
+
backend: opts.backend,
|
|
140
|
+
error: `CLI "${opts.backend}" not found on PATH`,
|
|
141
|
+
text: '',
|
|
142
|
+
sessionId: null,
|
|
143
|
+
durationMs: 0,
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
const startedAt = Date.now()
|
|
148
|
+
const { rawArgs, env, stdinText, codexLastMsgFile } = buildCliInvocation(opts)
|
|
149
|
+
const knownCliModels = discoverCliModels()
|
|
150
|
+
const defaultModel = knownCliModels[opts.backend]?.defaultModel || null
|
|
151
|
+
|
|
152
|
+
const { command, args } = resolveWindowsCmdShim(binPath, rawArgs)
|
|
153
|
+
const proc = await runSpawned({
|
|
154
|
+
command,
|
|
155
|
+
args,
|
|
156
|
+
cwd: opts.cwd,
|
|
157
|
+
env,
|
|
158
|
+
stdinText,
|
|
159
|
+
timeoutMs: opts.timeoutMs,
|
|
160
|
+
signal: opts.signal,
|
|
161
|
+
backend: opts.backend,
|
|
162
|
+
onProgress: opts.onProgress,
|
|
163
|
+
})
|
|
164
|
+
const durationMs = Date.now() - startedAt
|
|
165
|
+
|
|
166
|
+
let codexLastMsg = null
|
|
167
|
+
if (codexLastMsgFile) {
|
|
168
|
+
try {
|
|
169
|
+
if (existsSync(codexLastMsgFile)) codexLastMsg = readFileSync(codexLastMsgFile, 'utf8')
|
|
170
|
+
} catch {}
|
|
171
|
+
try { rmSync(codexLastMsgFile, { force: true }) } catch {}
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
let parsed
|
|
175
|
+
if (opts.backend === 'claude') parsed = parseClaudeOutput(proc.stdout)
|
|
176
|
+
else if (opts.backend === 'codex') parsed = parseCodexOutput(proc.stdout, codexLastMsg)
|
|
177
|
+
else if (opts.backend === 'gemini') parsed = parseGeminiOutput(proc.stdout)
|
|
178
|
+
else if (opts.backend === 'antigravity') parsed = parseAntigravityOutput(proc.stdout)
|
|
179
|
+
else parsed = parseOpencodeOutput(proc.stdout)
|
|
180
|
+
|
|
181
|
+
if (proc.timedOut) {
|
|
182
|
+
return {
|
|
183
|
+
...parsed,
|
|
184
|
+
ok: false,
|
|
185
|
+
backend: opts.backend,
|
|
186
|
+
durationMs,
|
|
187
|
+
exitCode: proc.exitCode,
|
|
188
|
+
error: `CLI "${opts.backend}" timed out after ${opts.timeoutMs || 300_000}ms`,
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
if (proc.error) {
|
|
192
|
+
return {
|
|
193
|
+
...parsed,
|
|
194
|
+
ok: false,
|
|
195
|
+
backend: opts.backend,
|
|
196
|
+
durationMs,
|
|
197
|
+
exitCode: proc.exitCode,
|
|
198
|
+
error: proc.error,
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
if (proc.exitCode !== 0 && !parsed.ok) {
|
|
202
|
+
const stderrTail = proc.stderr.trim().split(/\r?\n/).slice(-8).join('\n')
|
|
203
|
+
return {
|
|
204
|
+
...parsed,
|
|
205
|
+
ok: false,
|
|
206
|
+
backend: opts.backend,
|
|
207
|
+
durationMs,
|
|
208
|
+
exitCode: proc.exitCode,
|
|
209
|
+
error: parsed.error || stderrTail || `exit code ${proc.exitCode}`,
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
return {
|
|
214
|
+
...parsed,
|
|
215
|
+
backend: opts.backend,
|
|
216
|
+
requestedModel: opts.model || null,
|
|
217
|
+
resolvedModel: parsed.resolvedModel || opts.model || defaultModel,
|
|
218
|
+
durationMs,
|
|
219
|
+
exitCode: proc.exitCode,
|
|
220
|
+
stderrTail: proc.stderr.trim().split(/\r?\n/).slice(-5).join('\n'),
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
/**
|
|
225
|
+
* Build CLI argv, environment overrides, and stdin payload for one invocation.
|
|
226
|
+
* Exported for deterministic unit verification.
|
|
227
|
+
*/
|
|
228
|
+
export function buildCliInvocation(opts) {
|
|
229
|
+
const mode = opts.permissionMode || 'workspace-write'
|
|
230
|
+
const env = { ...process.env }
|
|
231
|
+
let rawArgs = []
|
|
232
|
+
let stdinText = undefined
|
|
233
|
+
let codexLastMsgFile = null
|
|
234
|
+
|
|
235
|
+
if (opts.backend === 'claude') {
|
|
236
|
+
rawArgs = ['-p', '--output-format', 'json', '--permission-mode', mapClaudePermission(mode), '--permission-prompts', 'none']
|
|
237
|
+
if (opts.model) rawArgs.push('--model', opts.model)
|
|
238
|
+
if (opts.effort) rawArgs.push('--effort', opts.effort)
|
|
239
|
+
if (opts.resumeSessionId) rawArgs.push('--resume', opts.resumeSessionId)
|
|
240
|
+
if (opts.prompt.length > 4000 || opts.prompt.startsWith('-') || /[\r\n]/.test(opts.prompt)) {
|
|
241
|
+
stdinText = opts.prompt
|
|
242
|
+
} else {
|
|
243
|
+
rawArgs.push('--', opts.prompt)
|
|
244
|
+
}
|
|
245
|
+
} else if (opts.backend === 'codex') {
|
|
246
|
+
codexLastMsgFile = join(tmpdir(), `dsh-router-codex-${randomUUID()}.txt`)
|
|
247
|
+
let codexProvider = null
|
|
248
|
+
let codexModel = opts.model || null
|
|
249
|
+
if (codexModel && codexModel.includes('/')) {
|
|
250
|
+
const slash = codexModel.indexOf('/')
|
|
251
|
+
codexProvider = codexModel.slice(0, slash)
|
|
252
|
+
codexModel = codexModel.slice(slash + 1)
|
|
253
|
+
}
|
|
254
|
+
const commonFlags = []
|
|
255
|
+
if (codexProvider) commonFlags.push('-c', `model_provider=${JSON.stringify(codexProvider)}`)
|
|
256
|
+
if (opts.effort) commonFlags.push('-c', `model_reasoning_effort=${JSON.stringify(opts.effort)}`)
|
|
257
|
+
if (codexModel) commonFlags.push('-m', codexModel)
|
|
258
|
+
|
|
259
|
+
if (opts.resumeSessionId) {
|
|
260
|
+
rawArgs = ['exec', 'resume', '--json', '--skip-git-repo-check', '-o', codexLastMsgFile, ...commonFlags, opts.resumeSessionId, '-']
|
|
261
|
+
} else {
|
|
262
|
+
rawArgs = ['exec', '--json', '--skip-git-repo-check', '-C', opts.cwd, '-s', mapCodexSandbox(mode), '-o', codexLastMsgFile, ...commonFlags, '-']
|
|
263
|
+
}
|
|
264
|
+
stdinText = opts.prompt
|
|
265
|
+
} else if (opts.backend === 'gemini') {
|
|
266
|
+
env.GEMINI_CLI_NO_RELAUNCH = '1'
|
|
267
|
+
rawArgs = ['--output-format', 'json', '--skip-trust', '--approval-mode', mapGeminiApproval(mode)]
|
|
268
|
+
if (opts.model) rawArgs.push('-m', opts.model)
|
|
269
|
+
if (opts.resumeSessionId) rawArgs.push('-r', opts.resumeSessionId)
|
|
270
|
+
if (opts.prompt.length > 4000 || opts.prompt.startsWith('-') || /[\r\n]/.test(opts.prompt)) {
|
|
271
|
+
rawArgs.push('-p', '')
|
|
272
|
+
stdinText = opts.prompt
|
|
273
|
+
} else {
|
|
274
|
+
rawArgs.push('-p', opts.prompt)
|
|
275
|
+
}
|
|
276
|
+
} else if (opts.backend === 'antigravity') {
|
|
277
|
+
rawArgs = ['-p', opts.prompt, '--output-format', 'json']
|
|
278
|
+
if (mode === 'read-only') rawArgs.push('--mode', 'plan')
|
|
279
|
+
else if (mode === 'auto') rawArgs.push('--dangerously-skip-permissions')
|
|
280
|
+
if (opts.model) rawArgs.push('--model', opts.model)
|
|
281
|
+
if (opts.effort) rawArgs.push('--effort', opts.effort)
|
|
282
|
+
if (opts.resumeSessionId) rawArgs.push('--conversation', opts.resumeSessionId)
|
|
283
|
+
} else if (opts.backend === 'opencode') {
|
|
284
|
+
rawArgs = ['run', '--format', 'json', '--dir', opts.cwd]
|
|
285
|
+
if (mode === 'read-only') rawArgs.push('--agent', 'plan')
|
|
286
|
+
if (opts.model) rawArgs.push('-m', opts.model)
|
|
287
|
+
if (opts.effort) rawArgs.push('--variant', opts.effort)
|
|
288
|
+
if (mode === 'auto') rawArgs.push('--auto')
|
|
289
|
+
if (opts.resumeSessionId) rawArgs.push('-s', opts.resumeSessionId)
|
|
290
|
+
rawArgs.push('--', opts.prompt)
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
return { rawArgs, env, stdinText, codexLastMsgFile }
|
|
294
|
+
}
|