dsh-chief 1.6.0 → 1.7.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/CHANGELOG.md +31 -0
- package/README.en.md +277 -123
- package/README.md +283 -129
- package/api-routes.js +193 -2
- package/board-actions.js +1452 -2060
- package/board-handoff.js +709 -0
- package/board-schema.js +35 -2
- package/chief-approvals.js +6 -2
- package/chief-commands.js +1884 -3486
- package/chief-executor.js +6 -1
- package/chief-network.js +1098 -869
- package/chief-review.js +193 -3
- package/chief-state.js +1996 -3078
- package/chief-view.js +7 -4
- package/client.js +12237 -8021
- package/command-helpers.js +568 -0
- package/command-ops.js +1226 -0
- package/digest.js +25 -3
- package/index.js +6 -0
- package/locale/en.json +4 -4
- package/locale/zh.json +4 -4
- package/model-tools.js +40 -2
- package/network-harness.js +1047 -0
- package/package.json +8 -2
- package/runtime-hooks.js +69 -2
- package/safety/guard-walls.js +5 -0
- package/safety/invariant-guards.js +125 -6
- package/safety/tool-gate.js +2 -0
- package/state-media.js +173 -0
- package/state-schema.js +1505 -0
- package/subagent-runtime.js +57 -3
|
@@ -0,0 +1,1047 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* network-harness.js — 本机外部 Harness (Claude/Codex 等) CLI 探测、协同水泡状态与物理隔离派发
|
|
3
|
+
*
|
|
4
|
+
* 【核心职责】
|
|
5
|
+
* 1. 跨平台本机 CLI/配置自动探测(`detectLocalHarnessBinaries`、`discoverHarnessProviders`)
|
|
6
|
+
* 及 `refreshBubbleDiscovery` 一键强制清缓存重扫。
|
|
7
|
+
* 2. 协同水泡状态组装(`computeBubbleState`)与目标解析(`resolveExternalHarnessTarget`)。
|
|
8
|
+
* 3. 外部进程物理隔离派发与红线防穿透(`dispatchBubbleHarness`)。
|
|
9
|
+
*
|
|
10
|
+
* 【边界与无环约定】
|
|
11
|
+
* - 作为 `chief-network.js` 的下层专属模块,不反向 `import './chief-network.js'`;
|
|
12
|
+
* - 通过 `registerPeerDirectoryReader(fn)` 在运行时注入同组会话目录读取器。
|
|
13
|
+
* - 本模块严禁引入 `child_process`,所有外部执行由调度层 / executor 沙箱通道完成。
|
|
14
|
+
*/
|
|
15
|
+
|
|
16
|
+
import fs from 'node:fs'
|
|
17
|
+
import os from 'node:os'
|
|
18
|
+
import path from 'node:path'
|
|
19
|
+
import {
|
|
20
|
+
MAIL_CAP,
|
|
21
|
+
CHAT_CAP,
|
|
22
|
+
nextId,
|
|
23
|
+
clamp,
|
|
24
|
+
loadChiefState,
|
|
25
|
+
mutateChiefState,
|
|
26
|
+
appendChiefAuditLog,
|
|
27
|
+
getLinkedCluster,
|
|
28
|
+
ensureWorkspace,
|
|
29
|
+
resolveWorkspaceConfig,
|
|
30
|
+
OFFICIAL_HARNESS_CATALOG,
|
|
31
|
+
setBubbleHarnessMembership,
|
|
32
|
+
} from './chief-state.js'
|
|
33
|
+
import { listGuardWalls } from './chief-executor.js'
|
|
34
|
+
|
|
35
|
+
let peerDirectoryReader = null
|
|
36
|
+
|
|
37
|
+
/** Register peer directory reader from chief-network.js without introducing a circular ESM import. */
|
|
38
|
+
export function registerPeerDirectoryReader(fn) {
|
|
39
|
+
peerDirectoryReader = typeof fn === 'function' ? fn : null
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
const PROBE_EXTERNAL_PROVIDER_NAMES = [
|
|
43
|
+
'codex',
|
|
44
|
+
'claude-code',
|
|
45
|
+
'acp',
|
|
46
|
+
'dsh-sdk',
|
|
47
|
+
'opencode',
|
|
48
|
+
'antigravity',
|
|
49
|
+
'gemini',
|
|
50
|
+
]
|
|
51
|
+
|
|
52
|
+
let localHarnessCache = { at: 0, envSig: '', map: new Map() }
|
|
53
|
+
|
|
54
|
+
function isRegularFileSafe(p) {
|
|
55
|
+
if (!p) return false
|
|
56
|
+
try {
|
|
57
|
+
return fs.statSync(p).isFile()
|
|
58
|
+
} catch {
|
|
59
|
+
return false
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
function platformBinCandidates(baseName) {
|
|
64
|
+
return process.platform === 'win32'
|
|
65
|
+
? [`${baseName}.exe`, `${baseName}.cmd`, `${baseName}.bat`, baseName]
|
|
66
|
+
: [baseName]
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
function findInSystemPath(candidates = []) {
|
|
70
|
+
const rawPath = String(process.env.PATH || '')
|
|
71
|
+
if (!rawPath) return ''
|
|
72
|
+
for (const dir of rawPath.split(path.delimiter)) {
|
|
73
|
+
const cleanDir = dir.trim().replace(/^"+|"+$/g, '')
|
|
74
|
+
if (!cleanDir) continue
|
|
75
|
+
for (const fileName of candidates) {
|
|
76
|
+
const full = path.join(cleanDir, fileName)
|
|
77
|
+
if (isRegularFileSafe(full)) return full
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
return ''
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
function resolveCodexFromAppAlias(aliasPath) {
|
|
84
|
+
try {
|
|
85
|
+
const target = fs.readlinkSync(aliasPath)
|
|
86
|
+
if (!target) return ''
|
|
87
|
+
if (path.basename(target).toLowerCase() === 'codex.exe' && isRegularFileSafe(target)) return target
|
|
88
|
+
const dir = path.dirname(target)
|
|
89
|
+
for (const cand of [
|
|
90
|
+
path.join(dir, 'codex.exe'),
|
|
91
|
+
path.join(dir, 'resources', 'codex.exe'),
|
|
92
|
+
path.join(path.dirname(dir), 'resources', 'codex.exe'),
|
|
93
|
+
]) {
|
|
94
|
+
if (isRegularFileSafe(cand)) return cand
|
|
95
|
+
}
|
|
96
|
+
} catch {}
|
|
97
|
+
return ''
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
function posixFallbackPaths(baseName) {
|
|
101
|
+
const home = os.homedir()
|
|
102
|
+
return [
|
|
103
|
+
`/opt/homebrew/bin/${baseName}`,
|
|
104
|
+
`/usr/local/bin/${baseName}`,
|
|
105
|
+
path.join(home, '.local', 'bin', baseName),
|
|
106
|
+
path.join(home, '.npm-global', 'bin', baseName),
|
|
107
|
+
path.join(home, '.volta', 'bin', baseName),
|
|
108
|
+
path.join(home, '.bun', 'bin', baseName),
|
|
109
|
+
path.join(home, '.asdf', 'shims', baseName),
|
|
110
|
+
]
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
function probeLocalCodexBinary() {
|
|
114
|
+
const envBin = String(process.env.DSH_CHIEF_CODEX_BIN || '').trim()
|
|
115
|
+
if (envBin && isRegularFileSafe(envBin)) return envBin
|
|
116
|
+
|
|
117
|
+
const fromPath = findInSystemPath(platformBinCandidates('codex'))
|
|
118
|
+
if (fromPath) return fromPath
|
|
119
|
+
|
|
120
|
+
if (process.platform === 'win32') {
|
|
121
|
+
const localApp = String(process.env.LOCALAPPDATA || '')
|
|
122
|
+
if (localApp) {
|
|
123
|
+
const aliasRoot = path.join(localApp, 'Microsoft', 'WindowsApps')
|
|
124
|
+
try {
|
|
125
|
+
const entries = fs.readdirSync(aliasRoot, { withFileTypes: true })
|
|
126
|
+
for (const ent of entries) {
|
|
127
|
+
if (ent.isDirectory() && /^OpenAI\.Codex_/i.test(ent.name)) {
|
|
128
|
+
const pkgAliasDir = path.join(aliasRoot, ent.name)
|
|
129
|
+
try {
|
|
130
|
+
for (const sub of fs.readdirSync(pkgAliasDir, { withFileTypes: true })) {
|
|
131
|
+
if (!sub.name.toLowerCase().endsWith('.exe')) continue
|
|
132
|
+
const hit = resolveCodexFromAppAlias(path.join(pkgAliasDir, sub.name))
|
|
133
|
+
if (hit) return hit
|
|
134
|
+
}
|
|
135
|
+
} catch {}
|
|
136
|
+
} else if (/^codex.*\.exe$/i.test(ent.name)) {
|
|
137
|
+
const hit = resolveCodexFromAppAlias(path.join(aliasRoot, ent.name))
|
|
138
|
+
if (hit) return hit
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
} catch {}
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
// Direct Windows Store MSIX fallback when WindowsApps is readable
|
|
145
|
+
const winAppsDir = process.env.ProgramFiles ? path.join(process.env.ProgramFiles, 'WindowsApps') : 'C:\\Program Files\\WindowsApps'
|
|
146
|
+
try {
|
|
147
|
+
const dirs = fs.readdirSync(winAppsDir, { withFileTypes: true })
|
|
148
|
+
.filter(d => d.isDirectory() && /^OpenAI\.Codex_/i.test(d.name))
|
|
149
|
+
.map(d => d.name)
|
|
150
|
+
.sort()
|
|
151
|
+
.reverse()
|
|
152
|
+
for (const dirName of dirs) {
|
|
153
|
+
for (const rel of ['app\\resources\\codex.exe', 'resources\\codex.exe', 'app\\codex.exe']) {
|
|
154
|
+
const cand = path.join(winAppsDir, dirName, rel)
|
|
155
|
+
if (isRegularFileSafe(cand)) return cand
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
} catch {}
|
|
159
|
+
|
|
160
|
+
const appData = String(process.env.APPDATA || '')
|
|
161
|
+
const home = os.homedir()
|
|
162
|
+
for (const cand of [
|
|
163
|
+
appData ? path.join(appData, 'npm', 'codex.cmd') : '',
|
|
164
|
+
localApp ? path.join(localApp, 'pnpm', 'codex.cmd') : '',
|
|
165
|
+
path.join(home, 'scoop', 'shims', 'codex.exe'),
|
|
166
|
+
path.join(home, 'scoop', 'shims', 'codex.cmd'),
|
|
167
|
+
path.join(home, '.local', 'bin', 'codex.exe'),
|
|
168
|
+
path.join(home, '.local', 'bin', 'codex'),
|
|
169
|
+
]) {
|
|
170
|
+
if (isRegularFileSafe(cand)) return cand
|
|
171
|
+
}
|
|
172
|
+
return ''
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
for (const cand of posixFallbackPaths('codex')) {
|
|
176
|
+
if (isRegularFileSafe(cand)) return cand
|
|
177
|
+
}
|
|
178
|
+
return ''
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
function findVersionedClaudeExe(baseDir, nestedHashDir = false) {
|
|
182
|
+
if (!baseDir) return ''
|
|
183
|
+
try {
|
|
184
|
+
const vers = fs.readdirSync(baseDir, { withFileTypes: true })
|
|
185
|
+
.filter(d => d.isDirectory())
|
|
186
|
+
.map(d => d.name)
|
|
187
|
+
.sort()
|
|
188
|
+
.reverse()
|
|
189
|
+
for (const ver of vers) {
|
|
190
|
+
const verDir = path.join(baseDir, ver)
|
|
191
|
+
if (!nestedHashDir) {
|
|
192
|
+
const direct = path.join(verDir, 'claude.exe')
|
|
193
|
+
if (isRegularFileSafe(direct)) return direct
|
|
194
|
+
} else {
|
|
195
|
+
try {
|
|
196
|
+
const subDirs = fs.readdirSync(verDir, { withFileTypes: true }).filter(d => d.isDirectory())
|
|
197
|
+
for (const sub of subDirs) {
|
|
198
|
+
const nested = path.join(verDir, sub.name, 'claude.exe')
|
|
199
|
+
if (isRegularFileSafe(nested)) return nested
|
|
200
|
+
}
|
|
201
|
+
} catch {}
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
} catch {}
|
|
205
|
+
return ''
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
function probeLocalClaudeBinary() {
|
|
209
|
+
const envBin = String(process.env.DSH_CHIEF_CLAUDE_BIN || '').trim()
|
|
210
|
+
if (envBin && isRegularFileSafe(envBin)) return envBin
|
|
211
|
+
|
|
212
|
+
const fromPath = findInSystemPath(platformBinCandidates('claude'))
|
|
213
|
+
if (fromPath) return fromPath
|
|
214
|
+
|
|
215
|
+
if (process.platform === 'win32') {
|
|
216
|
+
const localApp = String(process.env.LOCALAPPDATA || '')
|
|
217
|
+
const appData = String(process.env.APPDATA || '')
|
|
218
|
+
if (localApp) {
|
|
219
|
+
const claude3p = findVersionedClaudeExe(path.join(localApp, 'Claude-3p', 'claude-code'), true)
|
|
220
|
+
|| findVersionedClaudeExe(path.join(localApp, 'Claude-3p', 'claude-code'), false)
|
|
221
|
+
if (claude3p) return claude3p
|
|
222
|
+
|
|
223
|
+
try {
|
|
224
|
+
const pkgsDir = path.join(localApp, 'Packages')
|
|
225
|
+
const claudePkgs = fs.readdirSync(pkgsDir, { withFileTypes: true })
|
|
226
|
+
.filter(d => d.isDirectory() && /^AnthropicPBC\.Claude_/i.test(d.name))
|
|
227
|
+
for (const pkg of claudePkgs) {
|
|
228
|
+
const base = path.join(pkgsDir, pkg.name, 'LocalCache', 'Roaming', 'Claude', 'claude-code')
|
|
229
|
+
const hit = findVersionedClaudeExe(base, true) || findVersionedClaudeExe(base, false)
|
|
230
|
+
if (hit) return hit
|
|
231
|
+
}
|
|
232
|
+
} catch {}
|
|
233
|
+
}
|
|
234
|
+
if (appData) {
|
|
235
|
+
const roamingHit = findVersionedClaudeExe(path.join(appData, 'Claude', 'claude-code'), true)
|
|
236
|
+
|| findVersionedClaudeExe(path.join(appData, 'Claude', 'claude-code'), false)
|
|
237
|
+
if (roamingHit) return roamingHit
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
const home = os.homedir()
|
|
241
|
+
for (const cand of [
|
|
242
|
+
path.join(home, '.local', 'bin', 'claude.exe'),
|
|
243
|
+
path.join(home, '.local', 'bin', 'claude'),
|
|
244
|
+
appData ? path.join(appData, 'npm', 'claude.cmd') : '',
|
|
245
|
+
localApp ? path.join(localApp, 'pnpm', 'claude.cmd') : '',
|
|
246
|
+
path.join(home, 'scoop', 'shims', 'claude.exe'),
|
|
247
|
+
path.join(home, 'scoop', 'shims', 'claude.cmd'),
|
|
248
|
+
]) {
|
|
249
|
+
if (isRegularFileSafe(cand)) return cand
|
|
250
|
+
}
|
|
251
|
+
return ''
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
for (const cand of posixFallbackPaths('claude')) {
|
|
255
|
+
if (isRegularFileSafe(cand)) return cand
|
|
256
|
+
}
|
|
257
|
+
return ''
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
function isDirSafe(p) {
|
|
261
|
+
if (!p) return false
|
|
262
|
+
try {
|
|
263
|
+
return fs.statSync(p).isDirectory()
|
|
264
|
+
} catch {
|
|
265
|
+
return false
|
|
266
|
+
}
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
function probeLocalCodexConfig() {
|
|
270
|
+
const customHome = String(process.env.CODEX_HOME || '').trim()
|
|
271
|
+
const candidates = [
|
|
272
|
+
customHome ? { dir: customHome, label: 'CODEX_HOME' } : null,
|
|
273
|
+
{ dir: path.join(os.homedir(), '.codex'), label: '~/.codex' },
|
|
274
|
+
].filter(Boolean)
|
|
275
|
+
for (const item of candidates) {
|
|
276
|
+
if (isRegularFileSafe(path.join(item.dir, 'config.toml')) || isRegularFileSafe(path.join(item.dir, 'auth.json')) || isDirSafe(item.dir)) {
|
|
277
|
+
return { configured: true, configLabel: item.label }
|
|
278
|
+
}
|
|
279
|
+
}
|
|
280
|
+
if (String(process.env.OPENAI_API_KEY || '').trim()) {
|
|
281
|
+
return { configured: true, configLabel: 'OPENAI_API_KEY' }
|
|
282
|
+
}
|
|
283
|
+
if (String(process.env.AZURE_OPENAI_API_KEY || '').trim()) {
|
|
284
|
+
return { configured: true, configLabel: 'AZURE_OPENAI' }
|
|
285
|
+
}
|
|
286
|
+
return { configured: false, configLabel: '' }
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
function probeLocalClaudeConfig() {
|
|
290
|
+
const customDir = String(process.env.CLAUDE_CONFIG_DIR || '').trim()
|
|
291
|
+
const home = os.homedir()
|
|
292
|
+
const appData = String(process.env.APPDATA || '')
|
|
293
|
+
const candidates = [
|
|
294
|
+
customDir ? { check: customDir, type: 'dir', label: 'CLAUDE_CONFIG_DIR' } : null,
|
|
295
|
+
{ check: path.join(home, '.claude.json'), type: 'file', label: '~/.claude.json' },
|
|
296
|
+
{ check: path.join(home, '.claude'), type: 'dir', label: '~/.claude' },
|
|
297
|
+
appData ? { check: path.join(appData, 'Claude', 'claude_desktop_config.json'), type: 'file', label: 'Claude Desktop' } : null,
|
|
298
|
+
].filter(Boolean)
|
|
299
|
+
for (const item of candidates) {
|
|
300
|
+
const ok = item.type === 'file' ? isRegularFileSafe(item.check) : isDirSafe(item.check)
|
|
301
|
+
if (ok) {
|
|
302
|
+
return { configured: true, configLabel: item.label }
|
|
303
|
+
}
|
|
304
|
+
}
|
|
305
|
+
if (String(process.env.CLAUDE_CODE_OAUTH_TOKEN || '').trim()) {
|
|
306
|
+
return { configured: true, configLabel: 'OAuth Token' }
|
|
307
|
+
}
|
|
308
|
+
if (String(process.env.ANTHROPIC_API_KEY || '').trim()) {
|
|
309
|
+
return { configured: true, configLabel: 'ANTHROPIC_API_KEY' }
|
|
310
|
+
}
|
|
311
|
+
if (String(process.env.ANTHROPIC_AUTH_TOKEN || '').trim()) {
|
|
312
|
+
return { configured: true, configLabel: 'ANTHROPIC_AUTH_TOKEN' }
|
|
313
|
+
}
|
|
314
|
+
if (String(process.env.CLAUDE_CODE_USE_BEDROCK || '').trim()) {
|
|
315
|
+
return { configured: true, configLabel: 'Bedrock' }
|
|
316
|
+
}
|
|
317
|
+
if (String(process.env.CLAUDE_CODE_USE_VERTEX || '').trim()) {
|
|
318
|
+
return { configured: true, configLabel: 'Vertex' }
|
|
319
|
+
}
|
|
320
|
+
return { configured: false, configLabel: '' }
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
/** Pure filesystem detection of local external Harness CLIs (`codex`, `claude-code`) with 60s TTL cache. */
|
|
324
|
+
export function detectLocalHarnessBinaries({ force = false } = {}) {
|
|
325
|
+
const now = Date.now()
|
|
326
|
+
const envSig = [
|
|
327
|
+
process.env.DSH_CHIEF_CODEX_BIN || '',
|
|
328
|
+
process.env.DSH_CHIEF_CLAUDE_BIN || '',
|
|
329
|
+
process.env.CODEX_HOME || '',
|
|
330
|
+
process.env.CLAUDE_CONFIG_DIR || '',
|
|
331
|
+
process.env.OPENAI_API_KEY ? '1' : '0',
|
|
332
|
+
process.env.AZURE_OPENAI_API_KEY ? '1' : '0',
|
|
333
|
+
process.env.ANTHROPIC_API_KEY ? '1' : '0',
|
|
334
|
+
process.env.ANTHROPIC_AUTH_TOKEN ? '1' : '0',
|
|
335
|
+
process.env.CLAUDE_CODE_OAUTH_TOKEN ? '1' : '0',
|
|
336
|
+
process.env.CLAUDE_CODE_USE_BEDROCK ? '1' : '0',
|
|
337
|
+
process.env.CLAUDE_CODE_USE_VERTEX ? '1' : '0',
|
|
338
|
+
].join('|')
|
|
339
|
+
if (!force && envSig === localHarnessCache.envSig && (now - localHarnessCache.at) < 60_000) {
|
|
340
|
+
return localHarnessCache.map
|
|
341
|
+
}
|
|
342
|
+
const found = new Map()
|
|
343
|
+
const codexBin = probeLocalCodexBinary()
|
|
344
|
+
if (codexBin) {
|
|
345
|
+
const codexCfg = probeLocalCodexConfig()
|
|
346
|
+
found.set('codex', {
|
|
347
|
+
provider: 'codex',
|
|
348
|
+
binaryPath: codexBin,
|
|
349
|
+
transport: 'local-cli',
|
|
350
|
+
configured: codexCfg.configured,
|
|
351
|
+
configLabel: codexCfg.configLabel,
|
|
352
|
+
})
|
|
353
|
+
}
|
|
354
|
+
const claudeBin = probeLocalClaudeBinary()
|
|
355
|
+
if (claudeBin) {
|
|
356
|
+
const claudeCfg = probeLocalClaudeConfig()
|
|
357
|
+
found.set('claude-code', {
|
|
358
|
+
provider: 'claude-code',
|
|
359
|
+
binaryPath: claudeBin,
|
|
360
|
+
transport: 'local-cli',
|
|
361
|
+
configured: claudeCfg.configured,
|
|
362
|
+
configLabel: claudeCfg.configLabel,
|
|
363
|
+
})
|
|
364
|
+
}
|
|
365
|
+
localHarnessCache = { at: now, envSig, map: found }
|
|
366
|
+
return found
|
|
367
|
+
}
|
|
368
|
+
|
|
369
|
+
/** Discover registered external Harness backends (`ctx.subagents` + local `ctx.subprocess` direct CLIs). */
|
|
370
|
+
export function discoverHarnessProviders(runtime, hostState = null) {
|
|
371
|
+
const sub = runtime && typeof runtime.get === 'function' ? runtime.get('subagents') : null
|
|
372
|
+
const subprocessSvc = (runtime && typeof runtime.get === 'function' ? runtime.get('subprocess') : null)
|
|
373
|
+
|| (hostState && hostState.activeSubprocess)
|
|
374
|
+
|| null
|
|
375
|
+
const foundMap = new Map()
|
|
376
|
+
const addProv = (pname, prov, transport = 'dsh-subagent', binaryPath = '', meta = {}) => {
|
|
377
|
+
const clean = String(pname || '').trim()
|
|
378
|
+
if (!clean || clean === 'spawn' || clean === 'fork') return
|
|
379
|
+
if (prov && typeof prov.prepareContinuable === 'function') return
|
|
380
|
+
if (!foundMap.has(clean)) {
|
|
381
|
+
foundMap.set(clean, {
|
|
382
|
+
prov: prov || { name: clean },
|
|
383
|
+
transport,
|
|
384
|
+
binaryPath,
|
|
385
|
+
configured: meta.configured !== undefined ? Boolean(meta.configured) : (transport === 'dsh-subagent'),
|
|
386
|
+
configLabel: meta.configLabel || (transport === 'dsh-subagent' ? 'DSH 插件' : ''),
|
|
387
|
+
})
|
|
388
|
+
}
|
|
389
|
+
}
|
|
390
|
+
|
|
391
|
+
if (sub && sub.providers instanceof Map) {
|
|
392
|
+
for (const [pname, prov] of sub.providers.entries()) addProv(pname, prov, 'dsh-subagent', '')
|
|
393
|
+
}
|
|
394
|
+
if (sub && typeof sub.getProvider === 'function') {
|
|
395
|
+
for (const candidate of PROBE_EXTERNAL_PROVIDER_NAMES) {
|
|
396
|
+
try {
|
|
397
|
+
const prov = sub.getProvider(candidate)
|
|
398
|
+
if (prov) addProv(prov.name || candidate, prov, 'dsh-subagent', '')
|
|
399
|
+
} catch {}
|
|
400
|
+
}
|
|
401
|
+
}
|
|
402
|
+
if (hostState && hostState.detectedHarnessProviders instanceof Map) {
|
|
403
|
+
for (const [pname, prov] of hostState.detectedHarnessProviders.entries()) addProv(pname, prov, 'dsh-subagent', '')
|
|
404
|
+
}
|
|
405
|
+
|
|
406
|
+
// Layer 2: Directly detected local Codex / Claude Code CLIs via host ctx.subprocess
|
|
407
|
+
if (subprocessSvc && typeof subprocessSvc.spawn === 'function') {
|
|
408
|
+
const localBins = detectLocalHarnessBinaries()
|
|
409
|
+
for (const [pname, info] of localBins.entries()) {
|
|
410
|
+
addProv(pname, { name: pname }, 'local-cli', info.binaryPath, {
|
|
411
|
+
configured: info.configured,
|
|
412
|
+
configLabel: info.configLabel,
|
|
413
|
+
})
|
|
414
|
+
}
|
|
415
|
+
}
|
|
416
|
+
|
|
417
|
+
const available = []
|
|
418
|
+
for (const [pname, entry] of foundMap.entries()) {
|
|
419
|
+
const prov = entry.prov
|
|
420
|
+
const official = OFFICIAL_HARNESS_CATALOG.find(item => item.provider === pname)
|
|
421
|
+
const caps = (prov && prov.capabilities && typeof prov.capabilities === 'object') ? prov.capabilities : {}
|
|
422
|
+
available.push({
|
|
423
|
+
provider: pname,
|
|
424
|
+
label: (official && official.label) || String((prov && prov.label) || pname),
|
|
425
|
+
packageName: (official && official.packageName) || '',
|
|
426
|
+
accent: (official && official.accent) || '#38bdf8',
|
|
427
|
+
roleHint: (official && official.roleHint) || '外部 Harness 执行进程',
|
|
428
|
+
mode: 'one-shot',
|
|
429
|
+
installed: true,
|
|
430
|
+
transport: entry.transport,
|
|
431
|
+
binaryPath: entry.binaryPath || '',
|
|
432
|
+
configured: Boolean(entry.configured),
|
|
433
|
+
configLabel: entry.configLabel || '',
|
|
434
|
+
capabilities: {
|
|
435
|
+
agentPreset: Boolean(caps.agentPreset),
|
|
436
|
+
outputSchema: Boolean(caps.outputSchema),
|
|
437
|
+
depthLimit: Boolean(caps.depthLimit),
|
|
438
|
+
},
|
|
439
|
+
})
|
|
440
|
+
}
|
|
441
|
+
|
|
442
|
+
const availableNames = new Set(available.map(x => x.provider))
|
|
443
|
+
const catalog = OFFICIAL_HARNESS_CATALOG
|
|
444
|
+
.filter(item => !availableNames.has(item.provider))
|
|
445
|
+
.map(item => ({
|
|
446
|
+
...item,
|
|
447
|
+
mode: 'one-shot',
|
|
448
|
+
installed: false,
|
|
449
|
+
transport: '',
|
|
450
|
+
binaryPath: '',
|
|
451
|
+
installCmd: `dsh plugin --profile desktop add ${item.packageName}`,
|
|
452
|
+
}))
|
|
453
|
+
|
|
454
|
+
return { available, catalog }
|
|
455
|
+
}
|
|
456
|
+
|
|
457
|
+
/** Force-refresh local external CLI probes, host subagent providers, and dormant session title cache. */
|
|
458
|
+
export function refreshBubbleDiscovery(runtime, hostState = null) {
|
|
459
|
+
detectLocalHarnessBinaries({ force: true })
|
|
460
|
+
if (hostState && typeof hostState === 'object') {
|
|
461
|
+
hostState.dormantTitleCache = new Map()
|
|
462
|
+
const sub = runtime && typeof runtime.get === 'function' ? runtime.get('subagents') : null
|
|
463
|
+
if (sub) {
|
|
464
|
+
if (!(hostState.detectedHarnessProviders instanceof Map)) {
|
|
465
|
+
hostState.detectedHarnessProviders = new Map()
|
|
466
|
+
}
|
|
467
|
+
const addDetected = (pname, prov) => {
|
|
468
|
+
const clean = String(pname || '').trim()
|
|
469
|
+
if (!clean || clean === 'spawn' || clean === 'fork') return
|
|
470
|
+
if (prov && typeof prov.prepareContinuable === 'function') return
|
|
471
|
+
hostState.detectedHarnessProviders.set(clean, prov || { name: clean })
|
|
472
|
+
}
|
|
473
|
+
if (sub.providers instanceof Map) {
|
|
474
|
+
for (const [pname, prov] of sub.providers.entries()) addDetected(pname, prov)
|
|
475
|
+
}
|
|
476
|
+
if (typeof sub.listProviders === 'function') {
|
|
477
|
+
try {
|
|
478
|
+
for (const prov of sub.listProviders() || []) {
|
|
479
|
+
if (prov && (prov.name || prov.id)) addDetected(prov.name || prov.id, prov)
|
|
480
|
+
}
|
|
481
|
+
} catch {}
|
|
482
|
+
}
|
|
483
|
+
if (typeof sub.getProvider === 'function') {
|
|
484
|
+
for (const candidate of PROBE_EXTERNAL_PROVIDER_NAMES) {
|
|
485
|
+
try {
|
|
486
|
+
const prov = sub.getProvider(candidate)
|
|
487
|
+
if (prov) addDetected(prov.name || candidate, prov)
|
|
488
|
+
} catch {}
|
|
489
|
+
}
|
|
490
|
+
}
|
|
491
|
+
}
|
|
492
|
+
}
|
|
493
|
+
return {
|
|
494
|
+
localHarnesses: detectLocalHarnessBinaries({ force: false }).size,
|
|
495
|
+
}
|
|
496
|
+
}
|
|
497
|
+
|
|
498
|
+
/** Compute live Bubble squad membership, available Harnesses, and hard structural lock state. */
|
|
499
|
+
export function computeBubbleState(deps, rootId, state, directory = null) {
|
|
500
|
+
const rid = String(rootId || 'global').trim() || 'global'
|
|
501
|
+
const st = state || loadChiefState()
|
|
502
|
+
const ws = ensureWorkspace(st, rid)
|
|
503
|
+
const cfg = resolveWorkspaceConfig(st, rid)
|
|
504
|
+
const cluster = (directory && Array.isArray(directory.cluster)) ? directory.cluster : getLinkedCluster(st, rid)
|
|
505
|
+
const enrolledHarnesses = Array.isArray(ws.bubbleHarnesses) ? ws.bubbleHarnesses.slice() : []
|
|
506
|
+
const enrolledSet = new Set(enrolledHarnesses.map(h => h && h.provider).filter(Boolean))
|
|
507
|
+
const targets = (directory && Array.isArray(directory.targets)) ? directory.targets : []
|
|
508
|
+
const disc = discoverHarnessProviders(deps && deps.runtime, deps && deps.hostState)
|
|
509
|
+
|
|
510
|
+
const activeRunners = targets
|
|
511
|
+
.filter(t => t && t.status === 'running')
|
|
512
|
+
.map(t => ({ key: t.key, id: t.id, name: t.name, kind: t.kind }))
|
|
513
|
+
|
|
514
|
+
const activeExternalRuns = []
|
|
515
|
+
const runsMap = deps && deps.hostState && deps.hostState.activeBubbleRuns
|
|
516
|
+
if (runsMap instanceof Map) {
|
|
517
|
+
for (const run of runsMap.values()) {
|
|
518
|
+
if (run && (!run.rootId || run.rootId === rid)) {
|
|
519
|
+
activeExternalRuns.push({
|
|
520
|
+
runId: run.id,
|
|
521
|
+
provider: run.provider,
|
|
522
|
+
label: run.label,
|
|
523
|
+
childId: run.childId || '',
|
|
524
|
+
transport: run.transport || '',
|
|
525
|
+
startedAt: run.startedAt || 0,
|
|
526
|
+
})
|
|
527
|
+
}
|
|
528
|
+
}
|
|
529
|
+
}
|
|
530
|
+
|
|
531
|
+
const hasCrossSquad = cluster.length > 1 || enrolledHarnesses.length > 0
|
|
532
|
+
const interventionActive = Boolean(cfg && cfg.tacticalModes && cfg.tacticalModes.intervention && !cfg.stopped)
|
|
533
|
+
const autoLocked = activeExternalRuns.length > 0
|
|
534
|
+
|| (hasCrossSquad && (activeRunners.length > 0 || interventionActive))
|
|
535
|
+
const manualLocked = Boolean(ws.bubbleLock && ws.bubbleLock.manualLocked)
|
|
536
|
+
const locked = manualLocked || autoLocked
|
|
537
|
+
|
|
538
|
+
const reasons = []
|
|
539
|
+
if (activeExternalRuns.length > 0) reasons.push(`${activeExternalRuns.length} 个外部 Harness 执行中`)
|
|
540
|
+
if (hasCrossSquad && activeRunners.length > 0) reasons.push(`${activeRunners.length} 个会话/子代理运行中`)
|
|
541
|
+
if (hasCrossSquad && interventionActive) reasons.push('主动强介入督导进行中')
|
|
542
|
+
if (manualLocked && ws.bubbleLock && ws.bubbleLock.reason) reasons.push(ws.bubbleLock.reason)
|
|
543
|
+
else if (manualLocked) reasons.push('已手动锁定编队结构')
|
|
544
|
+
|
|
545
|
+
return {
|
|
546
|
+
locked,
|
|
547
|
+
autoLocked,
|
|
548
|
+
manualLocked,
|
|
549
|
+
lockReason: reasons.join(' · '),
|
|
550
|
+
hasCrossSquad,
|
|
551
|
+
activeRunners,
|
|
552
|
+
activeExternalRuns,
|
|
553
|
+
enrolledHarnesses: enrolledHarnesses.map(h => {
|
|
554
|
+
const avail = disc.available.find(a => a.provider === h.provider)
|
|
555
|
+
const official = OFFICIAL_HARNESS_CATALOG.find(item => item.provider === h.provider)
|
|
556
|
+
const roleHint = (avail && avail.roleHint) || (official && official.roleHint) || '外部 Harness 执行进程'
|
|
557
|
+
return {
|
|
558
|
+
...h,
|
|
559
|
+
role: h.role || roleHint,
|
|
560
|
+
roleHint,
|
|
561
|
+
installed: Boolean(avail),
|
|
562
|
+
transport: (avail && avail.transport) || h.transport || '',
|
|
563
|
+
binaryPath: (avail && avail.binaryPath) || '',
|
|
564
|
+
configured: Boolean(avail && avail.configured),
|
|
565
|
+
configLabel: (avail && avail.configLabel) || '',
|
|
566
|
+
running: activeExternalRuns.some(r => r.provider === h.provider),
|
|
567
|
+
}
|
|
568
|
+
}),
|
|
569
|
+
availableHarnesses: disc.available.filter(a => !enrolledSet.has(a.provider)),
|
|
570
|
+
catalogHarnesses: disc.catalog,
|
|
571
|
+
}
|
|
572
|
+
}
|
|
573
|
+
|
|
574
|
+
const BUBBLE_LOCK_ERR = '🔒 协同水泡工作中已锁死结构,不允许中途拆解或改动编队;请等待全员收工或点击「⏹ 急停解体」'
|
|
575
|
+
|
|
576
|
+
const CLAUDE_FORWARD_ENV_KEYS = [
|
|
577
|
+
'CLAUDE_CONFIG_DIR',
|
|
578
|
+
'ANTHROPIC_BASE_URL',
|
|
579
|
+
'ANTHROPIC_API_KEY',
|
|
580
|
+
'ANTHROPIC_AUTH_TOKEN',
|
|
581
|
+
'CLAUDE_CODE_OAUTH_TOKEN',
|
|
582
|
+
'ANTHROPIC_MODEL',
|
|
583
|
+
'ANTHROPIC_SMALL_FAST_MODEL',
|
|
584
|
+
'ANTHROPIC_DEFAULT_SONNET_MODEL',
|
|
585
|
+
'ANTHROPIC_DEFAULT_OPUS_MODEL',
|
|
586
|
+
'ANTHROPIC_DEFAULT_HAIKU_MODEL',
|
|
587
|
+
'CLAUDE_CODE_USE_BEDROCK',
|
|
588
|
+
'CLAUDE_CODE_USE_VERTEX',
|
|
589
|
+
'CLAUDE_CODE_USE_FOUNDRY',
|
|
590
|
+
'CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC',
|
|
591
|
+
'API_TIMEOUT_MS',
|
|
592
|
+
'AWS_ACCESS_KEY_ID',
|
|
593
|
+
'AWS_SECRET_ACCESS_KEY',
|
|
594
|
+
'AWS_SESSION_TOKEN',
|
|
595
|
+
'AWS_BEARER_TOKEN_BEDROCK',
|
|
596
|
+
'AWS_REGION',
|
|
597
|
+
'AWS_PROFILE',
|
|
598
|
+
'ANTHROPIC_VERTEX_PROJECT_ID',
|
|
599
|
+
'CLOUD_ML_REGION',
|
|
600
|
+
'GOOGLE_APPLICATION_CREDENTIALS',
|
|
601
|
+
]
|
|
602
|
+
|
|
603
|
+
const CODEX_FORWARD_ENV_KEYS = [
|
|
604
|
+
'CODEX_HOME',
|
|
605
|
+
'OPENAI_API_KEY',
|
|
606
|
+
'OPENAI_BASE_URL',
|
|
607
|
+
'OPENAI_ORG_ID',
|
|
608
|
+
'OPENAI_PROJECT',
|
|
609
|
+
'AZURE_OPENAI_API_KEY',
|
|
610
|
+
'AZURE_OPENAI_ENDPOINT',
|
|
611
|
+
'AZURE_OPENAI_API_VERSION',
|
|
612
|
+
]
|
|
613
|
+
|
|
614
|
+
function resolveLocalCliArgv(binaryPath, cliArgs = []) {
|
|
615
|
+
const bin = String(binaryPath || '').trim()
|
|
616
|
+
if (!bin) return cliArgs
|
|
617
|
+
if (process.platform === 'win32' && /\.(cmd|bat)$/i.test(bin)) {
|
|
618
|
+
try {
|
|
619
|
+
const fd = fs.openSync(bin, 'r')
|
|
620
|
+
const buf = Buffer.alloc(16384)
|
|
621
|
+
let bytes = 0
|
|
622
|
+
try {
|
|
623
|
+
bytes = fs.readSync(fd, buf, 0, buf.length, 0)
|
|
624
|
+
} finally {
|
|
625
|
+
fs.closeSync(fd)
|
|
626
|
+
}
|
|
627
|
+
const txt = buf.toString('utf8', 0, bytes)
|
|
628
|
+
const binDir = path.dirname(bin)
|
|
629
|
+
const dpRe = /(?:%dp0%|%~dp0)[\\/]*([^\r\n"'`<>|*?\t]+?\.(?:mjs|cjs|js|exe))(?=["'\s]|$)/gi
|
|
630
|
+
let m
|
|
631
|
+
while ((m = dpRe.exec(txt)) !== null) {
|
|
632
|
+
const rel = String(m[1] || '').replace(/[\\/]+/g, path.sep)
|
|
633
|
+
const resolved = path.resolve(binDir, rel)
|
|
634
|
+
const baseLower = path.basename(resolved).toLowerCase()
|
|
635
|
+
if (!baseLower || baseLower === 'node.exe' || !isRegularFileSafe(resolved)) continue
|
|
636
|
+
if (baseLower.endsWith('.exe')) return [resolved, ...cliArgs]
|
|
637
|
+
return [process.execPath, resolved, ...cliArgs]
|
|
638
|
+
}
|
|
639
|
+
const absRe = /(["'])([A-Za-z]:[\\/][^"'\r\n]+?\.(?:exe|mjs|cjs|js))\1/gi
|
|
640
|
+
while ((m = absRe.exec(txt)) !== null) {
|
|
641
|
+
const resolved = path.normalize(String(m[2] || ''))
|
|
642
|
+
const baseLower = path.basename(resolved).toLowerCase()
|
|
643
|
+
if (!baseLower || baseLower === 'node.exe' || !isRegularFileSafe(resolved)) continue
|
|
644
|
+
if (baseLower.endsWith('.exe')) return [resolved, ...cliArgs]
|
|
645
|
+
return [process.execPath, resolved, ...cliArgs]
|
|
646
|
+
}
|
|
647
|
+
} catch {}
|
|
648
|
+
return [process.env.ComSpec || 'cmd.exe', '/d', '/s', '/c', bin, ...cliArgs]
|
|
649
|
+
}
|
|
650
|
+
return [bin, ...cliArgs]
|
|
651
|
+
}
|
|
652
|
+
|
|
653
|
+
/** Build explicit opt-in child env for out-of-process external CLIs (passes dsh-subprocess scrub without leaking DEEPSEEK_* / DSH_*). */
|
|
654
|
+
function buildExternalHarnessEnv(provider) {
|
|
655
|
+
const keys = provider === 'claude-code'
|
|
656
|
+
? CLAUDE_FORWARD_ENV_KEYS
|
|
657
|
+
: (provider === 'codex' ? CODEX_FORWARD_ENV_KEYS : [])
|
|
658
|
+
if (!keys.length) return undefined
|
|
659
|
+
const out = {}
|
|
660
|
+
for (const k of keys) {
|
|
661
|
+
const val = process.env[k]
|
|
662
|
+
if (typeof val === 'string' && val.length > 0) {
|
|
663
|
+
out[k] = val
|
|
664
|
+
}
|
|
665
|
+
}
|
|
666
|
+
return Object.keys(out).length ? out : undefined
|
|
667
|
+
}
|
|
668
|
+
|
|
669
|
+
const HARNESS_TARGET_ALIASES = {
|
|
670
|
+
claude: 'claude-code',
|
|
671
|
+
claudecode: 'claude-code',
|
|
672
|
+
'claude code': 'claude-code',
|
|
673
|
+
'claude-code': 'claude-code',
|
|
674
|
+
codex: 'codex',
|
|
675
|
+
'openai-codex': 'codex',
|
|
676
|
+
}
|
|
677
|
+
|
|
678
|
+
/** Resolve an external Harness target identifier or alias against enrolled/available Harnesses in the Bubble. */
|
|
679
|
+
export function resolveExternalHarnessTarget(runtime, hostState, rootId, rawTarget) {
|
|
680
|
+
const clean = String(rawTarget || '').trim().replace(/^@/, '').toLowerCase()
|
|
681
|
+
if (!clean) return null
|
|
682
|
+
const canonical = HARNESS_TARGET_ALIASES[clean] || clean
|
|
683
|
+
const bState = computeBubbleState({ runtime, hostState }, rootId)
|
|
684
|
+
const enrolledList = Array.isArray(bState.enrolledHarnesses) ? bState.enrolledHarnesses : []
|
|
685
|
+
const availList = Array.isArray(bState.availableHarnesses) ? bState.availableHarnesses : []
|
|
686
|
+
|
|
687
|
+
const matchItem = (item) => {
|
|
688
|
+
if (!item || !item.provider || item.installed === false) return false
|
|
689
|
+
const pLow = String(item.provider).trim().toLowerCase()
|
|
690
|
+
const lLow = String(item.label || '').trim().toLowerCase()
|
|
691
|
+
return pLow === canonical || pLow === clean || lLow === clean
|
|
692
|
+
}
|
|
693
|
+
|
|
694
|
+
const enrolledHit = enrolledList.find(matchItem)
|
|
695
|
+
if (enrolledHit) {
|
|
696
|
+
return {
|
|
697
|
+
provider: enrolledHit.provider,
|
|
698
|
+
label: enrolledHit.label || enrolledHit.provider,
|
|
699
|
+
transport: enrolledHit.transport || '',
|
|
700
|
+
installed: Boolean(enrolledHit.installed),
|
|
701
|
+
enrolled: true,
|
|
702
|
+
}
|
|
703
|
+
}
|
|
704
|
+
|
|
705
|
+
const availHit = availList.find(matchItem)
|
|
706
|
+
if (availHit) {
|
|
707
|
+
return {
|
|
708
|
+
provider: availHit.provider,
|
|
709
|
+
label: availHit.label || availHit.provider,
|
|
710
|
+
transport: availHit.transport || '',
|
|
711
|
+
installed: Boolean(availHit.installed),
|
|
712
|
+
enrolled: false,
|
|
713
|
+
}
|
|
714
|
+
}
|
|
715
|
+
return null
|
|
716
|
+
}
|
|
717
|
+
|
|
718
|
+
/** Unified out-of-process external Harness dispatcher shared by HTTP routes & DSH Chief relays. */
|
|
719
|
+
export async function dispatchBubbleHarness(deps, {
|
|
720
|
+
rootId = '',
|
|
721
|
+
provider = '',
|
|
722
|
+
text = '',
|
|
723
|
+
label = '',
|
|
724
|
+
fromLabel = 'DSH 参谋长',
|
|
725
|
+
force = false,
|
|
726
|
+
allowAutoEnroll = true,
|
|
727
|
+
} = {}) {
|
|
728
|
+
const rid = String(rootId || 'global').trim() || 'global'
|
|
729
|
+
const cleanProvider = clamp(String(provider || '').trim(), 64)
|
|
730
|
+
const taskText = typeof text === 'string' ? text.trim() : ''
|
|
731
|
+
const taskLabel = clamp(String(label || taskText || cleanProvider).trim(), 48)
|
|
732
|
+
if (!cleanProvider || !taskText) {
|
|
733
|
+
return { ok: false, statusCode: 400, error: '需要指定目标 Harness provider 与任务内容' }
|
|
734
|
+
}
|
|
735
|
+
|
|
736
|
+
const runtime = deps && deps.runtime
|
|
737
|
+
const subagents = runtime && typeof runtime.get === 'function' ? runtime.get('subagents') : null
|
|
738
|
+
const agentsSvc = runtime && typeof runtime.get === 'function' ? runtime.get('agents') : null
|
|
739
|
+
const subprocessSvc = (runtime && typeof runtime.get === 'function' ? runtime.get('subprocess') : null)
|
|
740
|
+
|| (deps && deps.hostState && deps.hostState.activeSubprocess)
|
|
741
|
+
|| null
|
|
742
|
+
const prov = subagents && typeof subagents.getProvider === 'function' ? subagents.getProvider(cleanProvider) : null
|
|
743
|
+
const localHit = detectLocalHarnessBinaries().get(cleanProvider) || null
|
|
744
|
+
const canUseSubagent = Boolean(subagents && typeof subagents.startActivation === 'function' && prov)
|
|
745
|
+
const canUseLocalCli = Boolean(subprocessSvc && typeof subprocessSvc.spawn === 'function' && localHit && localHit.binaryPath)
|
|
746
|
+
|
|
747
|
+
if (!canUseSubagent && !canUseLocalCli) {
|
|
748
|
+
return {
|
|
749
|
+
ok: false,
|
|
750
|
+
statusCode: 400,
|
|
751
|
+
error: `当前宿主未检测到「${cleanProvider}」外部插件,也未找到本机 CLI(可安装 @deepseek-ai/dsh-subagent-${cleanProvider} 或本机 CLI 后重试)`,
|
|
752
|
+
}
|
|
753
|
+
}
|
|
754
|
+
|
|
755
|
+
const liveCaller = (agentsSvc && typeof agentsSvc.get === 'function' ? agentsSvc.get(rid) : null)
|
|
756
|
+
|| (deps && typeof deps.findLiveCallerAgent === 'function' ? deps.findLiveCallerAgent(runtime, rid, null) : null)
|
|
757
|
+
if (!canUseLocalCli && canUseSubagent && !liveCaller) {
|
|
758
|
+
return {
|
|
759
|
+
ok: false,
|
|
760
|
+
statusCode: 400,
|
|
761
|
+
error: '当前主对话会话未激活,请先在主窗口发一条消息激活会话',
|
|
762
|
+
}
|
|
763
|
+
}
|
|
764
|
+
|
|
765
|
+
const stNow = loadChiefState()
|
|
766
|
+
const wsNow = ensureWorkspace(stNow, rid)
|
|
767
|
+
const official = OFFICIAL_HARNESS_CATALOG.find(item => item.provider === cleanProvider)
|
|
768
|
+
const displayLabel = (official && official.label) || String((prov && prov.label) || cleanProvider)
|
|
769
|
+
const isEnrolled = Array.isArray(wsNow.bubbleHarnesses) && wsNow.bubbleHarnesses.some(h => h && h.provider === cleanProvider)
|
|
770
|
+
|
|
771
|
+
if (!isEnrolled) {
|
|
772
|
+
const dirNow = peerDirectoryReader ? await peerDirectoryReader(deps, rid).catch(() => ({ targets: [], cluster: [] })) : { targets: [], cluster: [] }
|
|
773
|
+
const bState = computeBubbleState(deps, rid, stNow, dirNow)
|
|
774
|
+
if (bState.locked && force !== true) {
|
|
775
|
+
return { ok: false, locked: true, statusCode: 409, error: BUBBLE_LOCK_ERR, bubble: bState }
|
|
776
|
+
}
|
|
777
|
+
if (!allowAutoEnroll) {
|
|
778
|
+
return { ok: false, statusCode: 400, error: `外部 Harness「${displayLabel}」尚未编入当前协同水泡` }
|
|
779
|
+
}
|
|
780
|
+
setBubbleHarnessMembership(rid, {
|
|
781
|
+
provider: cleanProvider,
|
|
782
|
+
label: displayLabel,
|
|
783
|
+
role: (official && official.roleHint) || '外部 Harness 执行进程',
|
|
784
|
+
joined: true,
|
|
785
|
+
})
|
|
786
|
+
}
|
|
787
|
+
|
|
788
|
+
let actionCwd = process.cwd()
|
|
789
|
+
try {
|
|
790
|
+
const resolvedCwd = deps && typeof deps.getSessionCwd === 'function' ? deps.getSessionCwd(rid) : ''
|
|
791
|
+
if (resolvedCwd) actionCwd = resolvedCwd
|
|
792
|
+
} catch {}
|
|
793
|
+
|
|
794
|
+
let boardNow = null
|
|
795
|
+
try {
|
|
796
|
+
if (rid && deps && typeof deps.boardForSession === 'function' && typeof deps.boardFileFor === 'function') {
|
|
797
|
+
boardNow = deps.boardForSession(deps.boardFileFor(rid))
|
|
798
|
+
}
|
|
799
|
+
} catch {}
|
|
800
|
+
const forbiddenList = (boardNow && boardNow.bounds && Array.isArray(boardNow.bounds.forbidden))
|
|
801
|
+
? boardNow.bounds.forbidden.filter(Boolean).slice(0, 8)
|
|
802
|
+
: []
|
|
803
|
+
const activeWalls = listGuardWalls({ cwd: actionCwd }).filter(w => w && w.activeNow).slice(0, 8)
|
|
804
|
+
const constraintLines = []
|
|
805
|
+
if (forbiddenList.length) {
|
|
806
|
+
constraintLines.push('禁止红线: ' + forbiddenList.join(';'))
|
|
807
|
+
}
|
|
808
|
+
if (activeWalls.length) {
|
|
809
|
+
constraintLines.push('物理驻墙保护: ' + activeWalls.map(w => `${w.title}(${(w.patterns || []).join(', ')})`).join(';'))
|
|
810
|
+
}
|
|
811
|
+
const safePrompt = constraintLines.length
|
|
812
|
+
? `[DSH 参谋长协同水泡派单 · 外部独立进程需严格遵守以下边界]\n${constraintLines.join('\n')}\n\n[任务内容]\n${taskText}`
|
|
813
|
+
: taskText
|
|
814
|
+
|
|
815
|
+
if (deps && deps.hostState && !(deps.hostState.activeBubbleRuns instanceof Map)) {
|
|
816
|
+
deps.hostState.activeBubbleRuns = new Map()
|
|
817
|
+
}
|
|
818
|
+
const activeRuns = deps && deps.hostState ? deps.hostState.activeBubbleRuns : null
|
|
819
|
+
|
|
820
|
+
const ac = new AbortController()
|
|
821
|
+
const runKey = nextId('brun')
|
|
822
|
+
const recordDispatchState = (childIdVal, transportLabel) => {
|
|
823
|
+
appendChiefAuditLog(rid, {
|
|
824
|
+
kind: 'bubble_harness_dispatch',
|
|
825
|
+
decision: 'allowed',
|
|
826
|
+
tool: cleanProvider,
|
|
827
|
+
reason: `${fromLabel} 向水泡外部 Harness「${cleanProvider}」(${transportLabel}) 派发任务并自动锁死编队:${taskLabel}`,
|
|
828
|
+
})
|
|
829
|
+
mutateChiefState((st) => {
|
|
830
|
+
const ws = ensureWorkspace(st, rid)
|
|
831
|
+
const harnessRoot = `harness:${cleanProvider}`
|
|
832
|
+
ws.mailbox.push({
|
|
833
|
+
id: nextId('mail'),
|
|
834
|
+
from: fromLabel || 'DSH 参谋长',
|
|
835
|
+
fromSession: rid,
|
|
836
|
+
fromRootId: rid,
|
|
837
|
+
to: cleanProvider,
|
|
838
|
+
toSession: childIdVal || cleanProvider,
|
|
839
|
+
toRootId: harnessRoot,
|
|
840
|
+
participantRoots: [rid, harnessRoot],
|
|
841
|
+
subject: `外部 Harness 派单 · ${cleanProvider}`,
|
|
842
|
+
text: taskText.slice(0, 1200),
|
|
843
|
+
mode: 'followup',
|
|
844
|
+
channelType: 'pair',
|
|
845
|
+
readBy: [rid],
|
|
846
|
+
at: Date.now(),
|
|
847
|
+
})
|
|
848
|
+
if (ws.mailbox.length > MAIL_CAP) ws.mailbox = ws.mailbox.slice(-MAIL_CAP)
|
|
849
|
+
ws.chat.push({
|
|
850
|
+
id: nextId('chat'),
|
|
851
|
+
role: 'chief',
|
|
852
|
+
kind: 'receipt',
|
|
853
|
+
text: `- 【⚡ 水泡派单 · ${cleanProvider}】已启动${transportLabel === 'local-cli' ? '本机 CLI 直连' : '外部 Harness'}执行「${taskLabel}」,编队已自动锁定保护。`,
|
|
854
|
+
actions: ['🔒 编队工作中已锁死'],
|
|
855
|
+
at: Date.now(),
|
|
856
|
+
})
|
|
857
|
+
if (ws.chat.length > CHAT_CAP) ws.chat = ws.chat.slice(-CHAT_CAP)
|
|
858
|
+
})
|
|
859
|
+
}
|
|
860
|
+
|
|
861
|
+
const writeSettlementReceipt = (childIdVal, outText, ok = true) => {
|
|
862
|
+
const bodyTxt = clamp(String(outText || '').trim() || (ok ? '外部 Harness 任务已完成' : '外部 Harness 执行未返回有效结果'), 1400)
|
|
863
|
+
mutateChiefState((st) => {
|
|
864
|
+
const ws = ensureWorkspace(st, rid)
|
|
865
|
+
const harnessRoot = `harness:${cleanProvider}`
|
|
866
|
+
ws.mailbox.push({
|
|
867
|
+
id: nextId('mail'),
|
|
868
|
+
from: `@${cleanProvider}`,
|
|
869
|
+
fromSession: childIdVal || cleanProvider,
|
|
870
|
+
fromRootId: harnessRoot,
|
|
871
|
+
to: 'lead',
|
|
872
|
+
toSession: rid,
|
|
873
|
+
toRootId: rid,
|
|
874
|
+
participantRoots: [rid, harnessRoot],
|
|
875
|
+
subject: `外部 Harness 回执 · ${cleanProvider}`,
|
|
876
|
+
text: bodyTxt,
|
|
877
|
+
mode: 'followup',
|
|
878
|
+
channelType: 'pair',
|
|
879
|
+
readBy: [],
|
|
880
|
+
at: Date.now(),
|
|
881
|
+
})
|
|
882
|
+
if (ws.mailbox.length > MAIL_CAP) ws.mailbox = ws.mailbox.slice(-MAIL_CAP)
|
|
883
|
+
ws.chat.push({
|
|
884
|
+
id: nextId('chat'),
|
|
885
|
+
role: 'chief',
|
|
886
|
+
kind: 'receipt',
|
|
887
|
+
text: ok
|
|
888
|
+
? `- 【✅ @${cleanProvider} 交卷】${bodyTxt.slice(0, 320)}`
|
|
889
|
+
: `- 【⚠️ @${cleanProvider} 异常中断】${bodyTxt.slice(0, 320)}`,
|
|
890
|
+
actions: [ok ? '解开对应执行锁' : '🔓 已释放执行锁'],
|
|
891
|
+
at: Date.now(),
|
|
892
|
+
})
|
|
893
|
+
if (ws.chat.length > CHAT_CAP) ws.chat = ws.chat.slice(-CHAT_CAP)
|
|
894
|
+
})
|
|
895
|
+
}
|
|
896
|
+
|
|
897
|
+
let childId = runKey
|
|
898
|
+
let usedTransport = 'dsh-subagent'
|
|
899
|
+
|
|
900
|
+
if (canUseSubagent && liveCaller) {
|
|
901
|
+
const activation = await subagents.startActivation({
|
|
902
|
+
provider: cleanProvider,
|
|
903
|
+
label: taskLabel,
|
|
904
|
+
prompt: [{ type: 'text', text: safePrompt }],
|
|
905
|
+
parent: liveCaller,
|
|
906
|
+
signal: ac.signal,
|
|
907
|
+
delivery: 'parent',
|
|
908
|
+
})
|
|
909
|
+
childId = String((activation && activation.childId) || '') || runKey
|
|
910
|
+
if (activeRuns) {
|
|
911
|
+
activeRuns.set(runKey, {
|
|
912
|
+
id: runKey,
|
|
913
|
+
rootId: rid,
|
|
914
|
+
provider: cleanProvider,
|
|
915
|
+
label: taskLabel,
|
|
916
|
+
childId,
|
|
917
|
+
transport: 'dsh-subagent',
|
|
918
|
+
startedAt: Date.now(),
|
|
919
|
+
abortController: ac,
|
|
920
|
+
})
|
|
921
|
+
}
|
|
922
|
+
recordDispatchState(childId, 'dsh-subagent')
|
|
923
|
+
|
|
924
|
+
if (activation && activation.result && typeof activation.result.then === 'function') {
|
|
925
|
+
Promise.resolve(activation.result)
|
|
926
|
+
.then((resVal) => {
|
|
927
|
+
if (ac.signal.aborted) return
|
|
928
|
+
const outText = (resVal && (resVal.text || resVal.output || resVal.summary))
|
|
929
|
+
|| (typeof resVal === 'string' ? resVal : '外部 Harness 任务已完成')
|
|
930
|
+
writeSettlementReceipt(childId, outText, true)
|
|
931
|
+
})
|
|
932
|
+
.catch((err) => {
|
|
933
|
+
if (ac.signal.aborted) return
|
|
934
|
+
writeSettlementReceipt(childId, (err && err.message) || err || '执行失败', false)
|
|
935
|
+
})
|
|
936
|
+
.finally(() => {
|
|
937
|
+
if (activeRuns) activeRuns.delete(runKey)
|
|
938
|
+
})
|
|
939
|
+
}
|
|
940
|
+
} else {
|
|
941
|
+
// Path B: Direct invocation of local Codex / Claude Code CLI via DSH host ctx.subprocess
|
|
942
|
+
usedTransport = 'local-cli'
|
|
943
|
+
const tmpOutFile = cleanProvider === 'codex'
|
|
944
|
+
? path.join(os.tmpdir(), `dsh-bubble-${cleanProvider}-${runKey}.txt`)
|
|
945
|
+
: ''
|
|
946
|
+
const cliArgs = cleanProvider === 'codex'
|
|
947
|
+
? ['exec', '--skip-git-repo-check', '--color', 'never', '-C', actionCwd, '-s', 'workspace-write', '-o', tmpOutFile, '-']
|
|
948
|
+
: ['-p', '--output-format', 'text', '--no-session-persistence']
|
|
949
|
+
const argv = resolveLocalCliArgv(localHit.binaryPath, cliArgs)
|
|
950
|
+
|
|
951
|
+
const envOverrides = buildExternalHarnessEnv(cleanProvider)
|
|
952
|
+
const handle = subprocessSvc.spawn({
|
|
953
|
+
argv,
|
|
954
|
+
cwd: actionCwd,
|
|
955
|
+
graceMs: 4000,
|
|
956
|
+
signal: ac.signal,
|
|
957
|
+
...(envOverrides ? { env: envOverrides } : {}),
|
|
958
|
+
stdio: {
|
|
959
|
+
stdin: { data: safePrompt },
|
|
960
|
+
stdout: 'pipe',
|
|
961
|
+
stderr: 'pipe',
|
|
962
|
+
},
|
|
963
|
+
})
|
|
964
|
+
|
|
965
|
+
const outChunks = []
|
|
966
|
+
const errChunks = []
|
|
967
|
+
const appendChunk = (arr, byteRefSet, chunk) => {
|
|
968
|
+
if (byteRefSet.n >= 65536) return
|
|
969
|
+
const s = Buffer.isBuffer(chunk) ? chunk.toString('utf8') : String(chunk || '')
|
|
970
|
+
arr.push(s)
|
|
971
|
+
byteRefSet.n += s.length
|
|
972
|
+
}
|
|
973
|
+
const outLen = { n: 0 }
|
|
974
|
+
const errLen = { n: 0 }
|
|
975
|
+
try { handle.stdout?.on?.('data', chunk => appendChunk(outChunks, outLen, chunk)) } catch {}
|
|
976
|
+
try { handle.stderr?.on?.('data', chunk => appendChunk(errChunks, errLen, chunk)) } catch {}
|
|
977
|
+
|
|
978
|
+
if (activeRuns) {
|
|
979
|
+
activeRuns.set(runKey, {
|
|
980
|
+
id: runKey,
|
|
981
|
+
rootId: rid,
|
|
982
|
+
provider: cleanProvider,
|
|
983
|
+
label: taskLabel,
|
|
984
|
+
childId,
|
|
985
|
+
transport: 'local-cli',
|
|
986
|
+
startedAt: Date.now(),
|
|
987
|
+
abortController: ac,
|
|
988
|
+
terminate: () => {
|
|
989
|
+
try { if (handle && typeof handle.terminate === 'function') handle.terminate() } catch {}
|
|
990
|
+
},
|
|
991
|
+
})
|
|
992
|
+
}
|
|
993
|
+
recordDispatchState(childId, 'local-cli')
|
|
994
|
+
|
|
995
|
+
const cleanTmpOut = () => {
|
|
996
|
+
if (!tmpOutFile) return
|
|
997
|
+
try { fs.rmSync(tmpOutFile, { force: true }) } catch {}
|
|
998
|
+
}
|
|
999
|
+
|
|
1000
|
+
if (handle && handle.done && typeof handle.done.then === 'function') {
|
|
1001
|
+
Promise.resolve(handle.done)
|
|
1002
|
+
.then((outcome) => {
|
|
1003
|
+
let outText = ''
|
|
1004
|
+
if (tmpOutFile) {
|
|
1005
|
+
try {
|
|
1006
|
+
if (fs.existsSync(tmpOutFile)) outText = fs.readFileSync(tmpOutFile, 'utf8').trim()
|
|
1007
|
+
} catch {}
|
|
1008
|
+
}
|
|
1009
|
+
if (!outText) outText = outChunks.join('').trim()
|
|
1010
|
+
const errTail = errChunks.join('').trim().slice(-400)
|
|
1011
|
+
const exitCode = outcome && typeof outcome.exitCode === 'number' ? outcome.exitCode : 0
|
|
1012
|
+
if (ac.signal.aborted) return
|
|
1013
|
+
if (exitCode !== 0) {
|
|
1014
|
+
const diagParts = [outText, errTail].filter(Boolean)
|
|
1015
|
+
const combinedDiag = diagParts.join(outText && errTail ? '\n' : '').trim()
|
|
1016
|
+
const failMsg = combinedDiag
|
|
1017
|
+
? `退出码 ${exitCode}:${clamp(combinedDiag, 1200)}`
|
|
1018
|
+
: `外部 CLI 进程以退出码 ${exitCode} 结束`
|
|
1019
|
+
writeSettlementReceipt(childId, failMsg, false)
|
|
1020
|
+
} else {
|
|
1021
|
+
writeSettlementReceipt(childId, outText || '本机 CLI 任务已执行完成', true)
|
|
1022
|
+
}
|
|
1023
|
+
})
|
|
1024
|
+
.catch((err) => {
|
|
1025
|
+
if (ac.signal.aborted) return
|
|
1026
|
+
writeSettlementReceipt(childId, (err && err.message) || err || 'CLI 调用失败', false)
|
|
1027
|
+
})
|
|
1028
|
+
.finally(() => {
|
|
1029
|
+
cleanTmpOut()
|
|
1030
|
+
if (activeRuns) activeRuns.delete(runKey)
|
|
1031
|
+
})
|
|
1032
|
+
} else {
|
|
1033
|
+
cleanTmpOut()
|
|
1034
|
+
}
|
|
1035
|
+
}
|
|
1036
|
+
|
|
1037
|
+
return {
|
|
1038
|
+
ok: true,
|
|
1039
|
+
runId: runKey,
|
|
1040
|
+
childId,
|
|
1041
|
+
provider: cleanProvider,
|
|
1042
|
+
label: displayLabel,
|
|
1043
|
+
transport: usedTransport,
|
|
1044
|
+
bubbleLocked: true,
|
|
1045
|
+
}
|
|
1046
|
+
}
|
|
1047
|
+
|