@sshirkit/dsh-orchestrator 1.0.1 → 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 +65 -30
- package/README.zh.md +62 -29
- package/lib/client.js +809 -311
- package/lib/delegate-status.js +42 -67
- package/lib/delegate.js +98 -140
- package/lib/gate.js +11 -5
- package/lib/index.js +533 -442
- package/lib/orchestrate.js +143 -129
- package/lib/read-index.js +186 -0
- package/lib/reconcile.js +2 -3
- package/lib/rules.js +22 -10
- package/lib/session-tools.js +516 -0
- 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 +57 -9
- 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
|
-
import { mainAgentRule } 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'
|
|
18
|
+
import { mainAgentRule, teamTaskPromptNote } from './rules.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,65 +34,78 @@ 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 = '本任务仅限只读,不得写入文件。不占写租约;宿主未提供逐子代理物理只读隔离。'
|
|
41
38
|
|
|
42
|
-
|
|
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
|
+
}
|
|
57
|
+
|
|
58
|
+
export const TEAM_TASK_ID_PARAMETER = Object.freeze({
|
|
59
|
+
type: 'string',
|
|
60
|
+
description: '可选原生 Team 任务 ID;传给子代理作为共享目标的只读对齐参考,不能替代完整任务说明。',
|
|
61
|
+
})
|
|
62
|
+
|
|
63
|
+
export function parseTeamTaskId(value, tool) {
|
|
64
|
+
if (value === undefined) return undefined
|
|
65
|
+
if (typeof value !== 'string' || value.trim() === '') {
|
|
66
|
+
throw new Error(`${tool}: "team_task_id" must be a non-empty string when provided`)
|
|
67
|
+
}
|
|
68
|
+
return value.trim()
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
export function dispatchWriteParameters({ batch = false, readOnlyEnabled = true } = {}) {
|
|
43
72
|
return {
|
|
44
73
|
writeScope: {
|
|
45
74
|
type: 'array',
|
|
46
75
|
items: { type: 'string' },
|
|
47
76
|
description:
|
|
48
|
-
'非只读任务必填:允许写入的文件或目录(至少一项);readOnly: true 必须省略此项或传空数组。'
|
|
77
|
+
(readOnlyEnabled ? '非只读任务必填:允许写入的文件或目录(至少一项);readOnly: true 必须省略此项或传空数组。'
|
|
78
|
+
: '必填:声明作用域(至少一项);只读调研请同时使用 shared 并明确禁止修改文件。') +
|
|
49
79
|
(batch ? '共享模式下整批共享一个写租约;隔离模式下每条目独立租用。' : '') +
|
|
50
80
|
'冲突报 write-scope-conflict。相对路径基于 cwd,目录用 "/" 或 "/**";声明不扩大权限,也不阻止越界写入。',
|
|
51
81
|
},
|
|
52
|
-
readOnly: { type: 'boolean', default: false, description: `设为 true 时:${READ_ONLY_NOTICE}` },
|
|
82
|
+
...(readOnlyEnabled && { readOnly: { type: 'boolean', default: false, description: `设为 true 时:${READ_ONLY_NOTICE}` } }),
|
|
53
83
|
isolation: {
|
|
54
84
|
type: 'string',
|
|
55
85
|
enum: [...ISOLATION_MODES],
|
|
56
|
-
description: 'auto(默认,受 worktreeIsolationEnabled 控制):Git 写任务自动使用独立 Worktree,非 Git
|
|
57
|
-
'worktree:强制隔离,非 Git、空仓或超出工作区边界时报错,不降级。shared:使用共享工作区。
|
|
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 的相对路径。',
|
|
86
|
+
description: 'auto(默认,受 worktreeIsolationEnabled 控制):Git 写任务自动使用独立 Worktree,非 Git 使用共享工作区。' +
|
|
87
|
+
'worktree:强制隔离,非 Git、空仓或超出工作区边界时报错,不降级。shared:使用共享工作区。' +
|
|
88
|
+
(readOnlyEnabled ? 'readOnly: true 不建树,不能组合 worktree。' : ''),
|
|
69
89
|
},
|
|
70
90
|
}
|
|
71
91
|
}
|
|
72
92
|
|
|
93
|
+
export const READ_ONLY_DISABLED = 'readOnly 参数当前未启用,请移除此参数。只读调研请使用 isolation: "shared",并在任务中明确禁止修改文件。'
|
|
94
|
+
|
|
73
95
|
const invalidWrite = (message) => new WriteScopeError(WRITE_SCOPE_TOOL_CODES.invalid, message)
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
const normalized = path.posix.normalize(value.replaceAll('\\', '/'))
|
|
78
|
-
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)
|
|
79
99
|
}
|
|
80
100
|
|
|
81
|
-
export function validateDispatchWrite(args, tool) {
|
|
82
|
-
|
|
101
|
+
export function validateDispatchWrite(args, tool, readOnlyEnabled = true) {
|
|
102
|
+
assertReadOnlyArgumentEnabled(args, readOnlyEnabled)
|
|
103
|
+
const { writeScope, readOnly } = args ?? {}
|
|
83
104
|
if (readOnly !== undefined && typeof readOnly !== 'boolean') throw invalidWrite('readOnly 必须是布尔值。')
|
|
84
105
|
// Preserve the established tool-level error for a missing declaration.
|
|
85
106
|
if (readOnly !== true) requireWriteScope(args, tool)
|
|
86
107
|
const checked = validateWriteScopeInput({ writeScope, readOnly })
|
|
87
108
|
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
109
|
return checked
|
|
100
110
|
}
|
|
101
111
|
|
|
@@ -132,30 +142,6 @@ export function discardEmptyWorktree(worktrees, worktree, onCleanupFailed) {
|
|
|
132
142
|
}
|
|
133
143
|
}
|
|
134
144
|
|
|
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
145
|
function relocateWriteScope(entries, sourceCwd) {
|
|
160
146
|
const normalized = normalizeScope(entries, sourceCwd)
|
|
161
147
|
if (!normalized.ok) throw writeScopeFailure(normalized)
|
|
@@ -170,7 +156,7 @@ function relocateWriteScope(entries, sourceCwd) {
|
|
|
170
156
|
}
|
|
171
157
|
|
|
172
158
|
export function prepareDispatchWrite({
|
|
173
|
-
args, exec, parent, leases, childId, tool, checked, worktree,
|
|
159
|
+
args, exec, parent, leases, childId, tool, checked, worktree,
|
|
174
160
|
}) {
|
|
175
161
|
const sourceCwd = dispatchCwd(args, exec)
|
|
176
162
|
const cwd = worktree?.execCwd ?? sourceCwd
|
|
@@ -180,58 +166,18 @@ export function prepareDispatchWrite({
|
|
|
180
166
|
: typeof args.writeScope === 'string' ? [args.writeScope] : [...args.writeScope]
|
|
181
167
|
const leaseArgs = worktree ? { ...args, cwd, writeScope } : args
|
|
182
168
|
const held = readOnly ? null : claimWriteScope({ args: leaseArgs, exec, parent, leases, childId, tool })
|
|
183
|
-
|
|
184
|
-
|
|
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)
|
|
169
|
+
const entries = held === null ? [] : leases.get?.(held.leaseId)?.entries ?? normalizeScope(writeScope, cwd).entries
|
|
170
|
+
return { lease: held, entries, cwd, writeScope, readOnly, ...(worktree && { worktree }) }
|
|
225
171
|
}
|
|
226
172
|
|
|
227
173
|
/** The delegate spec: the prompt carries the language note and delivery answers the parent. */
|
|
228
|
-
export function buildActivation({ args, parent, route, maxDepth, signal,
|
|
174
|
+
export function buildActivation({ args, parent, route, maxDepth, signal, worktree, teamTaskId }) {
|
|
229
175
|
return buildSpawnActivation({
|
|
230
176
|
cwd: worktree?.execCwd ?? args.cwd,
|
|
231
177
|
prompt: languageNote(args.prompt) + args.prompt +
|
|
232
178
|
(args.readOnly === true ? `\n\n${READ_ONLY_NOTICE}` : '') +
|
|
233
|
-
(
|
|
234
|
-
(
|
|
179
|
+
(worktree ? `\n\n${worktreePromptNote(worktree)}` : '') +
|
|
180
|
+
(teamTaskId === undefined ? '' : `\n\n${teamTaskPromptNote(teamTaskId)}`),
|
|
235
181
|
label: args.description,
|
|
236
182
|
parent,
|
|
237
183
|
route,
|
|
@@ -252,26 +198,31 @@ export function createDelegateTool({
|
|
|
252
198
|
leases,
|
|
253
199
|
worktrees,
|
|
254
200
|
isWorktreeEnabled = () => true,
|
|
201
|
+
resolveSessionConfig,
|
|
255
202
|
getWorkspaceRoot,
|
|
256
|
-
|
|
203
|
+
listReusableChildren,
|
|
257
204
|
onCleanupFailed,
|
|
258
205
|
persistence,
|
|
259
206
|
}) {
|
|
260
|
-
//
|
|
261
|
-
//
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
const
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
'把一个自包含任务交给子代理执行。子代理看不到本会话,prompt 须写清目标、允许修改的文件、验收命令与兜底方案。非只读任务必填 writeScope;只读任务设 readOnly: true,不占租约,只做逻辑写后审计而非物理隔离。' +
|
|
207
|
+
// Direct callers may provide an unscoped display list. Model-facing descriptions
|
|
208
|
+
// are rendered explicitly on scoped copies by tool-surface, never through this list.
|
|
209
|
+
const legacyList = allowedTools ?? deniedTools
|
|
210
|
+
const legacyAllowed = typeof legacyList === 'function' ? legacyList : () => legacyList
|
|
211
|
+
const globalReadOnly = () => configValue(config, 'readOnlyEnabled', false) === true
|
|
212
|
+
const body = (readOnlyEnabled) =>
|
|
213
|
+
'把一个自包含任务交给子代理执行。子代理看不到本会话,prompt 须写清目标、允许修改的文件、验收命令与兜底方案。' +
|
|
214
|
+
(readOnlyEnabled ? '非只读任务必填 writeScope;只读任务设 readOnly: true,不占租约,宿主不提供逐子代理物理只读隔离。'
|
|
215
|
+
: '必填 writeScope。') +
|
|
216
|
+
"有闲置可续跑子代理时请先复用,需要新建时填写 allowNewReason。" +
|
|
271
217
|
'立即返回子代理 ID 及宿主提供的 agentName,二者均可填 send_message.agent。结束时自动通知,严禁要求子代理用 send_message 汇报。' +
|
|
272
218
|
'独立 Worktree 交付物须经 worktree_manage 评审、合回或丢弃。' +
|
|
273
219
|
'多个独立任务在同一轮并发发起;同构批量请用 orchestrate。'
|
|
274
|
-
const
|
|
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())
|
|
275
226
|
|
|
276
227
|
// A provisional id lets the lease be registered before the host names the child: the
|
|
277
228
|
// conflict has to be refused before `startActivation` (AC1). `rebind` moves the same
|
|
@@ -301,6 +252,8 @@ export function createDelegateTool({
|
|
|
301
252
|
required: true,
|
|
302
253
|
description: '交给子代理的完整任务说明;它看不到本会话。',
|
|
303
254
|
},
|
|
255
|
+
team_task_id: TEAM_TASK_ID_PARAMETER,
|
|
256
|
+
allowNewReason: { type: "string", description: "确实无法复用闲置子代理时,填写非空原因以允许新建。" },
|
|
304
257
|
provider: {
|
|
305
258
|
type: 'string',
|
|
306
259
|
description:
|
|
@@ -325,7 +278,6 @@ export function createDelegateTool({
|
|
|
325
278
|
subagentId: { type: 'string' },
|
|
326
279
|
agentName: { type: 'string' },
|
|
327
280
|
readOnly: { type: 'boolean' },
|
|
328
|
-
baselineId: { type: 'string' },
|
|
329
281
|
worktree: {
|
|
330
282
|
type: 'object',
|
|
331
283
|
additionalProperties: false,
|
|
@@ -355,22 +307,28 @@ export function createDelegateTool({
|
|
|
355
307
|
// Workers are independent by contract, so several may be started in one message.
|
|
356
308
|
isConcurrencySafe: () => true,
|
|
357
309
|
async execute(args, exec) {
|
|
358
|
-
|
|
359
|
-
const
|
|
310
|
+
const parent = exec?.agent
|
|
311
|
+
const effective = resolveSessionConfig?.(parent)
|
|
312
|
+
if (!(effective?.enabled ?? isDispatchEnabled(config))) throw new Error(disabledToolMessage(DELEGATE_TOOL))
|
|
360
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())
|
|
361
315
|
const isolation = validateDispatchIsolation(args)
|
|
362
|
-
const checked = validateDispatchWrite(args, DELEGATE_TOOL)
|
|
363
316
|
if (typeof args?.prompt !== 'string' || args.prompt.trim() === '') throw new Error('delegate requires a non-empty prompt')
|
|
364
317
|
if (typeof args?.description !== 'string' || args.description.trim() === '') throw new Error('delegate requires a non-empty description')
|
|
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
|
+
}
|
|
365
323
|
// An explicit per-call override wins and is never read from config; otherwise the
|
|
366
324
|
// route is read at call time, so a changed route applies from this delegation on.
|
|
367
|
-
const route = readRouteOverride(args, DELEGATE_TOOL) ?? readRoute(config)
|
|
325
|
+
const route = readRouteOverride(args, DELEGATE_TOOL) ?? effective?.workerRoute ?? readRoute(config)
|
|
368
326
|
exec.signal.throwIfAborted()
|
|
369
327
|
const maxDepth = subagents.resolveMaxDepth(undefined)
|
|
370
328
|
let worktree
|
|
371
329
|
let isolationFallback
|
|
372
330
|
const forced = isolation.mode === 'worktree'
|
|
373
|
-
if (!checked.readOnly && (forced || (isolation.mode === 'auto' && isWorktreeEnabled()))) {
|
|
331
|
+
if (!checked.readOnly && (forced || (isolation.mode === 'auto' && (effective?.worktreeIsolationEnabled ?? isWorktreeEnabled(parent))))) {
|
|
374
332
|
if (!worktrees && forced) throw worktreeFailure({ code: 'worktree-create-failed', message: '工作树管理器不可用。' })
|
|
375
333
|
if (worktrees) {
|
|
376
334
|
const created = worktrees.create({
|
|
@@ -388,14 +346,16 @@ export function createDelegateTool({
|
|
|
388
346
|
let handedOff = false
|
|
389
347
|
let childStarted = false
|
|
390
348
|
try {
|
|
391
|
-
// Claim the execution checkout
|
|
349
|
+
// Claim the execution checkout before the host can run the child.
|
|
392
350
|
write = prepareDispatchWrite({
|
|
393
351
|
args, exec, parent, leases, childId: nextPendingChildId(parent), tool: DELEGATE_TOOL, checked,
|
|
394
|
-
worktree,
|
|
352
|
+
worktree,
|
|
395
353
|
})
|
|
354
|
+
if (allowNewReason !== undefined) write.allowNewReason = allowNewReason
|
|
396
355
|
const held = write.lease
|
|
397
|
-
const
|
|
398
|
-
|
|
356
|
+
const spec = buildActivation({
|
|
357
|
+
args, parent, route, maxDepth, signal: exec.signal, worktree, teamTaskId,
|
|
358
|
+
})
|
|
399
359
|
if (persistence) {
|
|
400
360
|
await persistence.beforeLaunch(write)
|
|
401
361
|
persistence.assertActive()
|
|
@@ -443,7 +403,6 @@ export function createDelegateTool({
|
|
|
443
403
|
subagentId: childId,
|
|
444
404
|
...(agentName && { agentName }),
|
|
445
405
|
...(held === null ? { readOnly: true } : { writeScope: { leaseId: held.leaseId, scope: [...scope] } }),
|
|
446
|
-
...(baselineId === undefined ? {} : { baselineId }),
|
|
447
406
|
...(isolated ? { worktree: isolated, details: { worktree: isolated } } : {}),
|
|
448
407
|
...(isolationFallback ? { details: { isolationFallback } } : {}),
|
|
449
408
|
}
|
|
@@ -458,12 +417,11 @@ export function createDelegateTool({
|
|
|
458
417
|
}
|
|
459
418
|
},
|
|
460
419
|
})
|
|
461
|
-
//
|
|
462
|
-
//
|
|
463
|
-
Object.
|
|
464
|
-
enumerable: true,
|
|
465
|
-
|
|
466
|
-
get: descriptionOf,
|
|
420
|
+
// Direct consumers keep a readable default. Request-scoped definitions supply their
|
|
421
|
+
// resolved list explicitly rather than changing the registered tool's description.
|
|
422
|
+
Object.defineProperties(tool, {
|
|
423
|
+
description: { enumerable: true, configurable: true, get: descriptionOf },
|
|
424
|
+
describeFor: { value: describeFor },
|
|
467
425
|
})
|
|
468
426
|
return tool
|
|
469
427
|
}
|
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,13 +258,13 @@ 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
|
|
260
266
|
}
|
|
261
|
-
const guard = allowGuard(liveAllowed(), { allowAgentTeam: liveAllowAgentTeam() })
|
|
267
|
+
const guard = allowGuard(liveAllowed(caller), { allowAgentTeam: liveAllowAgentTeam() })
|
|
262
268
|
const refusal = guard(exec)
|
|
263
269
|
if (refusal === undefined) return undefined
|
|
264
270
|
return checkSupervision?.(caller, tool, { whitelistMiss: true }) ?? refusal
|
|
@@ -267,7 +273,7 @@ export function installGate({ agent, allowed, allowAgentTeam = true, enabled = (
|
|
|
267
273
|
guardError = error instanceof Error ? error.message : String(error)
|
|
268
274
|
}
|
|
269
275
|
return {
|
|
270
|
-
allowed: resolveEffectiveAllowedTools(liveAllowed(), { allowAgentTeam: liveAllowAgentTeam() }),
|
|
276
|
+
allowed: resolveEffectiveAllowedTools(liveAllowed(agent), { allowAgentTeam: liveAllowAgentTeam() }),
|
|
271
277
|
guardError,
|
|
272
278
|
/** Unregister the guard. A second call is a no-op. */
|
|
273
279
|
dispose: () => {
|