@sshirkit/dsh-orchestrator 1.0.2 → 1.0.3
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 +44 -23
- package/README.zh.md +42 -22
- package/lib/client.js +657 -384
- package/lib/delegate-status.js +42 -67
- package/lib/delegate.js +69 -127
- package/lib/gate.js +9 -3
- package/lib/index.js +500 -432
- package/lib/orchestrate.js +91 -109
- package/lib/read-index.js +186 -0
- package/lib/reconcile.js +2 -3
- package/lib/rules.js +11 -10
- package/lib/session-tools.js +194 -22
- package/lib/state-store.js +14 -9
- package/lib/supervise.js +69 -85
- package/lib/switch-notice.js +2 -2
- package/lib/timeline.js +23 -181
- package/lib/tool-surface.js +33 -7
- package/lib/worker.js +18 -7
- package/lib/worktree-manage.js +3 -10
- package/lib/worktree.js +3 -12
- package/lib/write-lease.js +57 -12
- package/package.json +1 -1
- package/lib/git-audit.js +0 -383
- package/lib/write-audit.js +0 -333
package/lib/delegate-status.js
CHANGED
|
@@ -1,5 +1,3 @@
|
|
|
1
|
-
import { formatInlineAuditNotice } from './timeline.js'
|
|
2
|
-
|
|
3
1
|
export const DEFAULT_DELEGATE_STATUS_TOOL_NAME = 'delegate_status'
|
|
4
2
|
|
|
5
3
|
const DEFAULT_LIMIT = 20
|
|
@@ -7,45 +5,35 @@ const MAX_LIMIT = 64
|
|
|
7
5
|
|
|
8
6
|
function renderStatus({ total, counts, items }) {
|
|
9
7
|
const lines = [
|
|
10
|
-
|
|
11
|
-
`运行中 ${counts.running}
|
|
12
|
-
`审计失败 ${counts.auditFailed};未纳入审计 ${counts.auditUnmanaged}。`,
|
|
13
|
-
`工作树待评审 ${counts.worktreePendingReview}。`,
|
|
8
|
+
`委派状态:共 ${total} 条,本次显示 ${items.length} 条。`,
|
|
9
|
+
`运行中 ${counts.running},已结束 ${counts.ended},工作树待评审 ${counts.worktreePendingReview}。`,
|
|
14
10
|
]
|
|
15
|
-
if (items.length === 0)
|
|
16
|
-
|
|
17
|
-
}
|
|
18
|
-
for (const entry of items) {
|
|
19
|
-
const { childId, agentName, label, dispatchState, auditState, leaseState, baselineId, worktree } = entry
|
|
20
|
-
const delivery = worktree ? ` [wt:${worktree.id} ${worktree.state}]` : ''
|
|
11
|
+
if (items.length === 0) lines.push('当前会话没有符合条件的委派记录。')
|
|
12
|
+
for (const { childId, agentName, label, dispatchState, leaseState, worktree, pendingNextTurn } of items) {
|
|
21
13
|
const address = agentName ? `(${agentName})` : ''
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
lines.push(formatInlineAuditNotice([{ childId, entry }]))
|
|
26
|
-
}
|
|
14
|
+
const delivery = worktree ? ` [wt:${worktree.id} ${worktree.state}]` : ''
|
|
15
|
+
lines.push(`【${childId}】${address}${label ?? '未命名任务'}:执行 ${dispatchState},租约 ${leaseState}。` +
|
|
16
|
+
delivery + (pendingNextTurn ? ' 下一轮配置待应用。' : ''))
|
|
27
17
|
}
|
|
28
18
|
return [{ type: 'text', text: lines.join('\n') }]
|
|
29
19
|
}
|
|
30
20
|
|
|
31
|
-
function summarizeWorktree(worktree) {
|
|
32
|
-
if (worktree == null) return null
|
|
33
|
-
const { id, branch, state, commits, dirty, locked, path } = worktree
|
|
34
|
-
return { id, branch, state, commits, dirty, locked, path }
|
|
35
|
-
}
|
|
36
|
-
|
|
37
21
|
export function createDelegateStatusTool({
|
|
38
|
-
timeline,
|
|
39
|
-
toolName = DEFAULT_DELEGATE_STATUS_TOOL_NAME,
|
|
40
|
-
isRootAgent,
|
|
22
|
+
timeline, editNextTurn, toolName = DEFAULT_DELEGATE_STATUS_TOOL_NAME, isRootAgent,
|
|
41
23
|
defineTool = (definition) => definition,
|
|
42
24
|
} = {}) {
|
|
43
25
|
return defineTool({
|
|
44
26
|
name: toolName,
|
|
45
|
-
description: '
|
|
27
|
+
description: '查询本根会话直接委派的子代理、写租约和工作树状态。用 edit 更新闲置子代理的下一轮配置,再用 send_message 续跑。',
|
|
46
28
|
parameters: {
|
|
47
|
-
|
|
48
|
-
|
|
29
|
+
action: { type: 'string', enum: ['query', 'edit'], description: '默认 query,edit 保存下一轮配置。' },
|
|
30
|
+
childId: { type: 'string', description: 'query 可选;edit 必须指定子代理 ID。' },
|
|
31
|
+
writeScope: {
|
|
32
|
+
type: 'array', items: { type: 'string' },
|
|
33
|
+
description: 'edit 时替换写路径,基于子代理执行目录。切换为只读时省略或传空数组。',
|
|
34
|
+
},
|
|
35
|
+
readOnly: { type: 'boolean', description: 'edit 时设置下一轮是否只读,省略则沿用已有设置。' },
|
|
36
|
+
includeCompleted: { type: 'boolean', default: true, description: 'query 是否包含执行已结束的子代理。' },
|
|
49
37
|
limit: {
|
|
50
38
|
type: 'integer',
|
|
51
39
|
// The host author schema supports enum, not minimum/maximum.
|
|
@@ -56,70 +44,57 @@ export function createDelegateStatusTool({
|
|
|
56
44
|
},
|
|
57
45
|
output: {
|
|
58
46
|
schema: {
|
|
59
|
-
type: 'object',
|
|
60
|
-
additionalProperties: false,
|
|
47
|
+
type: 'object', additionalProperties: false,
|
|
61
48
|
properties: {
|
|
62
49
|
content: {
|
|
63
|
-
type: 'array',
|
|
64
|
-
|
|
65
|
-
type: 'object',
|
|
66
|
-
additionalProperties: false,
|
|
50
|
+
type: 'array', items: {
|
|
51
|
+
type: 'object', additionalProperties: false,
|
|
67
52
|
properties: { type: { type: 'string', const: 'text' }, text: { type: 'string' } },
|
|
68
53
|
},
|
|
69
54
|
},
|
|
70
|
-
details: {
|
|
71
|
-
type: 'object',
|
|
72
|
-
additionalProperties: false,
|
|
73
|
-
properties: {
|
|
74
|
-
parentId: { type: 'string' },
|
|
75
|
-
total: { type: 'integer' },
|
|
76
|
-
counts: {
|
|
77
|
-
type: 'object',
|
|
78
|
-
additionalProperties: false,
|
|
79
|
-
properties: {
|
|
80
|
-
running: { type: 'integer' },
|
|
81
|
-
endedPendingAudit: { type: 'integer' },
|
|
82
|
-
auditPassed: { type: 'integer' },
|
|
83
|
-
auditFailed: { type: 'integer' },
|
|
84
|
-
auditUnmanaged: { type: 'integer' },
|
|
85
|
-
worktreePendingReview: { type: 'integer' },
|
|
86
|
-
},
|
|
87
|
-
},
|
|
88
|
-
items: { type: 'array', items: { type: 'object', additionalProperties: true } },
|
|
89
|
-
},
|
|
90
|
-
},
|
|
55
|
+
details: { type: 'object', additionalProperties: true },
|
|
91
56
|
},
|
|
92
57
|
},
|
|
93
58
|
render: (_args, value) => value.content,
|
|
94
59
|
},
|
|
95
|
-
isConcurrencySafe: () =>
|
|
60
|
+
isConcurrencySafe: () => false,
|
|
96
61
|
async execute(args, exec) {
|
|
97
62
|
const parent = exec?.agent
|
|
98
|
-
//
|
|
63
|
+
// Never authorize against a caller-supplied parent id.
|
|
99
64
|
const parentId = parent?.id
|
|
100
65
|
if (typeof parentId !== 'string' || parentId.trim() === '') {
|
|
101
|
-
throw new Error(`${toolName} 无法识别调用代理的会话 ID
|
|
66
|
+
throw new Error(`${toolName} 无法识别调用代理的会话 ID,拒绝操作。`)
|
|
102
67
|
}
|
|
103
68
|
if (isRootAgent !== undefined && (typeof isRootAgent !== 'function' || !isRootAgent(parent))) {
|
|
104
|
-
throw new Error(`${toolName}
|
|
69
|
+
throw new Error(`${toolName} 仅限根代理调用。`)
|
|
105
70
|
}
|
|
106
71
|
if (Object.hasOwn(args ?? {}, 'parentId')) {
|
|
107
|
-
throw new Error(`${toolName} 不接受 parentId
|
|
72
|
+
throw new Error(`${toolName} 不接受 parentId 参数,只能操作调用方自己的委派记录。`)
|
|
108
73
|
}
|
|
109
|
-
const { childId, includeCompleted = true, limit = DEFAULT_LIMIT } = args ?? {}
|
|
74
|
+
const { action = 'query', childId, includeCompleted = true, limit = DEFAULT_LIMIT, writeScope, readOnly } = args ?? {}
|
|
110
75
|
if (childId !== undefined && (typeof childId !== 'string' || childId.trim() === '')) {
|
|
111
76
|
throw new Error('childId 必须是非空字符串。')
|
|
112
77
|
}
|
|
78
|
+
if (action === 'edit') {
|
|
79
|
+
if (!childId) throw new Error('edit 必须指定 childId。')
|
|
80
|
+
if (readOnly === undefined && writeScope === undefined) throw new Error('edit 至少需要提供 writeScope 或 readOnly。')
|
|
81
|
+
if (readOnly !== undefined && typeof readOnly !== 'boolean') throw new Error('readOnly 必须是布尔值。')
|
|
82
|
+
if (writeScope !== undefined && !Array.isArray(writeScope)) throw new Error('writeScope 必须是路径数组。')
|
|
83
|
+
if (!editNextTurn) throw new Error('当前环境不支持编辑委派配置。')
|
|
84
|
+
const details = await editNextTurn(parent, childId.trim(), { writeScope, readOnly }, exec.signal)
|
|
85
|
+
return {
|
|
86
|
+
content: [{ type: 'text', text: `已保存 ${childId} 的下一轮配置。请用 send_message 唤醒同一子代理。` }],
|
|
87
|
+
details: { action, ...details },
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
if (action !== 'query') throw new Error('action 必须是 query 或 edit。')
|
|
91
|
+
if (readOnly !== undefined || writeScope !== undefined) throw new Error('修改参数仅用于 edit。')
|
|
113
92
|
if (typeof includeCompleted !== 'boolean') throw new Error('includeCompleted 必须是布尔值。')
|
|
114
93
|
if (!Number.isInteger(limit) || limit < 1 || limit > MAX_LIMIT) {
|
|
115
94
|
throw new Error(`limit 必须是 1..${MAX_LIMIT} 之间的整数。`)
|
|
116
95
|
}
|
|
117
96
|
const report = timeline.queryParent(parentId, { childId, includeCompleted, limit })
|
|
118
|
-
|
|
119
|
-
...report,
|
|
120
|
-
items: report.items.map((entry) => ({ ...entry, worktree: summarizeWorktree(entry.worktree) })),
|
|
121
|
-
}
|
|
122
|
-
return { content: renderStatus(report), details }
|
|
97
|
+
return { content: renderStatus(report), details: report }
|
|
123
98
|
},
|
|
124
99
|
})
|
|
125
100
|
}
|
package/lib/delegate.js
CHANGED
|
@@ -13,13 +13,10 @@
|
|
|
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
16
|
import path from 'node:path'
|
|
18
17
|
import { DELEGATE_TOOL, DELIVERY, disabledToolMessage } from './api.js'
|
|
19
18
|
import { mainAgentRule, teamTaskPromptNote } from './rules.js'
|
|
20
|
-
import { buildSpawnActivation, isDispatchEnabled, languageNote, readRoute, readRouteOverride } from './worker.js'
|
|
21
|
-
import { auditBaseline, captureBaseline, formatAuditReport } from './write-audit.js'
|
|
22
|
-
import { auditGitBaseline, captureGitBaseline, formatGitAuditReport } from './git-audit.js'
|
|
19
|
+
import { buildSpawnActivation, configValue, isDispatchEnabled, languageNote, readRoute, readRouteOverride } from './worker.js'
|
|
23
20
|
import { validateWriteScopeInput } from './write-lease.js'
|
|
24
21
|
import { ROOT_CLAIM, SCOPE_KIND, normalizeScope } from './write-scope.js'
|
|
25
22
|
import {
|
|
@@ -37,7 +34,26 @@ export { DELEGATE_TOOL, languageNote, readRoute, readRouteOverride }
|
|
|
37
34
|
*/
|
|
38
35
|
export { WriteScopeError, WRITE_SCOPE_TOOL_CODES } from './write-scope-tool.js'
|
|
39
36
|
|
|
40
|
-
export const READ_ONLY_NOTICE = '
|
|
37
|
+
export const READ_ONLY_NOTICE = '本任务仅限只读,不得写入文件。不占写租约;宿主未提供逐子代理物理只读隔离。'
|
|
38
|
+
|
|
39
|
+
function parseAllowNewReason(value) {
|
|
40
|
+
if (value === undefined) return undefined
|
|
41
|
+
if (typeof value !== 'string' || value.trim() === '') {
|
|
42
|
+
throw Object.assign(new Error('allowNewReason 必须是非空字符串。'), { code: 'delegate-invalid-new-reason' })
|
|
43
|
+
}
|
|
44
|
+
return value.trim()
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
function requireReuse(candidates) {
|
|
48
|
+
if (candidates.length === 0) return
|
|
49
|
+
const { childId, agentName } = candidates[0]
|
|
50
|
+
throw Object.assign(new Error(
|
|
51
|
+
`[delegate-reuse-required] 当前会话有闲置可续跑的子代理:${candidates.map((row) => row.agentName).join('、')}。` +
|
|
52
|
+
`请用 send_message({ agent: ${JSON.stringify(agentName)}, message: '...' }) 复用。` +
|
|
53
|
+
`需改范围或只读模式时,先调用 delegate_status({ action: 'edit', childId: ${JSON.stringify(childId)}, ... }),再用 send_message。` +
|
|
54
|
+
'确实无法复用时才传入非空 allowNewReason 说明原因后新建。',
|
|
55
|
+
), { code: 'delegate-reuse-required', details: { candidates } })
|
|
56
|
+
}
|
|
41
57
|
|
|
42
58
|
export const TEAM_TASK_ID_PARAMETER = Object.freeze({
|
|
43
59
|
type: 'string',
|
|
@@ -52,63 +68,44 @@ export function parseTeamTaskId(value, tool) {
|
|
|
52
68
|
return value.trim()
|
|
53
69
|
}
|
|
54
70
|
|
|
55
|
-
export function dispatchWriteParameters({ batch = false } = {}) {
|
|
71
|
+
export function dispatchWriteParameters({ batch = false, readOnlyEnabled = true } = {}) {
|
|
56
72
|
return {
|
|
57
73
|
writeScope: {
|
|
58
74
|
type: 'array',
|
|
59
75
|
items: { type: 'string' },
|
|
60
76
|
description:
|
|
61
|
-
'非只读任务必填:允许写入的文件或目录(至少一项);readOnly: true 必须省略此项或传空数组。'
|
|
77
|
+
(readOnlyEnabled ? '非只读任务必填:允许写入的文件或目录(至少一项);readOnly: true 必须省略此项或传空数组。'
|
|
78
|
+
: '必填:声明作用域(至少一项);只读调研请同时使用 shared 并明确禁止修改文件。') +
|
|
62
79
|
(batch ? '共享模式下整批共享一个写租约;隔离模式下每条目独立租用。' : '') +
|
|
63
80
|
'冲突报 write-scope-conflict。相对路径基于 cwd,目录用 "/" 或 "/**";声明不扩大权限,也不阻止越界写入。',
|
|
64
81
|
},
|
|
65
|
-
readOnly: { type: 'boolean', default: false, description: `设为 true 时:${READ_ONLY_NOTICE}` },
|
|
82
|
+
...(readOnlyEnabled && { readOnly: { type: 'boolean', default: false, description: `设为 true 时:${READ_ONLY_NOTICE}` } }),
|
|
66
83
|
isolation: {
|
|
67
84
|
type: 'string',
|
|
68
85
|
enum: [...ISOLATION_MODES],
|
|
69
|
-
description: 'auto(默认,受 worktreeIsolationEnabled 控制):Git 写任务自动使用独立 Worktree,非 Git
|
|
70
|
-
'worktree:强制隔离,非 Git、空仓或超出工作区边界时报错,不降级。shared:使用共享工作区。
|
|
71
|
-
|
|
72
|
-
expectedFingerprints: {
|
|
73
|
-
type: 'object',
|
|
74
|
-
// The host's author dialect only accepts a boolean here; execute checks each value.
|
|
75
|
-
additionalProperties: true,
|
|
76
|
-
description: '可选:从工作区相对文件路径到预期旧 SHA-256(64 位十六进制)的映射,结算时与派发前的磁盘基线比对。',
|
|
77
|
-
},
|
|
78
|
-
expectedTargets: {
|
|
79
|
-
type: 'array',
|
|
80
|
-
items: { type: 'string' },
|
|
81
|
-
description: '可选:结算时预期仍存在的文件,使用基于 cwd 的相对路径。',
|
|
86
|
+
description: 'auto(默认,受 worktreeIsolationEnabled 控制):Git 写任务自动使用独立 Worktree,非 Git 使用共享工作区。' +
|
|
87
|
+
'worktree:强制隔离,非 Git、空仓或超出工作区边界时报错,不降级。shared:使用共享工作区。' +
|
|
88
|
+
(readOnlyEnabled ? 'readOnly: true 不建树,不能组合 worktree。' : ''),
|
|
82
89
|
},
|
|
83
90
|
}
|
|
84
91
|
}
|
|
85
92
|
|
|
93
|
+
export const READ_ONLY_DISABLED = 'readOnly 参数当前未启用,请移除此参数。只读调研请使用 isolation: "shared",并在任务中明确禁止修改文件。'
|
|
94
|
+
|
|
86
95
|
const invalidWrite = (message) => new WriteScopeError(WRITE_SCOPE_TOOL_CODES.invalid, message)
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
const normalized = path.posix.normalize(value.replaceAll('\\', '/'))
|
|
91
|
-
return normalized !== '.' && normalized !== '..' && !normalized.startsWith('../') && !normalized.endsWith('/')
|
|
96
|
+
|
|
97
|
+
export function assertReadOnlyArgumentEnabled(args, enabled) {
|
|
98
|
+
if (!enabled && args != null && Object.hasOwn(args, 'readOnly')) throw invalidWrite(READ_ONLY_DISABLED)
|
|
92
99
|
}
|
|
93
100
|
|
|
94
|
-
export function validateDispatchWrite(args, tool) {
|
|
95
|
-
|
|
101
|
+
export function validateDispatchWrite(args, tool, readOnlyEnabled = true) {
|
|
102
|
+
assertReadOnlyArgumentEnabled(args, readOnlyEnabled)
|
|
103
|
+
const { writeScope, readOnly } = args ?? {}
|
|
96
104
|
if (readOnly !== undefined && typeof readOnly !== 'boolean') throw invalidWrite('readOnly 必须是布尔值。')
|
|
97
105
|
// Preserve the established tool-level error for a missing declaration.
|
|
98
106
|
if (readOnly !== true) requireWriteScope(args, tool)
|
|
99
107
|
const checked = validateWriteScopeInput({ writeScope, readOnly })
|
|
100
108
|
if (!checked.ok) throw writeScopeFailure(checked)
|
|
101
|
-
if (expectedFingerprints !== undefined) {
|
|
102
|
-
const prototype = expectedFingerprints == null ? undefined : Object.getPrototypeOf(expectedFingerprints)
|
|
103
|
-
if ((prototype !== Object.prototype && prototype !== null) ||
|
|
104
|
-
!Object.entries(expectedFingerprints).every(([filename, hash]) => isRelativeFile(filename) &&
|
|
105
|
-
typeof hash === 'string' && /^[0-9a-f]{64}$/i.test(hash))) {
|
|
106
|
-
throw invalidWrite('expectedFingerprints 必须是工作区相对文件路径到 64 位十六进制 SHA-256 的对象。')
|
|
107
|
-
}
|
|
108
|
-
}
|
|
109
|
-
if (expectedTargets !== undefined && (!Array.isArray(expectedTargets) || !expectedTargets.every(isRelativeFile))) {
|
|
110
|
-
throw invalidWrite('expectedTargets 必须是工作区相对文件路径数组。')
|
|
111
|
-
}
|
|
112
109
|
return checked
|
|
113
110
|
}
|
|
114
111
|
|
|
@@ -145,30 +142,6 @@ export function discardEmptyWorktree(worktrees, worktree, onCleanupFailed) {
|
|
|
145
142
|
}
|
|
146
143
|
}
|
|
147
144
|
|
|
148
|
-
export function captureDispatchBaseline({ cwd, writeScope, readOnly, expectedFingerprints, expectedTargets }) {
|
|
149
|
-
// Never turn an absent/foreign mock cwd into our process directory or audit a virtual one.
|
|
150
|
-
let noDirectory = typeof cwd !== 'string' || !path.isAbsolute(cwd)
|
|
151
|
-
if (!noDirectory) {
|
|
152
|
-
try {
|
|
153
|
-
noDirectory = !statSync(cwd, { throwIfNoEntry: false })?.isDirectory()
|
|
154
|
-
} catch (error) {
|
|
155
|
-
// Permission or I/O failures must be reported by the audit instead of passing silently.
|
|
156
|
-
noDirectory = error?.code === 'ENOTDIR'
|
|
157
|
-
}
|
|
158
|
-
}
|
|
159
|
-
if (noDirectory) {
|
|
160
|
-
if (Object.keys(expectedFingerprints ?? {}).length > 0 || (expectedTargets?.length ?? 0) > 0) {
|
|
161
|
-
throw invalidWrite('需要存在的工作目录才能验证 expectedFingerprints 或 expectedTargets。')
|
|
162
|
-
}
|
|
163
|
-
return undefined
|
|
164
|
-
}
|
|
165
|
-
try {
|
|
166
|
-
return captureBaseline({ cwd, writeScope, readOnly, expectedFingerprints, expectedTargets })
|
|
167
|
-
} catch (error) {
|
|
168
|
-
throw invalidWrite(error instanceof Error ? error.message : String(error))
|
|
169
|
-
}
|
|
170
|
-
}
|
|
171
|
-
|
|
172
145
|
function relocateWriteScope(entries, sourceCwd) {
|
|
173
146
|
const normalized = normalizeScope(entries, sourceCwd)
|
|
174
147
|
if (!normalized.ok) throw writeScopeFailure(normalized)
|
|
@@ -183,7 +156,7 @@ function relocateWriteScope(entries, sourceCwd) {
|
|
|
183
156
|
}
|
|
184
157
|
|
|
185
158
|
export function prepareDispatchWrite({
|
|
186
|
-
args, exec, parent, leases, childId, tool, checked, worktree,
|
|
159
|
+
args, exec, parent, leases, childId, tool, checked, worktree,
|
|
187
160
|
}) {
|
|
188
161
|
const sourceCwd = dispatchCwd(args, exec)
|
|
189
162
|
const cwd = worktree?.execCwd ?? sourceCwd
|
|
@@ -193,57 +166,16 @@ export function prepareDispatchWrite({
|
|
|
193
166
|
: typeof args.writeScope === 'string' ? [args.writeScope] : [...args.writeScope]
|
|
194
167
|
const leaseArgs = worktree ? { ...args, cwd, writeScope } : args
|
|
195
168
|
const held = readOnly ? null : claimWriteScope({ args: leaseArgs, exec, parent, leases, childId, tool })
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
const baseline = worktree
|
|
199
|
-
? captureGit({ ...args, worktree, cwd, repoRoot: worktree.repoRoot, writeScope, readOnly })
|
|
200
|
-
: captureDispatchBaseline({ ...args, cwd, writeScope, readOnly })
|
|
201
|
-
return { lease: held, entries, cwd, writeScope, readOnly, baseline, ...(worktree && { worktree }) }
|
|
202
|
-
} catch (error) {
|
|
203
|
-
releaseWriteScope(leases, held)
|
|
204
|
-
throw error
|
|
205
|
-
}
|
|
206
|
-
}
|
|
207
|
-
|
|
208
|
-
export function settleDispatchWrite(baseline, auditGit = auditGitBaseline) {
|
|
209
|
-
if (baseline === undefined) return undefined
|
|
210
|
-
const git = baseline.kind === 'git-worktree' || baseline.mode === 'git-worktree' || Boolean(baseline.worktree)
|
|
211
|
-
try {
|
|
212
|
-
return git ? auditGit(baseline) : auditBaseline(baseline)
|
|
213
|
-
} catch (error) {
|
|
214
|
-
return {
|
|
215
|
-
baselineId: baseline.baselineId,
|
|
216
|
-
passed: false,
|
|
217
|
-
readOnly: baseline.readOnly,
|
|
218
|
-
isolationLevel: git ? 'git-worktree' : 'logical-post-audit',
|
|
219
|
-
isolationNote: git ? 'Git 工作树审计失败,不能验收。' : '审计失败,不能据此确认写入合规;本模式不是物理隔离。',
|
|
220
|
-
changedFiles: [],
|
|
221
|
-
violations: [{ code: 'audit-incomplete', path: '.', reason: error instanceof Error ? error.message : String(error) }],
|
|
222
|
-
summary: { added: 0, modified: 0, deleted: 0, violations: 1, truncated: baseline.truncated },
|
|
223
|
-
}
|
|
224
|
-
}
|
|
225
|
-
}
|
|
226
|
-
|
|
227
|
-
export function worktreeAuditSummary(audit) {
|
|
228
|
-
return {
|
|
229
|
-
commits: audit.git?.commits?.length ?? 0,
|
|
230
|
-
dirty: (audit.git?.dirtyFiles?.length ?? 0) > 0,
|
|
231
|
-
auditPassed: audit.passed,
|
|
232
|
-
}
|
|
233
|
-
}
|
|
234
|
-
|
|
235
|
-
export function auditNotice(audit) {
|
|
236
|
-
if (audit?.passed !== false) return ''
|
|
237
|
-
return audit.git ? formatGitAuditReport(audit) : formatAuditReport(audit)
|
|
169
|
+
const entries = held === null ? [] : leases.get?.(held.leaseId)?.entries ?? normalizeScope(writeScope, cwd).entries
|
|
170
|
+
return { lease: held, entries, cwd, writeScope, readOnly, ...(worktree && { worktree }) }
|
|
238
171
|
}
|
|
239
172
|
|
|
240
173
|
/** The delegate spec: the prompt carries the language note and delivery answers the parent. */
|
|
241
|
-
export function buildActivation({ args, parent, route, maxDepth, signal,
|
|
174
|
+
export function buildActivation({ args, parent, route, maxDepth, signal, worktree, teamTaskId }) {
|
|
242
175
|
return buildSpawnActivation({
|
|
243
176
|
cwd: worktree?.execCwd ?? args.cwd,
|
|
244
177
|
prompt: languageNote(args.prompt) + args.prompt +
|
|
245
178
|
(args.readOnly === true ? `\n\n${READ_ONLY_NOTICE}` : '') +
|
|
246
|
-
(baselineId === undefined ? '' : `\n写后审计基线:${baselineId}。`) +
|
|
247
179
|
(worktree ? `\n\n${worktreePromptNote(worktree)}` : '') +
|
|
248
180
|
(teamTaskId === undefined ? '' : `\n\n${teamTaskPromptNote(teamTaskId)}`),
|
|
249
181
|
label: args.description,
|
|
@@ -266,8 +198,9 @@ export function createDelegateTool({
|
|
|
266
198
|
leases,
|
|
267
199
|
worktrees,
|
|
268
200
|
isWorktreeEnabled = () => true,
|
|
201
|
+
resolveSessionConfig,
|
|
269
202
|
getWorkspaceRoot,
|
|
270
|
-
|
|
203
|
+
listReusableChildren,
|
|
271
204
|
onCleanupFailed,
|
|
272
205
|
persistence,
|
|
273
206
|
}) {
|
|
@@ -275,16 +208,21 @@ export function createDelegateTool({
|
|
|
275
208
|
// are rendered explicitly on scoped copies by tool-surface, never through this list.
|
|
276
209
|
const legacyList = allowedTools ?? deniedTools
|
|
277
210
|
const legacyAllowed = typeof legacyList === 'function' ? legacyList : () => legacyList
|
|
278
|
-
const
|
|
279
|
-
const body =
|
|
280
|
-
'把一个自包含任务交给子代理执行。子代理看不到本会话,prompt
|
|
211
|
+
const globalReadOnly = () => configValue(config, 'readOnlyEnabled', false) === true
|
|
212
|
+
const body = (readOnlyEnabled) =>
|
|
213
|
+
'把一个自包含任务交给子代理执行。子代理看不到本会话,prompt 须写清目标、允许修改的文件、验收命令与兜底方案。' +
|
|
214
|
+
(readOnlyEnabled ? '非只读任务必填 writeScope;只读任务设 readOnly: true,不占租约,宿主不提供逐子代理物理只读隔离。'
|
|
215
|
+
: '必填 writeScope。') +
|
|
216
|
+
"有闲置可续跑子代理时请先复用,需要新建时填写 allowNewReason。" +
|
|
281
217
|
'立即返回子代理 ID 及宿主提供的 agentName,二者均可填 send_message.agent。结束时自动通知,严禁要求子代理用 send_message 汇报。' +
|
|
282
218
|
'独立 Worktree 交付物须经 worktree_manage 评审、合回或丢弃。' +
|
|
283
219
|
'多个独立任务在同一轮并发发起;同构批量请用 orchestrate。'
|
|
284
|
-
const describeFor = (allowed) =>
|
|
285
|
-
|
|
286
|
-
:
|
|
287
|
-
|
|
220
|
+
const describeFor = (allowed, options = {}) => {
|
|
221
|
+
const { enabled = isDispatchEnabled(config), readOnlyEnabled = globalReadOnly() } = options
|
|
222
|
+
const rule = enabled ? mainAgentRule(allowed, { readOnlyEnabled }) + (nativeToolNote?.(allowed) ?? '') : ''
|
|
223
|
+
return rule + body(readOnlyEnabled)
|
|
224
|
+
}
|
|
225
|
+
const descriptionOf = () => legacyList === undefined ? body(globalReadOnly()) : describeFor(legacyAllowed())
|
|
288
226
|
|
|
289
227
|
// A provisional id lets the lease be registered before the host names the child: the
|
|
290
228
|
// conflict has to be refused before `startActivation` (AC1). `rebind` moves the same
|
|
@@ -315,6 +253,7 @@ export function createDelegateTool({
|
|
|
315
253
|
description: '交给子代理的完整任务说明;它看不到本会话。',
|
|
316
254
|
},
|
|
317
255
|
team_task_id: TEAM_TASK_ID_PARAMETER,
|
|
256
|
+
allowNewReason: { type: "string", description: "确实无法复用闲置子代理时,填写非空原因以允许新建。" },
|
|
318
257
|
provider: {
|
|
319
258
|
type: 'string',
|
|
320
259
|
description:
|
|
@@ -339,7 +278,6 @@ export function createDelegateTool({
|
|
|
339
278
|
subagentId: { type: 'string' },
|
|
340
279
|
agentName: { type: 'string' },
|
|
341
280
|
readOnly: { type: 'boolean' },
|
|
342
|
-
baselineId: { type: 'string' },
|
|
343
281
|
worktree: {
|
|
344
282
|
type: 'object',
|
|
345
283
|
additionalProperties: false,
|
|
@@ -369,23 +307,28 @@ export function createDelegateTool({
|
|
|
369
307
|
// Workers are independent by contract, so several may be started in one message.
|
|
370
308
|
isConcurrencySafe: () => true,
|
|
371
309
|
async execute(args, exec) {
|
|
372
|
-
|
|
373
|
-
const
|
|
310
|
+
const parent = exec?.agent
|
|
311
|
+
const effective = resolveSessionConfig?.(parent)
|
|
312
|
+
if (!(effective?.enabled ?? isDispatchEnabled(config))) throw new Error(disabledToolMessage(DELEGATE_TOOL))
|
|
374
313
|
if (!parent) throw new Error('delegate requires a calling agent (exec.agent was undefined)')
|
|
314
|
+
const checked = validateDispatchWrite(args, DELEGATE_TOOL, effective?.readOnlyEnabled ?? globalReadOnly())
|
|
375
315
|
const isolation = validateDispatchIsolation(args)
|
|
376
|
-
const checked = validateDispatchWrite(args, DELEGATE_TOOL)
|
|
377
316
|
if (typeof args?.prompt !== 'string' || args.prompt.trim() === '') throw new Error('delegate requires a non-empty prompt')
|
|
378
317
|
if (typeof args?.description !== 'string' || args.description.trim() === '') throw new Error('delegate requires a non-empty description')
|
|
379
318
|
const teamTaskId = parseTeamTaskId(args.team_task_id, DELEGATE_TOOL)
|
|
319
|
+
const allowNewReason = parseAllowNewReason(args.allowNewReason)
|
|
320
|
+
if (allowNewReason === undefined && listReusableChildren) {
|
|
321
|
+
requireReuse(await listReusableChildren(parent, exec.signal))
|
|
322
|
+
}
|
|
380
323
|
// An explicit per-call override wins and is never read from config; otherwise the
|
|
381
324
|
// route is read at call time, so a changed route applies from this delegation on.
|
|
382
|
-
const route = readRouteOverride(args, DELEGATE_TOOL) ?? readRoute(config)
|
|
325
|
+
const route = readRouteOverride(args, DELEGATE_TOOL) ?? effective?.workerRoute ?? readRoute(config)
|
|
383
326
|
exec.signal.throwIfAborted()
|
|
384
327
|
const maxDepth = subagents.resolveMaxDepth(undefined)
|
|
385
328
|
let worktree
|
|
386
329
|
let isolationFallback
|
|
387
330
|
const forced = isolation.mode === 'worktree'
|
|
388
|
-
if (!checked.readOnly && (forced || (isolation.mode === 'auto' && isWorktreeEnabled()))) {
|
|
331
|
+
if (!checked.readOnly && (forced || (isolation.mode === 'auto' && (effective?.worktreeIsolationEnabled ?? isWorktreeEnabled(parent))))) {
|
|
389
332
|
if (!worktrees && forced) throw worktreeFailure({ code: 'worktree-create-failed', message: '工作树管理器不可用。' })
|
|
390
333
|
if (worktrees) {
|
|
391
334
|
const created = worktrees.create({
|
|
@@ -403,15 +346,15 @@ export function createDelegateTool({
|
|
|
403
346
|
let handedOff = false
|
|
404
347
|
let childStarted = false
|
|
405
348
|
try {
|
|
406
|
-
// Claim the execution checkout
|
|
349
|
+
// Claim the execution checkout before the host can run the child.
|
|
407
350
|
write = prepareDispatchWrite({
|
|
408
351
|
args, exec, parent, leases, childId: nextPendingChildId(parent), tool: DELEGATE_TOOL, checked,
|
|
409
|
-
worktree,
|
|
352
|
+
worktree,
|
|
410
353
|
})
|
|
354
|
+
if (allowNewReason !== undefined) write.allowNewReason = allowNewReason
|
|
411
355
|
const held = write.lease
|
|
412
|
-
const baselineId = write.baseline?.baselineId
|
|
413
356
|
const spec = buildActivation({
|
|
414
|
-
args, parent, route, maxDepth, signal: exec.signal,
|
|
357
|
+
args, parent, route, maxDepth, signal: exec.signal, worktree, teamTaskId,
|
|
415
358
|
})
|
|
416
359
|
if (persistence) {
|
|
417
360
|
await persistence.beforeLaunch(write)
|
|
@@ -460,7 +403,6 @@ export function createDelegateTool({
|
|
|
460
403
|
subagentId: childId,
|
|
461
404
|
...(agentName && { agentName }),
|
|
462
405
|
...(held === null ? { readOnly: true } : { writeScope: { leaseId: held.leaseId, scope: [...scope] } }),
|
|
463
|
-
...(baselineId === undefined ? {} : { baselineId }),
|
|
464
406
|
...(isolated ? { worktree: isolated, details: { worktree: isolated } } : {}),
|
|
465
407
|
...(isolationFallback ? { details: { isolationFallback } } : {}),
|
|
466
408
|
}
|
package/lib/gate.js
CHANGED
|
@@ -33,11 +33,17 @@
|
|
|
33
33
|
* through `tools.*`).
|
|
34
34
|
*/
|
|
35
35
|
|
|
36
|
-
import { DELEGATE_TOOL, ORCHESTRATE_TOOL, disabledToolMessage } from './api.js'
|
|
36
|
+
import { DELEGATE_STATUS_TOOL_NAME, DELEGATE_TOOL, ORCHESTRATE_TOOL, disabledToolMessage } from './api.js'
|
|
37
37
|
import { RUN_CODE_TOOL, runCodeRefusal } from './run-code-guard.js'
|
|
38
38
|
|
|
39
39
|
export { DELEGATE_TOOL }
|
|
40
40
|
|
|
41
|
+
export const DISPATCH_MODE_TOOLS = Object.freeze([
|
|
42
|
+
DELEGATE_TOOL, ORCHESTRATE_TOOL, DELEGATE_STATUS_TOOL_NAME, 'worktree_manage',
|
|
43
|
+
])
|
|
44
|
+
const DISPATCH_MODE_TOOL_SET = new Set(DISPATCH_MODE_TOOLS)
|
|
45
|
+
export const isDispatchTool = (name) => DISPATCH_MODE_TOOL_SET.has(name)
|
|
46
|
+
|
|
41
47
|
/** Optional host task board. These names do not register tools or create a separate board. */
|
|
42
48
|
export const NATIVE_TEAM_TOOLS = Object.freeze([
|
|
43
49
|
'team_task_create',
|
|
@@ -252,8 +258,8 @@ export function installGate({ agent, allowed, allowAgentTeam = true, enabled = (
|
|
|
252
258
|
if (isDelegatedChild(caller)) return undefined
|
|
253
259
|
const supervisionDenial = checkSupervision?.(caller, tool)
|
|
254
260
|
if (typeof supervisionDenial === 'string' && supervisionDenial !== '') return supervisionDenial
|
|
255
|
-
if (!enabled()) {
|
|
256
|
-
if (tool
|
|
261
|
+
if (!enabled(caller)) {
|
|
262
|
+
if (isDispatchTool(tool)) {
|
|
257
263
|
return disabledToolMessage(tool)
|
|
258
264
|
}
|
|
259
265
|
return undefined
|