@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.
@@ -0,0 +1,186 @@
1
+ import { isDelegatedChild } from './gate.js'
2
+
3
+ const READ_TOOLS = new Map([
4
+ ['read', 'read'], ['ops_inspect_local_file', 'read'],
5
+ ['glob', 'glob'], ['ops_glob', 'glob'],
6
+ ['grep', 'grep'], ['ops_grep', 'grep'],
7
+ ])
8
+ const MAX_CHILDREN = 128
9
+ const MAX_CALLS = 1024
10
+ const MAX_ENTRIES = 20
11
+ const MAX_PEERS_SHOWN = 5
12
+ const MAX_ROWS_SHOWN = 5
13
+ const ANSWER_PREFIX = '【平级只读咨询答复】'
14
+ export const PEER_CONSULT_SOURCE_KIND = 'orchestrator-peer-read-only-consult'
15
+
16
+ function remember(map, key, value, limit) {
17
+ map.delete(key)
18
+ map.set(key, value)
19
+ if (map.size > limit) map.delete(map.keys().next().value)
20
+ }
21
+
22
+ function compact(value, limit = 220) {
23
+ return typeof value === 'string' ? value.replace(/[\x00-\x1f\x7f\u2028\u2029]/g, ' ').trim().slice(0, limit) : ''
24
+ }
25
+
26
+ function pathOf(value) {
27
+ return compact(typeof value === 'string' ? value : value?.path ?? value?.filePath ?? value?.file_path)
28
+ }
29
+
30
+ function positiveInteger(value) {
31
+ return Number.isSafeInteger(value) && value > 0 ? value : undefined
32
+ }
33
+
34
+ function readRows(kind, args, value) {
35
+ if (kind === 'read') {
36
+ const path = pathOf(value) || pathOf(args)
37
+ const lines = Array.isArray(value?.lines) ? value.lines : undefined
38
+ const from = positiveInteger(lines?.[0]?.number ?? value?.offset ?? value?.startLine ?? args.offset ?? args.start_line) ?? 1
39
+ const to = positiveInteger(lines?.at(-1)?.number ?? value?.endLine) ?? (lines?.length ? from + lines.length - 1 : undefined)
40
+ if (!path || lines?.length === 0) return []
41
+ return [{ path, detail: to === undefined ? `读取自第 ${from} 行` : `已读第 ${from}–${to} 行` }]
42
+ }
43
+ const matches = kind === 'glob' ? value?.paths ?? value?.items : value?.matches ?? value?.files ?? value?.items
44
+ if (!Array.isArray(matches)) return []
45
+ const rows = []
46
+ for (const match of matches.slice(0, MAX_ENTRIES)) {
47
+ const path = pathOf(match)
48
+ if (!path) continue
49
+ const line = positiveInteger(match?.lineNumber ?? match?.line_number ?? match?.line)
50
+ const detail = kind === 'glob' ? '路径匹配' : line === undefined ? '检索命中' : `第 ${line} 行命中`
51
+ rows.push({ path, detail })
52
+ }
53
+ return rows
54
+ }
55
+
56
+ function peerOf(left, right) {
57
+ return Boolean(left && right && left.id !== right.id &&
58
+ left.parentId === right.parentId && left.rootId === right.rootId)
59
+ }
60
+
61
+ function relaySender(message) {
62
+ const source = message?.source
63
+ return source?.kind === 'agent-message' && source.form === 'relay' ? source.senderSessionId : undefined
64
+ }
65
+
66
+ function isAnswer(message) {
67
+ // The host prepends its own sender banner as the first block.
68
+ const block = message.content?.[1]
69
+ return block?.type === 'text' && typeof block.text === 'string' && block.text.startsWith(ANSWER_PREFIX)
70
+ }
71
+
72
+ /** Keep metadata only; file contents, search excerpts and agent messages are never indexed. */
73
+ export function createReadIndex({
74
+ enabledFor, getAgent, listAgents, rootIdOf, readOnlyOf, nameOf, resolvePeerTarget,
75
+ } = {}) {
76
+ const children = new Map()
77
+ const calls = new Map()
78
+ const receipts = new Map()
79
+ const shown = new WeakMap()
80
+
81
+ function identity(agent) {
82
+ if (!isDelegatedChild(agent) || typeof agent?.id !== 'string') return undefined
83
+ const parentId = agent.session?.header?.parentSession
84
+ const rootId = rootIdOf(agent)
85
+ if (typeof parentId !== 'string' || typeof rootId !== 'string') return undefined
86
+ const previous = children.get(agent.id)
87
+ const rows = previous?.rootId === rootId && previous.parentId === parentId ? previous.rows : new Map()
88
+ return {
89
+ id: agent.id, parentId, rootId,
90
+ name: compact(nameOf?.(agent), 120) || agent.id,
91
+ readOnly: readOnlyOf?.(agent) === true,
92
+ rows,
93
+ }
94
+ }
95
+
96
+ function enabled(agent) {
97
+ return enabledFor(rootIdOf(agent)) === true
98
+ }
99
+
100
+ function addReceipt(id, sender, target) {
101
+ if (typeof id === 'string' && id && peerOf(sender, target)) {
102
+ remember(receipts, id, { senderId: sender.id, rootId: sender.rootId }, MAX_CALLS)
103
+ }
104
+ }
105
+
106
+ async function observe(exec, result) {
107
+ const agent = exec?.agent
108
+ const kind = READ_TOOLS.get(exec?.name)
109
+ if ((!kind && exec?.name !== 'send_message') || !isDelegatedChild(agent) ||
110
+ !result || result.isError === true || !enabled(agent)) return
111
+ const child = identity(agent)
112
+ if (!child) return
113
+ const { callId } = exec
114
+ if (typeof callId !== 'string' || !callId) return
115
+ const callKey = JSON.stringify([child.id, callId])
116
+ if (calls.has(callKey)) return
117
+ remember(calls, callKey, true, MAX_CALLS)
118
+ remember(children, child.id, child, MAX_CHILDREN)
119
+ if (exec.name === 'send_message') {
120
+ const targetId = await resolvePeerTarget?.(exec)
121
+ addReceipt(result.value?.messageId, child, identity(getAgent?.(targetId)) ?? children.get(targetId))
122
+ return
123
+ }
124
+ for (const row of readRows(kind, exec.arguments ?? {}, result.value)) {
125
+ remember(child.rows, JSON.stringify([row.path, row.detail]), row, MAX_ENTRIES)
126
+ }
127
+ }
128
+
129
+ function peerSummary(agent, child) {
130
+ const peers = []
131
+ for (const live of listAgents?.() ?? []) {
132
+ const peer = children.get(live?.id)
133
+ if (peer?.rows.size && peerOf(child, peer) && peerOf(child, identity(live))) peers.push(peer)
134
+ }
135
+ const text = peers.slice(0, MAX_PEERS_SHOWN).map((peer) => {
136
+ const rows = [...peer.rows.values()].slice(-MAX_ROWS_SHOWN)
137
+ .map(({ path, detail }) => `${JSON.stringify(path)}(${detail})`).join('、')
138
+ return `- ${JSON.stringify(peer.name)}(ID ${JSON.stringify(peer.id)},${peer.readOnly ? '只读任务' : '含写任务'}):${rows}`
139
+ }).join('\n')
140
+ if (shown.get(agent) === text) return ''
141
+ if (!text) shown.delete(agent)
142
+ return text
143
+ }
144
+
145
+ function prepare(agent, messages) {
146
+ if (!agent || !enabled(agent)) {
147
+ if (agent) shown.delete(agent)
148
+ return { messages }
149
+ }
150
+ if (!isDelegatedChild(agent)) {
151
+ const rootId = rootIdOf(agent)
152
+ const filtered = messages.filter((message) => {
153
+ const sender = relaySender(message)
154
+ const receipt = sender && receipts.get(message.id)
155
+ return !(receipt?.rootId === rootId && receipt?.senderId === sender && !message.source.error && !message.error)
156
+ })
157
+ return { messages: filtered.length === messages.length ? messages : filtered }
158
+ }
159
+ const child = identity(agent)
160
+ if (!child || messages.length === 0) return { messages }
161
+ const askers = new Map()
162
+ for (const message of messages) {
163
+ const senderId = relaySender(message)
164
+ if (!senderId) continue
165
+ const sender = identity(getAgent?.(senderId)) ?? children.get(senderId)
166
+ if (!peerOf(child, sender)) continue
167
+ addReceipt(message.id, sender, child)
168
+ if (!isAnswer(message)) askers.set(sender.id, sender.name)
169
+ }
170
+ const summary = peerSummary(agent, child)
171
+ const parts = []
172
+ if (summary) {
173
+ parts.push('【平级已读索引】下列条目是路径和命中位置。可用 send_message 请对方概括其已读上下文,减少重复读取。\n' + summary)
174
+ }
175
+ for (const [id, name] of [...askers].slice(0, MAX_PEERS_SHOWN)) {
176
+ parts.push(`这是来自平级子代理 ${JSON.stringify(name)} 的只读上下文咨询。请仅基于已读事实简明回答,保持文件和主任务边界。用 send_message 向 ${JSON.stringify(id)} 回复,正文以 ${ANSWER_PREFIX} 开头,然后继续原任务。`)
177
+ }
178
+ return {
179
+ messages,
180
+ text: parts.join('\n'),
181
+ acknowledge: summary ? () => shown.set(agent, summary) : undefined,
182
+ }
183
+ }
184
+
185
+ return { observe, prepare }
186
+ }
package/lib/reconcile.js CHANGED
@@ -485,7 +485,8 @@ export async function reconcileOnStartup({
485
485
  if (isId(leaseId) && !expired.has(leaseId) && (knownLeaseIds.has(leaseId) || await leases?.get?.(leaseId))) {
486
486
  childLeases.add(leaseId)
487
487
  }
488
- if (TERMINAL_STATES.has(record.dispatchState) && record.auditState !== 'pending' && childLeases.size === 0) continue
488
+ const activeCheckout = record.worktreeId && worktrees?.get?.(record.worktreeId)?.state === 'active'
489
+ if (TERMINAL_STATES.has(record.dispatchState) && childLeases.size === 0 && !activeCheckout) continue
489
490
 
490
491
  const host = await inspect(childId, parentId, rootSessionId)
491
492
  signal?.throwIfAborted?.()
@@ -531,8 +532,6 @@ export async function reconcileOnStartup({
531
532
  const terminal = lost ? { dispatchState: 'lost', stopReason: 'lost' } : terminalState(host.lastTurnEndKind)
532
533
  const outcome = lost ? 'lost' : terminal.dispatchState === 'interrupted' ? 'interrupted' : 'settled-offline'
533
534
  const updated = { ...record, ...terminal, endedAt: record.endedAt ?? at, updatedAt: at }
534
- if (record.auditState === 'pending') updated.auditState = 'incomplete'
535
- if (lost || record.auditState === 'pending') updated.incomplete = true
536
535
  const batchStages = pendingBatchStages.get(leaseId)
537
536
  if (!batchStages && (isId(leaseId) || childLeases.size > 0 || lost)) updated.leaseState = 'released'
538
537
  if (!lost && sessionQuery && isId(parentId)) {
package/lib/rules.js CHANGED
@@ -12,25 +12,37 @@
12
12
 
13
13
  import { DELEGATE_STATUS_TOOL_NAME } from './api.js'
14
14
 
15
+ export const TEAM_SHARED_GOAL_RULE =
16
+ '复杂多步或需多子代理协同的任务,先用 team_task_create 建立共享目标,将返回的 id(任务 ID)作为 team_task_id 传给 delegate 或 orchestrate。' +
17
+ '共享目标只用于对齐,仍由 delegate / orchestrate 派发并管理写租约;任务说明必须自包含。'
18
+
19
+ export function teamTaskPromptNote(teamTaskId) {
20
+ const id = JSON.stringify(teamTaskId)
21
+ return `关联的共享目标(team_task_id):${id}。` +
22
+ `若 team_task_get 可用,先调用 team_task_get({ task_id: ${id} }),只读查看共享目标作为对齐参考。` +
23
+ '除非任务明确要求更新进度,否则不要改写共享任务状态。若工具不可用或读取失败,按本提示中的完整自包含任务说明继续。'
24
+ }
25
+
15
26
  /**
16
27
  * Build the rule text. `allowedTools` is the live whitelist the gate enforces,
17
28
  * so the closing sentence names exactly what stays available.
18
29
  */
19
- export function mainAgentRule(allowedTools) {
30
+ export function mainAgentRule(allowedTools, { readOnlyEnabled = false } = {}) {
20
31
  const allowed = [...new Set(allowedTools ?? [])]
21
32
  const allowedNames = allowed.join(', ')
22
33
  return (
23
34
  '主代理规则:主代理只负责规划,读/写/编辑/搜索/命令/抓取均通过 delegate 或 orchestrate 交子代理执行,勿试探调用被禁工具。' +
24
- '同任务报错重试、参数纠偏、小幅返工或追问,优先用 send_message 复用原代理;仅在 writeScope 需变更、Worktree 已锁定、原上下文严重跑偏或无法继续时才新开 delegate。' +
25
- '已结束的写任务续跑前重抢原写租约并拍新基线,租约冲突或工作树已锁定时拒绝投递;本轮结束后写审计并再次释放租约。' +
26
- '新会话或压缩后直接推进,无需重新确认。' +
27
- '独立任务在同一消息内并发派发,delegate 完成后直接结束回合等待子代理完成,勿空转轮询状态。' +
28
- '子代理完成通知只代表执行结束,不等于写作用域审计通过。' +
35
+ '优先用 send_message 复用当前会话中已有且闲置(inactive)的子代理,例如重试、纠偏、返工或追问。' +
29
36
  (allowed.includes(DELEGATE_STATUS_TOOL_NAME)
30
- ? `若未见同帧审计通过确认,验收前按需调用一次 ${DELEGATE_STATUS_TOOL_NAME} 核验审计状态(pending / passed / failed);只有 passed 才确认通过,勿盲等或循环轮询。`
31
- : '') +
32
- 'Git 仓库的写任务默认在独立 Git Worktree 中执行,用 git diff / git log 审计;非 Git 目录自动降级为逻辑写后审计。可用 isolation: "auto" | "worktree" | "shared" 覆盖。' +
33
- 'Worktree 不自动合回;执行结束、写审计通过、主代理合回是三步。' +
37
+ ? `需调整该子代理下一轮的 writeScope 或 readOnly 时,先调用 ${DELEGATE_STATUS_TOOL_NAME}({ action: 'edit', childId, writeScope, readOnly }) 更新待应用声明,再用 send_message 唤醒。`
38
+ : '复用时沿用当前写作用域和只读声明。') +
39
+ '仅在 Worktree 已锁定或合回、原上下文跑偏,或确需并行处理互不干扰的独立任务时,才通过 delegate 的 allowNewReason 说明原因后新建。' +
40
+ '恢复写任务前按下一轮声明重新获取写租约,租约冲突或工作树已锁定时拒绝投递;本轮结束后释放租约。' +
41
+ '新会话或压缩后直接推进,无需重新确认。' +
42
+ '确需并行的独立任务在同一消息内派发,delegate 返回后直接结束回合等待子代理完成,勿空转轮询状态。' +
43
+ 'Git 仓库中的写任务默认在独立 Git Worktree 中执行,非 Git 目录使用写租约协调声明范围内的写入。可用 isolation: "auto" | "worktree" | "shared" 覆盖隔离模式。' +
44
+ (readOnlyEnabled ? '' : '只读调研或检索无需代码隔离时,显式传 isolation: "shared",并在任务描述和边界中要求不得修改文件,避免创建无用 Worktree。') +
45
+ 'Worktree 不自动合回;子代理交付后由主代理评审并决定是否合回。' +
34
46
  (allowed.includes('worktree_manage')
35
47
  ? '用 worktree_manage(list / inspect / merge / discard / prune)显式评审、合回或清理。'
36
48
  : '') +