@sshirkit/dsh-orchestrator 0.9.1 → 1.0.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/README.md +153 -92
- package/README.zh.md +155 -94
- package/docs/images/dispatch-panel.png +0 -0
- package/docs/images/hero-banner.png +0 -0
- package/lib/api.js +1 -0
- package/lib/catalog.js +2 -1
- package/lib/client.js +212 -55
- package/lib/delegate-status.js +125 -0
- package/lib/delegate.js +299 -59
- package/lib/gate.js +57 -15
- package/lib/git-audit.js +383 -0
- package/lib/index.js +1185 -173
- package/lib/orchestrate.js +313 -89
- package/lib/reconcile.js +590 -0
- package/lib/retry.js +68 -5
- package/lib/rules.js +15 -2
- package/lib/state-store.js +455 -0
- package/lib/supervise.js +593 -87
- package/lib/timeline.js +464 -0
- package/lib/tool-surface.js +69 -21
- package/lib/worktree-manage.js +244 -0
- package/lib/worktree-tool.js +38 -0
- package/lib/worktree.js +687 -0
- package/lib/write-audit.js +333 -0
- package/lib/write-lease.js +161 -7
- package/lib/write-scope-tool.js +29 -0
- package/lib/write-scope.js +14 -18
- package/package.json +3 -3
package/lib/delegate.js
CHANGED
|
@@ -13,10 +13,19 @@
|
|
|
13
13
|
* there is only one text, and it is written for the planner.
|
|
14
14
|
*/
|
|
15
15
|
|
|
16
|
+
import { statSync } from 'node:fs'
|
|
17
|
+
import path from 'node:path'
|
|
16
18
|
import { DELEGATE_TOOL, DELIVERY, disabledToolMessage } from './api.js'
|
|
17
19
|
import { mainAgentRule } from './rules.js'
|
|
18
20
|
import { buildSpawnActivation, isDispatchEnabled, languageNote, readRoute, readRouteOverride } from './worker.js'
|
|
19
|
-
import {
|
|
21
|
+
import { auditBaseline, captureBaseline, formatAuditReport } from './write-audit.js'
|
|
22
|
+
import { auditGitBaseline, captureGitBaseline, formatGitAuditReport } from './git-audit.js'
|
|
23
|
+
import { validateWriteScopeInput } from './write-lease.js'
|
|
24
|
+
import { ROOT_CLAIM, SCOPE_KIND, normalizeScope } from './write-scope.js'
|
|
25
|
+
import {
|
|
26
|
+
ISOLATION_MODES, WriteScopeError, WRITE_SCOPE_TOOL_CODES, claimWriteScope, dispatchCwd,
|
|
27
|
+
formatWorktreeError, parseIsolation, releaseWriteScope, requireWriteScope, writeScopeFailure,
|
|
28
|
+
} from './write-scope-tool.js'
|
|
20
29
|
|
|
21
30
|
export { DELEGATE_TOOL, languageNote, readRoute, readRouteOverride }
|
|
22
31
|
|
|
@@ -28,11 +37,201 @@ export { DELEGATE_TOOL, languageNote, readRoute, readRouteOverride }
|
|
|
28
37
|
*/
|
|
29
38
|
export { WriteScopeError, WRITE_SCOPE_TOOL_CODES } from './write-scope-tool.js'
|
|
30
39
|
|
|
40
|
+
export const READ_ONLY_NOTICE = '本任务仅限只读,不得写入文件。不占写租约;宿主未提供逐子代理物理只读隔离,由插件做逻辑写后审计并告警。'
|
|
41
|
+
|
|
42
|
+
export function dispatchWriteParameters({ batch = false } = {}) {
|
|
43
|
+
return {
|
|
44
|
+
writeScope: {
|
|
45
|
+
type: 'array',
|
|
46
|
+
items: { type: 'string' },
|
|
47
|
+
description:
|
|
48
|
+
'非只读任务必填:允许写入的文件或目录(至少一项);readOnly: true 必须省略此项或传空数组。' +
|
|
49
|
+
(batch ? '共享模式下整批共享一个写租约;隔离模式下每条目独立租用。' : '') +
|
|
50
|
+
'冲突报 write-scope-conflict。相对路径基于 cwd,目录用 "/" 或 "/**";声明不扩大权限,也不阻止越界写入。',
|
|
51
|
+
},
|
|
52
|
+
readOnly: { type: 'boolean', default: false, description: `设为 true 时:${READ_ONLY_NOTICE}` },
|
|
53
|
+
isolation: {
|
|
54
|
+
type: 'string',
|
|
55
|
+
enum: [...ISOLATION_MODES],
|
|
56
|
+
description: 'auto(默认,受 worktreeIsolationEnabled 控制):Git 写任务自动使用独立 Worktree,非 Git 使用共享工作区与快照审计。' +
|
|
57
|
+
'worktree:强制隔离,非 Git、空仓或超出工作区边界时报错,不降级。shared:使用共享工作区。readOnly: true 不建树,不能组合 worktree。',
|
|
58
|
+
},
|
|
59
|
+
expectedFingerprints: {
|
|
60
|
+
type: 'object',
|
|
61
|
+
// The host's author dialect only accepts a boolean here; execute checks each value.
|
|
62
|
+
additionalProperties: true,
|
|
63
|
+
description: '可选:从工作区相对文件路径到预期旧 SHA-256(64 位十六进制)的映射,结算时与派发前的磁盘基线比对。',
|
|
64
|
+
},
|
|
65
|
+
expectedTargets: {
|
|
66
|
+
type: 'array',
|
|
67
|
+
items: { type: 'string' },
|
|
68
|
+
description: '可选:结算时预期仍存在的文件,使用基于 cwd 的相对路径。',
|
|
69
|
+
},
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
const invalidWrite = (message) => new WriteScopeError(WRITE_SCOPE_TOOL_CODES.invalid, message)
|
|
74
|
+
function isRelativeFile(value) {
|
|
75
|
+
if (typeof value !== 'string' || value.trim() === '' || value.includes('\0') ||
|
|
76
|
+
path.posix.isAbsolute(value) || path.win32.isAbsolute(value) || /^[A-Za-z]:/.test(value)) return false
|
|
77
|
+
const normalized = path.posix.normalize(value.replaceAll('\\', '/'))
|
|
78
|
+
return normalized !== '.' && normalized !== '..' && !normalized.startsWith('../') && !normalized.endsWith('/')
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
export function validateDispatchWrite(args, tool) {
|
|
82
|
+
const { writeScope, readOnly, expectedFingerprints, expectedTargets } = args ?? {}
|
|
83
|
+
if (readOnly !== undefined && typeof readOnly !== 'boolean') throw invalidWrite('readOnly 必须是布尔值。')
|
|
84
|
+
// Preserve the established tool-level error for a missing declaration.
|
|
85
|
+
if (readOnly !== true) requireWriteScope(args, tool)
|
|
86
|
+
const checked = validateWriteScopeInput({ writeScope, readOnly })
|
|
87
|
+
if (!checked.ok) throw writeScopeFailure(checked)
|
|
88
|
+
if (expectedFingerprints !== undefined) {
|
|
89
|
+
const prototype = expectedFingerprints == null ? undefined : Object.getPrototypeOf(expectedFingerprints)
|
|
90
|
+
if ((prototype !== Object.prototype && prototype !== null) ||
|
|
91
|
+
!Object.entries(expectedFingerprints).every(([filename, hash]) => isRelativeFile(filename) &&
|
|
92
|
+
typeof hash === 'string' && /^[0-9a-f]{64}$/i.test(hash))) {
|
|
93
|
+
throw invalidWrite('expectedFingerprints 必须是工作区相对文件路径到 64 位十六进制 SHA-256 的对象。')
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
if (expectedTargets !== undefined && (!Array.isArray(expectedTargets) || !expectedTargets.every(isRelativeFile))) {
|
|
97
|
+
throw invalidWrite('expectedTargets 必须是工作区相对文件路径数组。')
|
|
98
|
+
}
|
|
99
|
+
return checked
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
export function validateDispatchIsolation(args) {
|
|
103
|
+
const parsed = parseIsolation(args?.isolation)
|
|
104
|
+
if (!parsed.ok) throw new WriteScopeError(parsed.code, parsed.message)
|
|
105
|
+
if (args?.readOnly === true && parsed.explicit && parsed.mode === 'worktree') {
|
|
106
|
+
throw new WriteScopeError('isolation-invalid', '只读任务不支持强制独立 Worktree:请省略 isolation 或使用 auto/shared。')
|
|
107
|
+
}
|
|
108
|
+
return parsed
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
export const worktreeFailure = (result) => new WriteScopeError(result.code, formatWorktreeError(result.code, result))
|
|
112
|
+
|
|
113
|
+
export function dispatchWorkspaceRoot(exec, getWorkspaceRoot) {
|
|
114
|
+
const cwd = exec?.agent?.session?.header?.cwd
|
|
115
|
+
return typeof cwd === 'string' && cwd.trim() !== '' ? cwd : getWorkspaceRoot?.(exec) ?? null
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
export function worktreeDetails(worktree) {
|
|
119
|
+
return { id: worktree.id, branch: worktree.branch, path: worktree.worktreePath, execCwd: worktree.execCwd }
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
export function worktreePromptNote(worktree) {
|
|
123
|
+
return `你在独立 Worktree(分支 ${worktree.branch})中工作,仅修改声明的作用域;请勿自行合并主分支。\n主代理会用 worktree_manage 评审、合回或丢弃交付。`
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
export function discardEmptyWorktree(worktrees, worktree, onCleanupFailed) {
|
|
127
|
+
try {
|
|
128
|
+
const result = worktrees.discard(worktree.id, { force: true, lockChild: false })
|
|
129
|
+
if (!result.ok) onCleanupFailed?.(worktreeFailure(result))
|
|
130
|
+
} catch (error) {
|
|
131
|
+
onCleanupFailed?.(error)
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
export function captureDispatchBaseline({ cwd, writeScope, readOnly, expectedFingerprints, expectedTargets }) {
|
|
136
|
+
// Never turn an absent/foreign mock cwd into our process directory or audit a virtual one.
|
|
137
|
+
let noDirectory = typeof cwd !== 'string' || !path.isAbsolute(cwd)
|
|
138
|
+
if (!noDirectory) {
|
|
139
|
+
try {
|
|
140
|
+
noDirectory = !statSync(cwd, { throwIfNoEntry: false })?.isDirectory()
|
|
141
|
+
} catch (error) {
|
|
142
|
+
// Permission or I/O failures must be reported by the audit instead of passing silently.
|
|
143
|
+
noDirectory = error?.code === 'ENOTDIR'
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
if (noDirectory) {
|
|
147
|
+
if (Object.keys(expectedFingerprints ?? {}).length > 0 || (expectedTargets?.length ?? 0) > 0) {
|
|
148
|
+
throw invalidWrite('需要存在的工作目录才能验证 expectedFingerprints 或 expectedTargets。')
|
|
149
|
+
}
|
|
150
|
+
return undefined
|
|
151
|
+
}
|
|
152
|
+
try {
|
|
153
|
+
return captureBaseline({ cwd, writeScope, readOnly, expectedFingerprints, expectedTargets })
|
|
154
|
+
} catch (error) {
|
|
155
|
+
throw invalidWrite(error instanceof Error ? error.message : String(error))
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
function relocateWriteScope(entries, sourceCwd) {
|
|
160
|
+
const normalized = normalizeScope(entries, sourceCwd)
|
|
161
|
+
if (!normalized.ok) throw writeScopeFailure(normalized)
|
|
162
|
+
if (normalized.outsideWorkspace.length > 0) {
|
|
163
|
+
throw invalidWrite(`独立 Worktree 的写作用域必须在源 cwd 内:${normalized.outsideWorkspace.join('、')}。`)
|
|
164
|
+
}
|
|
165
|
+
return normalized.entries.map((entry) => {
|
|
166
|
+
if (entry.kind === SCOPE_KIND.root) return ROOT_CLAIM
|
|
167
|
+
const relative = path.relative(sourceCwd, entry.path) || '.'
|
|
168
|
+
return entry.kind === SCOPE_KIND.dir ? `${relative}/` : relative
|
|
169
|
+
})
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
export function prepareDispatchWrite({
|
|
173
|
+
args, exec, parent, leases, childId, tool, checked, worktree, captureGit = captureGitBaseline,
|
|
174
|
+
}) {
|
|
175
|
+
const sourceCwd = dispatchCwd(args, exec)
|
|
176
|
+
const cwd = worktree?.execCwd ?? sourceCwd
|
|
177
|
+
const readOnly = checked.readOnly
|
|
178
|
+
const writeScope = readOnly ? [] : worktree
|
|
179
|
+
? relocateWriteScope(checked.entries, sourceCwd)
|
|
180
|
+
: typeof args.writeScope === 'string' ? [args.writeScope] : [...args.writeScope]
|
|
181
|
+
const leaseArgs = worktree ? { ...args, cwd, writeScope } : args
|
|
182
|
+
const held = readOnly ? null : claimWriteScope({ args: leaseArgs, exec, parent, leases, childId, tool })
|
|
183
|
+
try {
|
|
184
|
+
const entries = held === null ? [] : leases.get?.(held.leaseId)?.entries ?? normalizeScope(writeScope, cwd).entries
|
|
185
|
+
const baseline = worktree
|
|
186
|
+
? captureGit({ ...args, worktree, cwd, repoRoot: worktree.repoRoot, writeScope, readOnly })
|
|
187
|
+
: captureDispatchBaseline({ ...args, cwd, writeScope, readOnly })
|
|
188
|
+
return { lease: held, entries, cwd, writeScope, readOnly, baseline, ...(worktree && { worktree }) }
|
|
189
|
+
} catch (error) {
|
|
190
|
+
releaseWriteScope(leases, held)
|
|
191
|
+
throw error
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
export function settleDispatchWrite(baseline, auditGit = auditGitBaseline) {
|
|
196
|
+
if (baseline === undefined) return undefined
|
|
197
|
+
const git = baseline.kind === 'git-worktree' || baseline.mode === 'git-worktree' || Boolean(baseline.worktree)
|
|
198
|
+
try {
|
|
199
|
+
return git ? auditGit(baseline) : auditBaseline(baseline)
|
|
200
|
+
} catch (error) {
|
|
201
|
+
return {
|
|
202
|
+
baselineId: baseline.baselineId,
|
|
203
|
+
passed: false,
|
|
204
|
+
readOnly: baseline.readOnly,
|
|
205
|
+
isolationLevel: git ? 'git-worktree' : 'logical-post-audit',
|
|
206
|
+
isolationNote: git ? 'Git 工作树审计失败,不能验收。' : '审计失败,不能据此确认写入合规;本模式不是物理隔离。',
|
|
207
|
+
changedFiles: [],
|
|
208
|
+
violations: [{ code: 'audit-incomplete', path: '.', reason: error instanceof Error ? error.message : String(error) }],
|
|
209
|
+
summary: { added: 0, modified: 0, deleted: 0, violations: 1, truncated: baseline.truncated },
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
export function worktreeAuditSummary(audit) {
|
|
215
|
+
return {
|
|
216
|
+
commits: audit.git?.commits?.length ?? 0,
|
|
217
|
+
dirty: (audit.git?.dirtyFiles?.length ?? 0) > 0,
|
|
218
|
+
auditPassed: audit.passed,
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
export function auditNotice(audit) {
|
|
223
|
+
if (audit?.passed !== false) return ''
|
|
224
|
+
return audit.git ? formatGitAuditReport(audit) : formatAuditReport(audit)
|
|
225
|
+
}
|
|
226
|
+
|
|
31
227
|
/** The delegate spec: the prompt carries the language note and delivery answers the parent. */
|
|
32
|
-
export function buildActivation({ args, parent, route, maxDepth, signal }) {
|
|
228
|
+
export function buildActivation({ args, parent, route, maxDepth, signal, baselineId, worktree }) {
|
|
33
229
|
return buildSpawnActivation({
|
|
34
|
-
cwd: args.cwd,
|
|
35
|
-
prompt: languageNote(args.prompt) + args.prompt
|
|
230
|
+
cwd: worktree?.execCwd ?? args.cwd,
|
|
231
|
+
prompt: languageNote(args.prompt) + args.prompt +
|
|
232
|
+
(args.readOnly === true ? `\n\n${READ_ONLY_NOTICE}` : '') +
|
|
233
|
+
(baselineId === undefined ? '' : `\n写后审计基线:${baselineId}。`) +
|
|
234
|
+
(worktree ? `\n\n${worktreePromptNote(worktree)}` : ''),
|
|
36
235
|
label: args.description,
|
|
37
236
|
parent,
|
|
38
237
|
route,
|
|
@@ -47,9 +246,16 @@ export function createDelegateTool({
|
|
|
47
246
|
subagents,
|
|
48
247
|
config,
|
|
49
248
|
onStarted,
|
|
249
|
+
nativeToolNote,
|
|
50
250
|
allowedTools,
|
|
51
251
|
deniedTools,
|
|
52
252
|
leases,
|
|
253
|
+
worktrees,
|
|
254
|
+
isWorktreeEnabled = () => true,
|
|
255
|
+
getWorkspaceRoot,
|
|
256
|
+
captureGitBaseline: captureGit,
|
|
257
|
+
onCleanupFailed,
|
|
258
|
+
persistence,
|
|
53
259
|
}) {
|
|
54
260
|
// `allowedTools` is the Allowed Tools whitelist the gate enforces: a function when the
|
|
55
261
|
// host owns the list, read again whenever the description is rendered, so a settings
|
|
@@ -61,11 +267,11 @@ export function createDelegateTool({
|
|
|
61
267
|
const enabled = () => isDispatchEnabled(config)
|
|
62
268
|
const rule = () => mainAgentRule(liveAllowed())
|
|
63
269
|
const body =
|
|
64
|
-
'把一个自包含任务交给子代理执行。子代理看不到本会话,prompt
|
|
65
|
-
'
|
|
66
|
-
'
|
|
270
|
+
'把一个自包含任务交给子代理执行。子代理看不到本会话,prompt 须写清目标、允许修改的文件、验收命令与兜底方案。非只读任务必填 writeScope;只读任务设 readOnly: true,不占租约,只做逻辑写后审计而非物理隔离。' +
|
|
271
|
+
'立即返回子代理 ID 及宿主提供的 agentName,二者均可填 send_message.agent。结束时自动通知,严禁要求子代理用 send_message 汇报。' +
|
|
272
|
+
'独立 Worktree 交付物须经 worktree_manage 评审、合回或丢弃。' +
|
|
67
273
|
'多个独立任务在同一轮并发发起;同构批量请用 orchestrate。'
|
|
68
|
-
const descriptionOf = () => (enabled() ? rule() + body : body)
|
|
274
|
+
const descriptionOf = () => (enabled() ? rule() + (nativeToolNote?.() ?? '') + body : body)
|
|
69
275
|
|
|
70
276
|
// A provisional id lets the lease be registered before the host names the child: the
|
|
71
277
|
// conflict has to be refused before `startActivation` (AC1). `rebind` moves the same
|
|
@@ -76,17 +282,6 @@ export function createDelegateTool({
|
|
|
76
282
|
return `pending:${String(parent?.id ?? 'parent')}:${String(pending)}`
|
|
77
283
|
}
|
|
78
284
|
|
|
79
|
-
/** Normalize and claim the declared scope. A missing declaration is refused here. */
|
|
80
|
-
const acquireLease = (args, exec, parent) =>
|
|
81
|
-
claimWriteScope({
|
|
82
|
-
args,
|
|
83
|
-
exec,
|
|
84
|
-
parent,
|
|
85
|
-
leases,
|
|
86
|
-
childId: nextPendingChildId(parent),
|
|
87
|
-
tool: 'delegate',
|
|
88
|
-
})
|
|
89
|
-
|
|
90
285
|
const tool = defineTool({
|
|
91
286
|
name: DELEGATE_TOOL,
|
|
92
287
|
description: descriptionOf(),
|
|
@@ -95,17 +290,7 @@ export function createDelegateTool({
|
|
|
95
290
|
type: 'string',
|
|
96
291
|
description: '初始工作目录(相对路径基于当前目录);省略则继承。',
|
|
97
292
|
},
|
|
98
|
-
|
|
99
|
-
type: 'array',
|
|
100
|
-
required: true,
|
|
101
|
-
items: { type: 'string' },
|
|
102
|
-
// Required, with no default and no minItems: omitting the field is refused with
|
|
103
|
-
// `write-scope-missing`, while an empty array is refused as `write-scope-invalid`.
|
|
104
|
-
description:
|
|
105
|
-
'必填:允许写入的文件/目录清单(至少一项)。' +
|
|
106
|
-
'派发前与在租作用域求交,冲突报 write-scope-conflict。' +
|
|
107
|
-
'相对路径基于 cwd;目录用 "/" 或 "/**";不推荐 "*"。仅声明,不扩大权限也不阻止越界写入。',
|
|
108
|
-
},
|
|
293
|
+
...dispatchWriteParameters(),
|
|
109
294
|
description: {
|
|
110
295
|
type: 'string',
|
|
111
296
|
required: true,
|
|
@@ -138,6 +323,17 @@ export function createDelegateTool({
|
|
|
138
323
|
properties: {
|
|
139
324
|
kind: { type: 'string', const: 'activation' },
|
|
140
325
|
subagentId: { type: 'string' },
|
|
326
|
+
agentName: { type: 'string' },
|
|
327
|
+
readOnly: { type: 'boolean' },
|
|
328
|
+
baselineId: { type: 'string' },
|
|
329
|
+
worktree: {
|
|
330
|
+
type: 'object',
|
|
331
|
+
additionalProperties: false,
|
|
332
|
+
properties: {
|
|
333
|
+
id: { type: 'string' }, branch: { type: 'string' }, path: { type: 'string' }, execCwd: { type: 'string' },
|
|
334
|
+
},
|
|
335
|
+
},
|
|
336
|
+
details: { type: 'object', additionalProperties: true },
|
|
141
337
|
writeScope: {
|
|
142
338
|
type: 'object',
|
|
143
339
|
additionalProperties: false,
|
|
@@ -148,7 +344,13 @@ export function createDelegateTool({
|
|
|
148
344
|
},
|
|
149
345
|
},
|
|
150
346
|
},
|
|
151
|
-
render: (_args, value) => [{
|
|
347
|
+
render: (_args, value) => [{
|
|
348
|
+
type: 'text',
|
|
349
|
+
text: `已启动子代理 ${value.subagentId}` +
|
|
350
|
+
(value.agentName ? `(send_message.agent: ${value.agentName})` : '') + (value.worktree
|
|
351
|
+
? `\n独立 Worktree ${value.worktree.id}(${value.worktree.branch}):${value.worktree.path};执行目录 ${value.worktree.execCwd}。完成后请用 worktree_manage 评审。`
|
|
352
|
+
: value.details?.isolationFallback ? `\n已降级为共享工作区:${value.details.isolationFallback.message}` : ''),
|
|
353
|
+
}],
|
|
152
354
|
},
|
|
153
355
|
// Workers are independent by contract, so several may be started in one message.
|
|
154
356
|
isConcurrencySafe: () => true,
|
|
@@ -156,36 +358,64 @@ export function createDelegateTool({
|
|
|
156
358
|
if (!enabled()) throw new Error(disabledToolMessage(DELEGATE_TOOL))
|
|
157
359
|
const parent = exec.agent
|
|
158
360
|
if (!parent) throw new Error('delegate requires a calling agent (exec.agent was undefined)')
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
requireWriteScope(args, DELEGATE_TOOL)
|
|
361
|
+
const isolation = validateDispatchIsolation(args)
|
|
362
|
+
const checked = validateDispatchWrite(args, DELEGATE_TOOL)
|
|
162
363
|
if (typeof args?.prompt !== 'string' || args.prompt.trim() === '') throw new Error('delegate requires a non-empty prompt')
|
|
163
364
|
if (typeof args?.description !== 'string' || args.description.trim() === '') throw new Error('delegate requires a non-empty description')
|
|
164
365
|
// An explicit per-call override wins and is never read from config; otherwise the
|
|
165
366
|
// route is read at call time, so a changed route applies from this delegation on.
|
|
166
367
|
const route = readRouteOverride(args, DELEGATE_TOOL) ?? readRoute(config)
|
|
167
368
|
exec.signal.throwIfAborted()
|
|
168
|
-
const
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
369
|
+
const maxDepth = subagents.resolveMaxDepth(undefined)
|
|
370
|
+
let worktree
|
|
371
|
+
let isolationFallback
|
|
372
|
+
const forced = isolation.mode === 'worktree'
|
|
373
|
+
if (!checked.readOnly && (forced || (isolation.mode === 'auto' && isWorktreeEnabled()))) {
|
|
374
|
+
if (!worktrees && forced) throw worktreeFailure({ code: 'worktree-create-failed', message: '工作树管理器不可用。' })
|
|
375
|
+
if (worktrees) {
|
|
376
|
+
const created = worktrees.create({
|
|
377
|
+
sourceCwd: dispatchCwd(args, exec), workspaceRoot: dispatchWorkspaceRoot(exec, getWorkspaceRoot),
|
|
378
|
+
label: args.description, parentId: parent.id ?? null,
|
|
379
|
+
})
|
|
380
|
+
if (created.ok) worktree = created.worktree
|
|
381
|
+
else if (forced) throw worktreeFailure(created)
|
|
382
|
+
else if (!['not-git-repo', 'unborn-head'].includes(created.code)) {
|
|
383
|
+
isolationFallback = { code: created.code, message: formatWorktreeError(created.code, created) }
|
|
384
|
+
}
|
|
385
|
+
}
|
|
386
|
+
}
|
|
387
|
+
let write
|
|
178
388
|
let handedOff = false
|
|
389
|
+
let childStarted = false
|
|
179
390
|
try {
|
|
391
|
+
// Claim the execution checkout and freeze the baseline before the host can run the child.
|
|
392
|
+
write = prepareDispatchWrite({
|
|
393
|
+
args, exec, parent, leases, childId: nextPendingChildId(parent), tool: DELEGATE_TOOL, checked,
|
|
394
|
+
worktree, captureGit,
|
|
395
|
+
})
|
|
396
|
+
const held = write.lease
|
|
397
|
+
const baselineId = write.baseline?.baselineId
|
|
398
|
+
const spec = buildActivation({ args, parent, route, maxDepth, signal: exec.signal, baselineId, worktree })
|
|
399
|
+
if (persistence) {
|
|
400
|
+
await persistence.beforeLaunch(write)
|
|
401
|
+
persistence.assertActive()
|
|
402
|
+
exec.signal.throwIfAborted()
|
|
403
|
+
}
|
|
180
404
|
const started = await subagents.startActivation(spec)
|
|
181
405
|
const childId = started?.childId
|
|
182
406
|
if (typeof childId !== 'string' || childId === '') {
|
|
183
407
|
throw new Error('delegate: startActivation returned no child id')
|
|
184
408
|
}
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
if (
|
|
409
|
+
childStarted = true
|
|
410
|
+
const agentName = typeof started.name === 'string' && started.name.trim() && started.name !== childId
|
|
411
|
+
? started.name : undefined
|
|
412
|
+
if (worktree) {
|
|
413
|
+
worktrees.rebindChild(worktree.id, childId)
|
|
414
|
+
worktrees.bindChild?.(worktree.id, childId)
|
|
415
|
+
}
|
|
416
|
+
let scope = held?.scope
|
|
417
|
+
// `rebind` attaches a writable dispatch to the real child, never a read-only one.
|
|
418
|
+
if (held !== null && typeof leases.rebind === 'function') {
|
|
189
419
|
const rebound = leases.rebind(held.leaseId, { childId })
|
|
190
420
|
if (!rebound.ok) {
|
|
191
421
|
throw new WriteScopeError(WRITE_SCOPE_TOOL_CODES.invalid, rebound.message)
|
|
@@ -197,23 +427,33 @@ export function createDelegateTool({
|
|
|
197
427
|
handedOff = true
|
|
198
428
|
// Supervision is best-effort: a missing or broken callback must neither fail the
|
|
199
429
|
// dispatch nor change what the main agent receives back.
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
430
|
+
if (persistence) {
|
|
431
|
+
await onStarted?.(parent, started, args, write, agentName)
|
|
432
|
+
} else {
|
|
433
|
+
try {
|
|
434
|
+
const notified = onStarted?.(parent, started, args, write, agentName)
|
|
435
|
+
notified?.catch?.(() => {})
|
|
436
|
+
} catch {
|
|
437
|
+
// Standalone supervision is best-effort; it does not own dispatch durability.
|
|
438
|
+
}
|
|
206
439
|
}
|
|
440
|
+
const isolated = worktree && worktreeDetails(worktree)
|
|
207
441
|
return {
|
|
208
442
|
kind: 'activation',
|
|
209
443
|
subagentId: childId,
|
|
210
|
-
|
|
444
|
+
...(agentName && { agentName }),
|
|
445
|
+
...(held === null ? { readOnly: true } : { writeScope: { leaseId: held.leaseId, scope: [...scope] } }),
|
|
446
|
+
...(baselineId === undefined ? {} : { baselineId }),
|
|
447
|
+
...(isolated ? { worktree: isolated, details: { worktree: isolated } } : {}),
|
|
448
|
+
...(isolationFallback ? { details: { isolationFallback } } : {}),
|
|
211
449
|
}
|
|
212
450
|
} finally {
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
451
|
+
if (!handedOff && !childStarted && !persistence?.isDisposing()) {
|
|
452
|
+
releaseWriteScope(leases, write?.lease)
|
|
453
|
+
if (worktree) discardEmptyWorktree(worktrees, worktree, onCleanupFailed)
|
|
454
|
+
if (persistence) await persistence.afterFailedLaunch({ ...write, worktree })
|
|
455
|
+
} else if (!handedOff && !persistence) {
|
|
456
|
+
releaseWriteScope(leases, write?.lease)
|
|
217
457
|
}
|
|
218
458
|
}
|
|
219
459
|
},
|
package/lib/gate.js
CHANGED
|
@@ -38,6 +38,18 @@ import { RUN_CODE_TOOL, runCodeRefusal } from './run-code-guard.js'
|
|
|
38
38
|
|
|
39
39
|
export { DELEGATE_TOOL }
|
|
40
40
|
|
|
41
|
+
/** Optional host task board. These names do not register tools or create a separate board. */
|
|
42
|
+
export const NATIVE_TEAM_TOOLS = Object.freeze([
|
|
43
|
+
'team_task_create',
|
|
44
|
+
'team_task_list',
|
|
45
|
+
'team_task_get',
|
|
46
|
+
'team_task_update',
|
|
47
|
+
])
|
|
48
|
+
|
|
49
|
+
/** ADR-0004: coexist with these host tools without adding them to the shipped whitelist. */
|
|
50
|
+
export const DEFAULT_BLOCKED_NATIVE_TOOLS = Object.freeze(['subagent_fork', 'workflow'])
|
|
51
|
+
const NATIVE_TEAM_TOOL_SET = new Set(NATIVE_TEAM_TOOLS)
|
|
52
|
+
|
|
41
53
|
export const SUPERVISION_TODO_DENIAL = '[dsh-orchestrator] 当前为定时巡检回合,已禁止调用 todo_write。子代理仍在运行,请勿推进主任务清单状态;如需纠偏请直接通过调研或 send_message / interrupt_agent 等方式处理,无需干预请仅回复「巡检:正常」。任务进度请在子代理交付结算(subagent-settled)或正常用户回合再更新。'
|
|
42
54
|
export const SUPERVISION_NORMAL_DENIAL = '[dsh-orchestrator] 本回合已输出「巡检:正常」确认无需干预,已锁定后续工具调用,请立即结束本回合,勿再调用任何工具。'
|
|
43
55
|
const SUPERVISION_WHITELIST_DENIAL = 'orchestrator: The requested tool is not in allowedTools for the current supervision turn. Use currently allowed tools to handle existing workers, or reply "巡检:正常" and end the turn.'
|
|
@@ -54,6 +66,7 @@ export function createSupervisionTurnState() {
|
|
|
54
66
|
if (isTurnActive(agentId, turn)) turns.get(agentId).normalDeclared = true
|
|
55
67
|
},
|
|
56
68
|
isTurnActive,
|
|
69
|
+
hasActiveParent: (agentId) => turns.has(agentId),
|
|
57
70
|
clearTurn(agentId, turn) {
|
|
58
71
|
if (isTurnActive(agentId, turn)) turns.delete(agentId)
|
|
59
72
|
},
|
|
@@ -139,6 +152,29 @@ export function effectiveAllowed(configured, defaults = []) {
|
|
|
139
152
|
return cleanNames(source)
|
|
140
153
|
}
|
|
141
154
|
|
|
155
|
+
/**
|
|
156
|
+
* Resolve the strict main-agent whitelist for ADR-0004. A configured whitelist still
|
|
157
|
+
* replaces the shipped defaults, `[]` included. Only an explicit list can opt in to a
|
|
158
|
+
* default-blocked native tool. `allowAgentTeam: false` takes precedence over either list.
|
|
159
|
+
* A known catalog may restrict default Team names to the tools the host actually offers.
|
|
160
|
+
*/
|
|
161
|
+
export function resolveEffectiveAllowedTools(
|
|
162
|
+
configured,
|
|
163
|
+
{ defaults = [], allowAgentTeam = true, availableTools } = {},
|
|
164
|
+
) {
|
|
165
|
+
if (typeof configured !== 'string' && typeof configured?.[Symbol.iterator] === 'function') {
|
|
166
|
+
const names = effectiveAllowed(configured)
|
|
167
|
+
return allowAgentTeam === false ? names.filter((name) => !NATIVE_TEAM_TOOL_SET.has(name)) : names
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
const available = availableTools === undefined ? undefined : new Set(availableTools)
|
|
171
|
+
const team = allowAgentTeam === false ? [] : NATIVE_TEAM_TOOLS.filter((name) => available?.has(name) ?? true)
|
|
172
|
+
const base = effectiveAllowed(undefined, defaults).filter(
|
|
173
|
+
(name) => !NATIVE_TEAM_TOOL_SET.has(name) && !DEFAULT_BLOCKED_NATIVE_TOOLS.includes(name),
|
|
174
|
+
)
|
|
175
|
+
return [...base, ...team]
|
|
176
|
+
}
|
|
177
|
+
|
|
142
178
|
/**
|
|
143
179
|
* The tools a whitelist leaves out: every catalog name that is neither allowed nor the
|
|
144
180
|
* reserved `run_code` transport. Kept as a pure helper (the panel and older callers use it);
|
|
@@ -161,8 +197,16 @@ export function hiddenTools(catalog, allowed) {
|
|
|
161
197
|
* The refusal for one tool outside the whitelist. One home for the text, so a name check
|
|
162
198
|
* and the `run_code` argument check can never drift into two slightly different messages.
|
|
163
199
|
*/
|
|
164
|
-
function refusalFor(tool) {
|
|
165
|
-
|
|
200
|
+
function refusalFor(tool, allowAgentTeam = true) {
|
|
201
|
+
const prefix = `orchestrator: "${tool}" is not available to the main agent.`
|
|
202
|
+
if (DEFAULT_BLOCKED_NATIVE_TOOLS.includes(tool)) {
|
|
203
|
+
const reason = tool === 'subagent_fork' ? '避免完整继承上下文导致提示词缓存失效' : '避免宿主与插件的双编排体系冲突'
|
|
204
|
+
return `${prefix} 按 ADR-0004 默认禁用,以${reason};请改用 delegate / orchestrate。`
|
|
205
|
+
}
|
|
206
|
+
if (allowAgentTeam === false && NATIVE_TEAM_TOOL_SET.has(tool)) {
|
|
207
|
+
return `${prefix} 当前配置已关闭原生 Team 共享任务板(allowAgentTeam: false)。`
|
|
208
|
+
}
|
|
209
|
+
return `${prefix} The main agent only plans; hand every action to a worker with the delegate or orchestrate tools.`
|
|
166
210
|
}
|
|
167
211
|
|
|
168
212
|
/**
|
|
@@ -174,29 +218,30 @@ function refusalFor(tool) {
|
|
|
174
218
|
* `run_code` gets the argument check instead, because the transport itself must stay
|
|
175
219
|
* callable while the arguments that would escape the gate are refused.
|
|
176
220
|
*/
|
|
177
|
-
export function allowGuard(allowed) {
|
|
178
|
-
const allowedSet = new Set(
|
|
221
|
+
export function allowGuard(allowed, options) {
|
|
222
|
+
const allowedSet = new Set(resolveEffectiveAllowedTools(allowed, options))
|
|
179
223
|
return (exec) => {
|
|
180
224
|
const tool = exec?.name
|
|
181
225
|
if (typeof tool !== 'string' || tool === '') return undefined
|
|
182
226
|
if (allowedSet.has(tool)) return undefined
|
|
183
227
|
if (tool === RUN_CODE_TOOL) return runCodeRefusal(exec?.arguments, true)
|
|
184
|
-
return refusalFor(tool)
|
|
228
|
+
return refusalFor(tool, options?.allowAgentTeam)
|
|
185
229
|
}
|
|
186
230
|
}
|
|
187
231
|
|
|
188
232
|
/**
|
|
189
233
|
* Install a switch-aware, whitelist-driven guard on one top-level agent.
|
|
190
234
|
*
|
|
191
|
-
* `allowed()` and `
|
|
192
|
-
*
|
|
235
|
+
* `allowed`, `enabled()` and `allowAgentTeam` are read live; `allowed` and `allowAgentTeam`
|
|
236
|
+
* accept a plain array and a boolean, respectively, or getters. Nothing is restricted: the model-facing half is the
|
|
193
237
|
* `tools.definitions()` wrapper in `lib/tool-surface.js`, and this guard is what refuses a
|
|
194
238
|
* call the model makes anyway — a hallucinated name, a scope-local tool such as `subagent`,
|
|
195
239
|
* or a `run_code` program that would reach the host. A guard failure is reported, not
|
|
196
240
|
* thrown: a broken gate must not break agent creation.
|
|
197
241
|
*/
|
|
198
|
-
export function installGate({ agent, allowed, enabled = () => true, checkSupervision }) {
|
|
199
|
-
const liveAllowed = typeof allowed === 'function' ? allowed : () => allowed
|
|
242
|
+
export function installGate({ agent, allowed, allowAgentTeam = true, enabled = () => true, checkSupervision }) {
|
|
243
|
+
const liveAllowed = typeof allowed === 'function' ? allowed : () => allowed
|
|
244
|
+
const liveAllowAgentTeam = typeof allowAgentTeam === 'function' ? allowAgentTeam : () => allowAgentTeam
|
|
200
245
|
let guardError
|
|
201
246
|
let guardDispose
|
|
202
247
|
try {
|
|
@@ -213,11 +258,8 @@ export function installGate({ agent, allowed, enabled = () => true, checkSupervi
|
|
|
213
258
|
}
|
|
214
259
|
return undefined
|
|
215
260
|
}
|
|
216
|
-
const
|
|
217
|
-
|
|
218
|
-
// `run_code` is the PTC transport: it stays callable unless the panel checks it, and
|
|
219
|
-
// the arguments that would escape the gate are refused instead.
|
|
220
|
-
const refusal = tool === RUN_CODE_TOOL ? runCodeRefusal(exec?.arguments, true) : refusalFor(tool)
|
|
261
|
+
const guard = allowGuard(liveAllowed(), { allowAgentTeam: liveAllowAgentTeam() })
|
|
262
|
+
const refusal = guard(exec)
|
|
221
263
|
if (refusal === undefined) return undefined
|
|
222
264
|
return checkSupervision?.(caller, tool, { whitelistMiss: true }) ?? refusal
|
|
223
265
|
})
|
|
@@ -225,7 +267,7 @@ export function installGate({ agent, allowed, enabled = () => true, checkSupervi
|
|
|
225
267
|
guardError = error instanceof Error ? error.message : String(error)
|
|
226
268
|
}
|
|
227
269
|
return {
|
|
228
|
-
allowed:
|
|
270
|
+
allowed: resolveEffectiveAllowedTools(liveAllowed(), { allowAgentTeam: liveAllowAgentTeam() }),
|
|
229
271
|
guardError,
|
|
230
272
|
/** Unregister the guard. A second call is a no-op. */
|
|
231
273
|
dispose: () => {
|