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.
Files changed (65) hide show
  1. package/LICENSE +21 -0
  2. package/README.en.md +304 -0
  3. package/README.md +304 -0
  4. package/client.js +3061 -0
  5. package/cordis.patch.yml +20 -0
  6. package/docs/ARCHITECTURE_DIAGNOSIS_AND_PLAN.md +414 -0
  7. package/docs/DETAIL.ja.md +1 -0
  8. package/docs/DETAIL.md +1 -0
  9. package/docs/DETAIL.zh.md +1 -0
  10. package/docs/IMPLEMENTATION_PLAN.md +99 -0
  11. package/docs/ITERATION_PLAN_2026-11.md +377 -0
  12. package/docs/RELEASE.md +133 -0
  13. package/docs/RELEASE_CHECKLIST.md +88 -0
  14. package/docs/preview.svg +69 -0
  15. package/docs/preview.zh.svg +63 -0
  16. package/icon.svg +16 -0
  17. package/index.js +24 -0
  18. package/lib/classifier.js +405 -0
  19. package/lib/cli/discover.js +187 -0
  20. package/lib/cli/invoke.js +294 -0
  21. package/lib/cli/parsers.js +234 -0
  22. package/lib/cli/shared.js +145 -0
  23. package/lib/cli-runners.js +39 -0
  24. package/lib/config-limits.js +67 -0
  25. package/lib/config-normalize.js +147 -0
  26. package/lib/config-presets.js +89 -0
  27. package/lib/config-schema.js +347 -0
  28. package/lib/defaults.js +117 -0
  29. package/lib/diagnose-fallback.js +96 -0
  30. package/lib/error-classify.js +160 -0
  31. package/lib/eval-routing.js +96 -0
  32. package/lib/guardrails.js +70 -0
  33. package/lib/integrations.js +173 -0
  34. package/lib/job-runner.js +287 -0
  35. package/lib/ledger.js +360 -0
  36. package/lib/legacy-config.js +34 -0
  37. package/lib/model-capabilities.js +135 -0
  38. package/lib/model-score.js +65 -0
  39. package/lib/plugin.js +184 -0
  40. package/lib/profile-mount.js +524 -0
  41. package/lib/route-edit.js +82 -0
  42. package/lib/router/candidates.js +194 -0
  43. package/lib/router/catalog.js +121 -0
  44. package/lib/router/cli-select.js +84 -0
  45. package/lib/router/config-manager.js +122 -0
  46. package/lib/router/doctor.js +159 -0
  47. package/lib/router/local-models.js +126 -0
  48. package/lib/router/policy.js +61 -0
  49. package/lib/router/rpc.js +263 -0
  50. package/lib/router/system-prompt.js +29 -0
  51. package/lib/router/tools.js +1028 -0
  52. package/lib/router/util.js +99 -0
  53. package/lib/rpc-contract.js +46 -0
  54. package/lib/sessions.js +59 -0
  55. package/lib/task-queue.js +201 -0
  56. package/lib/tier-presets.js +595 -0
  57. package/lib/typert.host.js +79 -0
  58. package/lib/update-check.js +205 -0
  59. package/lib/worktree-lock.js +86 -0
  60. package/lib/worktree.js +268 -0
  61. package/locale/en.json +7 -0
  62. package/locale/ja.json +7 -0
  63. package/locale/zh.json +7 -0
  64. package/package.json +136 -0
  65. package/scripts/profile-maintenance.mjs +287 -0
@@ -0,0 +1,205 @@
1
+ /**
2
+ * Read-only update checker for GitHub-hosted installs.
3
+ *
4
+ * The checker compares the installed package version with `package.json` on
5
+ * the configured GitHub branch. Network failures, timeouts, and malformed
6
+ * responses are reported as data instead of thrown errors so that routing and
7
+ * the rest of the plugin keep working while offline.
8
+ *
9
+ * @module dsh-agent-router/lib/update-check
10
+ */
11
+
12
+ import { readFileSync } from 'node:fs'
13
+
14
+ const PACKAGE = 'dsh-agent-router'
15
+ const PACKAGE_JSON = new URL('../package.json', import.meta.url)
16
+ const SUCCESS_TTL_MS = 6 * 60 * 60 * 1000
17
+ const FAILURE_TTL_MS = 5 * 60 * 1000
18
+ const FETCH_TIMEOUT_MS = 8_000
19
+
20
+ const DEFAULT_SOURCE = Object.freeze({
21
+ owner: 'qingxuan233',
22
+ repo: 'dsh-agent-router',
23
+ branch: 'main',
24
+ })
25
+
26
+ let installedPackage = null
27
+ let cache = null
28
+
29
+ /**
30
+ * Clear the in-memory result cache. Intended for tests and manual refreshes.
31
+ */
32
+ export function resetUpdateCache() {
33
+ cache = null
34
+ }
35
+
36
+ /**
37
+ * Parse a semver string (with optional prerelease/build metadata).
38
+ * @param {unknown} value
39
+ * @returns {{ major: number, minor: number, patch: number, prerelease: string[] } | null}
40
+ */
41
+ export function parseVersion(value) {
42
+ const match = /^v?(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/.exec(String(value ?? '').trim())
43
+ if (!match) return null
44
+ return {
45
+ major: Number(match[1]),
46
+ minor: Number(match[2]),
47
+ patch: Number(match[3]),
48
+ prerelease: match[4] ? match[4].split('.') : [],
49
+ }
50
+ }
51
+
52
+ function compareIdentifiers(a, b) {
53
+ const aNumeric = /^\d+$/.test(a)
54
+ const bNumeric = /^\d+$/.test(b)
55
+ if (aNumeric && bNumeric) return Math.sign(Number(a) - Number(b))
56
+ if (aNumeric) return -1
57
+ if (bNumeric) return 1
58
+ if (a === b) return 0
59
+ return a < b ? -1 : 1
60
+ }
61
+
62
+ /**
63
+ * Compare two semver strings.
64
+ * @param {unknown} left
65
+ * @param {unknown} right
66
+ * @returns {-1 | 0 | 1} `0` when either value is not a valid version.
67
+ */
68
+ export function compareVersions(left, right) {
69
+ const a = parseVersion(left)
70
+ const b = parseVersion(right)
71
+ if (!a || !b) return 0
72
+ for (const key of ['major', 'minor', 'patch']) {
73
+ if (a[key] !== b[key]) return Math.sign(a[key] - b[key])
74
+ }
75
+ if (a.prerelease.length === 0 && b.prerelease.length === 0) return 0
76
+ if (a.prerelease.length === 0) return 1
77
+ if (b.prerelease.length === 0) return -1
78
+ const length = Math.max(a.prerelease.length, b.prerelease.length)
79
+ for (let index = 0; index < length; index += 1) {
80
+ const leftPart = a.prerelease[index]
81
+ const rightPart = b.prerelease[index]
82
+ if (leftPart === undefined) return -1
83
+ if (rightPart === undefined) return 1
84
+ const compared = compareIdentifiers(leftPart, rightPart)
85
+ if (compared !== 0) return compared
86
+ }
87
+ return 0
88
+ }
89
+
90
+ /**
91
+ * Resolve GitHub owner/repo from the package repository field.
92
+ * @param {any} [pkg]
93
+ * @returns {{ owner: string, repo: string, branch: string }}
94
+ */
95
+ export function resolveGitHubSource(pkg = readInstalledPackage()) {
96
+ const repository = typeof pkg?.repository === 'string' ? pkg.repository : pkg?.repository?.url
97
+ const match = /github\.com[/:]([^/]+)\/([^/#]+)/.exec(String(repository || ''))
98
+ return {
99
+ owner: match?.[1] || DEFAULT_SOURCE.owner,
100
+ repo: (match?.[2] || DEFAULT_SOURCE.repo).replace(/\.git$/, ''),
101
+ branch: DEFAULT_SOURCE.branch,
102
+ }
103
+ }
104
+
105
+ function readInstalledPackage() {
106
+ if (installedPackage) return installedPackage
107
+ try {
108
+ installedPackage = JSON.parse(readFileSync(PACKAGE_JSON, 'utf8'))
109
+ } catch {
110
+ installedPackage = { name: PACKAGE, version: '0.0.0', repository: {} }
111
+ }
112
+ return installedPackage
113
+ }
114
+
115
+ async function fetchLatestVersion(source, options) {
116
+ const fetchImpl = options.fetchImpl || globalThis.fetch
117
+ if (typeof fetchImpl !== 'function') throw new Error('fetch is unavailable')
118
+ // Use the GitHub contents API instead of raw.githubusercontent.com: the raw
119
+ // host is blocked or reset on some networks while api.github.com stays reachable.
120
+ const url = 'https://api.github.com/repos/'
121
+ + encodeURIComponent(source.owner) + '/'
122
+ + encodeURIComponent(source.repo) + '/contents/package.json?ref='
123
+ + encodeURIComponent(source.branch) + '&ts=' + Date.now()
124
+ const response = await fetchImpl(url, {
125
+ headers: {
126
+ accept: 'application/vnd.github+json',
127
+ 'user-agent': 'dsh-agent-router-update-check',
128
+ 'x-github-api-version': '2022-11-28',
129
+ 'cache-control': 'no-cache',
130
+ },
131
+ signal: AbortSignal.timeout(options.timeoutMs || FETCH_TIMEOUT_MS),
132
+ })
133
+ if (!response || !response.ok) throw new Error('HTTP ' + (response?.status ?? 'error'))
134
+ const payload = await response.json()
135
+ if (!payload || typeof payload.content !== 'string') {
136
+ throw new Error('GitHub API response has no package.json content')
137
+ }
138
+ const text = payload.encoding === 'base64'
139
+ ? Buffer.from(payload.content, 'base64').toString('utf8')
140
+ : payload.content
141
+ let data
142
+ try {
143
+ data = JSON.parse(text)
144
+ } catch {
145
+ throw new Error('remote package.json is not valid JSON')
146
+ }
147
+ if (!data || typeof data.version !== 'string') throw new Error('remote package.json has no version')
148
+ return data
149
+ }
150
+
151
+ /**
152
+ * Check whether a newer version exists on the GitHub branch.
153
+ *
154
+ * @param {{
155
+ * force?: boolean,
156
+ * now?: () => number,
157
+ * fetchImpl?: typeof fetch,
158
+ * timeoutMs?: number,
159
+ * installed?: any,
160
+ * source?: { owner: string, repo: string, branch: string },
161
+ * }} [options]
162
+ * @returns {Promise<Record<string, any>>} Always resolves; failures carry `ok: false`.
163
+ */
164
+ export async function checkForUpdate(options = {}) {
165
+ const now = typeof options.now === 'function' ? options.now() : Date.now()
166
+ if (!options.force && cache && now - cache.checkedAt < cache.ttlMs) return cache.result
167
+
168
+ const installed = options.installed || readInstalledPackage()
169
+ const source = options.source || resolveGitHubSource(installed)
170
+ const currentVersion = String(installed.version || '0.0.0')
171
+ const checkedAt = new Date(now).toISOString()
172
+ const repository = 'https://github.com/' + source.owner + '/' + source.repo
173
+ const base = {
174
+ currentVersion,
175
+ checkedAt,
176
+ source: { owner: source.owner, repo: source.repo, branch: source.branch },
177
+ repository,
178
+ releasesUrl: repository + '/commits/' + source.branch,
179
+ }
180
+
181
+ try {
182
+ const latest = await fetchLatestVersion(source, options)
183
+ if (!parseVersion(latest.version)) throw new Error('invalid remote version: ' + latest.version)
184
+ const comparison = compareVersions(latest.version, currentVersion)
185
+ const result = {
186
+ ok: true,
187
+ ...base,
188
+ latestVersion: latest.version,
189
+ hasUpdate: comparison > 0,
190
+ ahead: comparison < 0,
191
+ updateCommand: 'pnpm add "dsh-agent-router@github:' + source.owner + '/' + source.repo + '#' + source.branch + '"',
192
+ npmCommand: 'pnpm add dsh-agent-router@latest',
193
+ }
194
+ cache = { checkedAt: now, ttlMs: SUCCESS_TTL_MS, result }
195
+ return result
196
+ } catch (error) {
197
+ const result = {
198
+ ok: false,
199
+ ...base,
200
+ error: error instanceof Error ? error.message : String(error),
201
+ }
202
+ cache = { checkedAt: now, ttlMs: FAILURE_TTL_MS, result }
203
+ return result
204
+ }
205
+ }
@@ -0,0 +1,86 @@
1
+ /**
2
+ * Cross-process lock for destructive worktree operations on one repository.
3
+ *
4
+ * Two DSH windows can point at the same repo; without a lock they may merge two
5
+ * agent branches concurrently. The lock is a file under `.git/` and is treated
6
+ * as stale when its owner pid is gone or its timestamp is too old.
7
+ *
8
+ * @module dsh-agent-router/lib/worktree-lock
9
+ */
10
+
11
+ import { mkdirSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs'
12
+ import { join } from 'node:path'
13
+
14
+ const DEFAULT_TTL_MS = 5 * 60_000
15
+
16
+ export function worktreeLockPath(repoRoot) {
17
+ return join(repoRoot, '.git', 'dsh-agent-router.worktree.lock')
18
+ }
19
+
20
+ function isPidAlive(pid) {
21
+ if (!Number.isInteger(pid) || pid <= 0) return false
22
+ try {
23
+ process.kill(pid, 0)
24
+ return true
25
+ } catch (error) {
26
+ return error?.code === 'EPERM'
27
+ }
28
+ }
29
+
30
+ export function isStaleLock(lockPath, { ttlMs = DEFAULT_TTL_MS, now = Date.now() } = {}) {
31
+ try {
32
+ const info = JSON.parse(readFileSync(lockPath, 'utf8'))
33
+ if (Number.isFinite(Number(info?.at)) && now - Number(info.at) > ttlMs) return true
34
+ if (info?.pid && !isPidAlive(Number(info.pid))) return true
35
+ } catch {
36
+ // Unreadable payload: fall through to mtime-based staleness.
37
+ }
38
+ try {
39
+ return now - statSync(lockPath).mtimeMs > ttlMs
40
+ } catch {
41
+ return false
42
+ }
43
+ }
44
+
45
+ /**
46
+ * @param {string} repoRoot
47
+ * @param {{ ttlMs?: number, now?: number }} [opts]
48
+ * @returns {{ acquired: boolean, lockPath: string, reason?: string, release: () => void }}
49
+ */
50
+ export function acquireWorktreeLock(repoRoot, { ttlMs = DEFAULT_TTL_MS, now = Date.now() } = {}) {
51
+ const lockPath = worktreeLockPath(repoRoot)
52
+ const release = () => releaseWorktreeLock(repoRoot)
53
+ try {
54
+ mkdirSync(join(repoRoot, '.git'), { recursive: true })
55
+ } catch {
56
+ return { acquired: false, lockPath, reason: 'unwritable', release: () => {} }
57
+ }
58
+
59
+ for (let attempt = 0; attempt < 2; attempt += 1) {
60
+ try {
61
+ writeFileSync(lockPath, JSON.stringify({ pid: process.pid, at: now }), { flag: 'wx' })
62
+ return { acquired: true, lockPath, release }
63
+ } catch (error) {
64
+ if (error?.code !== 'EEXIST') {
65
+ return { acquired: false, lockPath, reason: 'unwritable', release: () => {} }
66
+ }
67
+ if (!isStaleLock(lockPath, { ttlMs, now })) {
68
+ return { acquired: false, lockPath, reason: 'held', release: () => {} }
69
+ }
70
+ try {
71
+ rmSync(lockPath, { force: true })
72
+ } catch {
73
+ // A concurrent process may have released it already.
74
+ }
75
+ }
76
+ }
77
+ return { acquired: false, lockPath, reason: 'contended', release: () => {} }
78
+ }
79
+
80
+ export function releaseWorktreeLock(repoRoot) {
81
+ try {
82
+ rmSync(worktreeLockPath(repoRoot), { force: true })
83
+ } catch {
84
+ // Releasing a missing lock is harmless.
85
+ }
86
+ }
@@ -0,0 +1,268 @@
1
+ /**
2
+ * Optional Git worktree isolation for parallel multi-agent edits.
3
+ * Worktrees live under OS temp dir to avoid polluting the repository tree.
4
+ * @module dsh-agent-router/lib/worktree
5
+ */
6
+
7
+ import { execFile } from 'node:child_process'
8
+ import { createHash } from 'node:crypto'
9
+ import { existsSync, mkdirSync, rmSync } from 'node:fs'
10
+ import { tmpdir } from 'node:os'
11
+ import { join, relative, resolve } from 'node:path'
12
+ import { promisify } from 'node:util'
13
+
14
+ const execFileAsync = promisify(execFile)
15
+
16
+ async function git(args, cwd) {
17
+ const { stdout, stderr } = await execFileAsync('git', args, {
18
+ cwd,
19
+ windowsHide: true,
20
+ timeout: 20_000,
21
+ maxBuffer: 1024 * 1024,
22
+ })
23
+ return { stdout: stdout.trim(), stderr: stderr.trim() }
24
+ }
25
+
26
+ /**
27
+ * Resolve the Git repository root for `cwd`, or null if not a Git repo.
28
+ * @param {string} cwd
29
+ */
30
+ export async function getRepoRoot(cwd) {
31
+ try {
32
+ const { stdout } = await git(['rev-parse', '--show-toplevel'], cwd)
33
+ return stdout || null
34
+ } catch {
35
+ return null
36
+ }
37
+ }
38
+
39
+ /**
40
+ * Create an isolated Git worktree and branch for a dispatched agent run.
41
+ * @param {{ cwd: string, runId: string }} opts
42
+ */
43
+ export async function createIsolatedWorktree({ cwd, runId }) {
44
+ const repoRoot = await getRepoRoot(cwd)
45
+ if (!repoRoot) {
46
+ throw new Error(`use_worktree requires a Git repository, but "${cwd}" is not inside one`)
47
+ }
48
+ const { stdout: baseCommit } = await git(['rev-parse', 'HEAD'], repoRoot)
49
+ const repoHash = createHash('sha1').update(repoRoot).digest('hex').slice(0, 10)
50
+ const baseDir = join(tmpdir(), 'dsh-router-worktrees', repoHash)
51
+ mkdirSync(baseDir, { recursive: true })
52
+ const safeId = String(runId).replace(/[^a-zA-Z0-9_-]/g, '-')
53
+ const worktreePath = join(baseDir, safeId)
54
+ const branch = `dsh-router/${safeId}`
55
+ await git(['worktree', 'add', '-b', branch, worktreePath], repoRoot)
56
+ const relSubdir = relative(resolve(repoRoot), resolve(cwd))
57
+ const effectiveCwd = relSubdir && !relSubdir.startsWith('..') && existsSync(join(worktreePath, relSubdir))
58
+ ? join(worktreePath, relSubdir)
59
+ : worktreePath
60
+ return { repoRoot, worktreePath, effectiveCwd, branch, baseCommit }
61
+ }
62
+
63
+ /**
64
+ * Collect git status and diff stat inside an isolated worktree after an agent run.
65
+ * @param {{ repoRoot: string, worktreePath: string, branch: string, baseCommit?: string }} wt
66
+ */
67
+ export async function inspectWorktreeDiff(wt) {
68
+ try {
69
+ const baseRef = wt.baseCommit || 'HEAD'
70
+ const [status, diffStat, ahead] = await Promise.all([
71
+ git(['status', '--short'], wt.worktreePath),
72
+ git(['diff', '--stat', baseRef], wt.worktreePath),
73
+ git(['rev-list', '--count', `${baseRef}..HEAD`], wt.worktreePath).catch(() => ({ stdout: '0' })),
74
+ ])
75
+ return {
76
+ worktreePath: wt.worktreePath,
77
+ branch: wt.branch,
78
+ ...(wt.baseCommit ? { baseCommit: wt.baseCommit } : {}),
79
+ dirty: status.stdout.length > 0,
80
+ statusShort: status.stdout,
81
+ diffStat: diffStat.stdout,
82
+ aheadCount: Number(ahead.stdout || 0),
83
+ }
84
+ } catch (error) {
85
+ return {
86
+ worktreePath: wt.worktreePath,
87
+ branch: wt.branch,
88
+ error: error instanceof Error ? error.message : String(error),
89
+ }
90
+ }
91
+ }
92
+
93
+ /**
94
+ * Remove a created worktree (and optionally its branch).
95
+ * @param {{ repoRoot: string, worktreePath: string, branch?: string, deleteBranch?: boolean }} wt
96
+ */
97
+ export async function cleanupIsolatedWorktree(wt) {
98
+ await git(['worktree', 'remove', '--force', wt.worktreePath], wt.repoRoot).catch(() => {})
99
+ rmSync(wt.worktreePath, { recursive: true, force: true })
100
+ if (wt.deleteBranch && wt.branch) {
101
+ await git(['branch', '-D', wt.branch], wt.repoRoot).catch(() => {})
102
+ }
103
+ }
104
+
105
+ function parseStatusFiles(statusOutput) {
106
+ if (!statusOutput) return []
107
+ return statusOutput
108
+ .split(/\r?\n/)
109
+ .filter(Boolean)
110
+ .map(line => line.slice(3).trim().replace(/^"|"$/g, ''))
111
+ .filter(Boolean)
112
+ }
113
+
114
+ async function previewMergeConflicts(repoRoot, branch) {
115
+ try {
116
+ const { stdout } = await git(['merge-tree', '--write-tree', 'HEAD', branch], repoRoot)
117
+ return { canMergeCleanly: true, conflictFiles: [], tree: stdout.split(/\r?\n/)[0] || null }
118
+ } catch (err) {
119
+ const msg = `${err?.stdout || ''}\n${err?.stderr || ''}\n${err?.message || ''}`
120
+ if (/unknown option|not a git command/i.test(msg)) {
121
+ return { canMergeCleanly: null, conflictFiles: [], note: 'git merge-tree --write-tree unsupported by installed Git version' }
122
+ }
123
+ const conflicts = []
124
+ for (const line of msg.split(/\r?\n/)) {
125
+ const m = line.match(/CONFLICT\s*\([^)]+\):\s*Merge conflict in\s+(.+)$/i)
126
+ if (m && !conflicts.includes(m[1].trim())) conflicts.push(m[1].trim())
127
+ }
128
+ return {
129
+ canMergeCleanly: false,
130
+ conflictFiles: conflicts,
131
+ error: msg.trim().split(/\r?\n/).slice(-5).join('\n'),
132
+ }
133
+ }
134
+ }
135
+
136
+ /**
137
+ * Inspect full patch diff, changed files, and merge-conflict preview for an isolated worktree.
138
+ * @param {{ repoRoot: string, worktreePath: string, branch: string, baseCommit?: string }} wt
139
+ * @param {{ maxBytes?: number }} [opts]
140
+ */
141
+ export async function readWorktreePatch(wt, opts = {}) {
142
+ const maxBytes = Math.max(1024, Math.min(512 * 1024, Number(opts.maxBytes ?? 32768)))
143
+ const baseRef = wt.baseCommit || 'HEAD'
144
+ const [status, diffStat, diffPatchRaw, ahead, changedNamesRaw, mergePreview] = await Promise.all([
145
+ git(['status', '--short'], wt.worktreePath),
146
+ git(['diff', '--stat', baseRef], wt.worktreePath),
147
+ execFileAsync('git', ['diff', '--no-color', baseRef], {
148
+ cwd: wt.worktreePath,
149
+ windowsHide: true,
150
+ timeout: 20_000,
151
+ maxBuffer: 4 * 1024 * 1024,
152
+ }).then(r => r.stdout, () => ''),
153
+ git(['rev-list', '--count', `${baseRef}..HEAD`], wt.worktreePath).catch(() => ({ stdout: '0' })),
154
+ git(['diff', '--name-only', baseRef], wt.worktreePath).catch(() => ({ stdout: '' })),
155
+ previewMergeConflicts(wt.repoRoot, wt.branch),
156
+ ])
157
+
158
+ const untrackedFiles = parseStatusFiles(status.stdout).filter(f => !changedNamesRaw.stdout.split(/\r?\n/).includes(f))
159
+ const trackedFiles = changedNamesRaw.stdout ? changedNamesRaw.stdout.split(/\r?\n/).filter(Boolean) : []
160
+ const files = [...new Set([...trackedFiles, ...untrackedFiles])]
161
+
162
+ let patch = diffPatchRaw || ''
163
+ let truncated = false
164
+ if (Buffer.byteLength(patch, 'utf8') > maxBytes) {
165
+ const buf = Buffer.from(patch, 'utf8')
166
+ patch = buf.subarray(0, maxBytes).toString('utf8') + '\n... [truncated]'
167
+ truncated = true
168
+ }
169
+
170
+ return {
171
+ worktreePath: wt.worktreePath,
172
+ branch: wt.branch,
173
+ ...(wt.baseCommit ? { baseCommit: wt.baseCommit } : {}),
174
+ dirty: status.stdout.length > 0,
175
+ aheadCount: Number(ahead.stdout || 0),
176
+ files,
177
+ statusShort: status.stdout,
178
+ diffStat: diffStat.stdout,
179
+ patch,
180
+ truncated,
181
+ mergePreview,
182
+ }
183
+ }
184
+
185
+ /**
186
+ * Safely merge an isolated worktree branch back into the main repository's current HEAD
187
+ * and optionally remove the temporary worktree & branch.
188
+ *
189
+ * @param {{ repoRoot: string, worktreePath: string, branch: string, baseCommit?: string }} wt
190
+ * @param {{ strategy?: 'squash'|'ff-only'|'merge', commitMessage?: string, autoCommit?: boolean, cleanup?: boolean }} [opts]
191
+ */
192
+ export async function mergeIsolatedWorktree(wt, opts = {}) {
193
+ const strategy = ['squash', 'ff-only', 'merge'].includes(opts.strategy) ? opts.strategy : 'squash'
194
+ const autoCommit = opts.autoCommit !== false
195
+ const cleanup = opts.cleanup !== false
196
+
197
+ const baseRef = wt.baseCommit || 'HEAD'
198
+ const wtStatus = await git(['status', '--short'], wt.worktreePath)
199
+ if (wtStatus.stdout.length > 0) {
200
+ if (!autoCommit) {
201
+ throw new Error(`Worktree ${wt.branch} has uncommitted changes; commit them or pass autoCommit=true`)
202
+ }
203
+ await git(['add', '-A'], wt.worktreePath)
204
+ const msg = opts.commitMessage || `dsh-agent-router: commit changes on ${wt.branch}`
205
+ await git(['commit', '-m', msg], wt.worktreePath)
206
+ }
207
+
208
+ const aheadRes = await git(['rev-list', '--count', `${baseRef}..HEAD`], wt.worktreePath).catch(() => ({ stdout: '0' }))
209
+ const aheadCount = Number(aheadRes.stdout || 0)
210
+ const filesRes = await git(['diff', '--name-only', `${baseRef}..HEAD`], wt.worktreePath).catch(() => ({ stdout: '' }))
211
+ const changedFiles = filesRes.stdout ? filesRes.stdout.split(/\r?\n/).filter(Boolean) : []
212
+
213
+ if (aheadCount === 0 && changedFiles.length === 0) {
214
+ if (cleanup) {
215
+ await cleanupIsolatedWorktree({ ...wt, deleteBranch: true })
216
+ }
217
+ return {
218
+ merged: false,
219
+ reason: 'no-changes',
220
+ strategy,
221
+ branch: wt.branch,
222
+ files: [],
223
+ cleaned: cleanup,
224
+ }
225
+ }
226
+
227
+ // Ensure main checkout has no overlapping uncommitted modifications
228
+ const mainStatus = await git(['status', '--short'], wt.repoRoot)
229
+ if (mainStatus.stdout.length > 0) {
230
+ const mainDirtyFiles = parseStatusFiles(mainStatus.stdout)
231
+ const overlap = mainDirtyFiles.filter(f => changedFiles.includes(f))
232
+ if (overlap.length > 0 || strategy !== 'ff-only') {
233
+ throw new Error(
234
+ `Main repository "${wt.repoRoot}" has uncommitted changes (${(overlap.length > 0 ? overlap : mainDirtyFiles).slice(0, 5).join(', ')}); commit or stash before merging ${wt.branch}`,
235
+ )
236
+ }
237
+ }
238
+
239
+ const mergeMsg = opts.commitMessage || `Merge ${wt.branch} via dsh-agent-router`
240
+ try {
241
+ if (strategy === 'ff-only') {
242
+ await git(['merge', '--ff-only', wt.branch], wt.repoRoot)
243
+ } else if (strategy === 'squash') {
244
+ await git(['merge', '--squash', wt.branch], wt.repoRoot)
245
+ await git(['commit', '-m', mergeMsg], wt.repoRoot)
246
+ } else {
247
+ await git(['merge', '--no-ff', '-m', mergeMsg, wt.branch], wt.repoRoot)
248
+ }
249
+ } catch (err) {
250
+ await git(['merge', '--abort'], wt.repoRoot).catch(() => {})
251
+ await git(['reset', '--merge'], wt.repoRoot).catch(() => {})
252
+ throw new Error(`Failed to merge ${wt.branch} (${strategy}): ${err instanceof Error ? err.message : String(err)}`)
253
+ }
254
+
255
+ const { stdout: mergeCommit } = await git(['rev-parse', '--short', 'HEAD'], wt.repoRoot).catch(() => ({ stdout: '' }))
256
+ if (cleanup) {
257
+ await cleanupIsolatedWorktree({ ...wt, deleteBranch: true })
258
+ }
259
+
260
+ return {
261
+ merged: true,
262
+ strategy,
263
+ branch: wt.branch,
264
+ mergeCommit: mergeCommit || null,
265
+ files: changedFiles,
266
+ cleaned: cleanup,
267
+ }
268
+ }
package/locale/en.json ADDED
@@ -0,0 +1,7 @@
1
+ {
2
+ "meta": {
3
+ "title": "Multi-agent difficulty router",
4
+ "description": "Routes tasks by difficulty (T1–T4) across native DSH subagents and local agent CLIs (Claude Code, Codex, Gemini, OpenCode) with an in-app routing editor, profile-synced config, adaptive CLI selection, optional local/self-hosted models, async background queue, EWMA ranking, dry-run route preview, session resume, and Git worktree diff/merge isolation.",
5
+ "detail": "docs/DETAIL.md"
6
+ }
7
+ }
package/locale/ja.json ADDED
@@ -0,0 +1,7 @@
1
+ {
2
+ "meta": {
3
+ "title": "マルチエージェント難易度ルーター",
4
+ "description": "タスク難易度(T1–T4)に応じて DSH ネイティブサブエージェントとローカル CLI(Claude Code、Codex、Gemini、OpenCode、Antigravity)へルーティングします。能力フィルタリング、適応型 CLI 選択、ローカルモデル、サーキットブレーカー、失敗分類、実行中ステータス、フィードバック/評価、セッション管理、Worktree 分離を備えます。",
5
+ "detail": "docs/DETAIL.ja.md"
6
+ }
7
+ }
package/locale/zh.json ADDED
@@ -0,0 +1,7 @@
1
+ {
2
+ "meta": {
3
+ "title": "多智能体难度路由器",
4
+ "description": "按任务难度(T1–T4)将工作路由到 DSH 原生子智能体或本机 CLI(Claude Code、Codex、Gemini、OpenCode),支持 Profile 原生配置同步、插件详情页可视化配表、CLI 自适应选择、可选本地/自托管模型、异步后台队列、EWMA 排序、熔断降级、失败升阶、会话续接与 Worktree Diff/合入闭环。",
5
+ "detail": "docs/DETAIL.zh.md"
6
+ }
7
+ }