dsh-chief 1.2.1 → 1.3.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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-chief",
3
- "version": "1.2.1",
3
+ "version": "1.3.0",
4
4
  "icon": "icon.svg",
5
5
  "type": "module",
6
6
  "description": "AI manager for your agent crews. Let AI manage AI — it watches the flow, stops a runaway loop before it burns budget, and asks before touching your workspace. Less babysitting, fewer blow-ups.",
@@ -47,6 +47,13 @@
47
47
  "dsh": ">=0.2.2-rc.2"
48
48
  },
49
49
  "main": "./index.js",
50
+ "scripts": {
51
+ "build:client": "node ./scripts/build-client.mjs",
52
+ "check:client": "node ./scripts/build-client.mjs --check",
53
+ "check:syntax": "node -e \"const fs=require('fs'),cp=require('child_process');for(const f of fs.readdirSync('.').filter(x=>x.endsWith('.js')))cp.execFileSync(process.execPath,['--check',f]);\"",
54
+ "test:ci": "npm run check:client && npm run check:syntax && node ./tests/verify-v130-release-gate.mjs",
55
+ "test": "node ./tests/verify-v130-release-gate.mjs && node -e \"const fs=require('fs'),path=require('path'),cp=require('child_process');if(fs.existsSync('../tools')){for(const s of ['verify-chief-facade-split.mjs','verify-index-modular-split.mjs','verify-archives-modular-split.mjs','verify-client-modular-build.mjs','verify-v121-permissions-and-ui.mjs','verify-compaction-and-blank-chat.mjs','check-action-surface.mjs','verify-v130-four-chains.mjs']){cp.execFileSync(process.execPath,[path.resolve('..','tools',s)],{stdio:'inherit'});}}\""
56
+ },
50
57
  "exports": {
51
58
  ".": "./index.js",
52
59
  "./client": "./client.js",
@@ -57,11 +64,31 @@
57
64
  },
58
65
  "files": [
59
66
  "index.js",
67
+ "board-schema.js",
68
+ "board-store.js",
69
+ "board-actions.js",
70
+ "subagent-runtime.js",
71
+ "api-routes.js",
72
+ "model-tools.js",
73
+ "runtime-hooks.js",
60
74
  "client.js",
61
75
  "chief.js",
76
+ "chief-state.js",
77
+ "chief-models.js",
78
+ "chief-network.js",
79
+ "chief-view.js",
80
+ "chief-archives.js",
81
+ "chief-compaction.js",
82
+ "chief-commands.js",
83
+ "chief-review.js",
84
+ "chief-approvals.js",
62
85
  "chief-executor.js",
63
86
  "auto-continue.js",
64
87
  "archives.js",
88
+ "archive-core.js",
89
+ "archive-cabinets.js",
90
+ "archive-precipitated.js",
91
+ "archive-dossiers.js",
65
92
  "idle-guard.js",
66
93
  "memory.js",
67
94
  "digest.js",
@@ -0,0 +1,629 @@
1
+ /**
2
+ * runtime-hooks.js
3
+ *
4
+ * Cordis plugin lifecycle initialization, board migration, idle guard, auto-continue, routes, and tool registration.
5
+ */
6
+
7
+ import fs from 'node:fs'
8
+ import path from 'node:path'
9
+ import { renderDigest } from './digest.js'
10
+ import { appendMemory, captureTurn } from './memory.js'
11
+ import {
12
+ buildNotice,
13
+ clearCallTrail,
14
+ isPlanWrite,
15
+ noteCallTrail,
16
+ noteIntervention,
17
+ notePlanWrite,
18
+ noteToolCall,
19
+ remainingInterventions,
20
+ shouldGuard,
21
+ } from './idle-guard.js'
22
+ import {
23
+ loadChiefState,
24
+ resolveWorkspaceConfig,
25
+ invalidateChiefModelCatalog,
26
+ buildMessageEnvelope,
27
+ consumePreStepDelta,
28
+ scheduleChiefTurnReview,
29
+ hasValidChiefRiskAck,
30
+ queueChiefApproval,
31
+ appendChiefAuditLog,
32
+ } from './chief.js'
33
+ import { createAutoContinueEngine } from './auto-continue.js'
34
+ import { bootstrapArchivesFromSharedBoard } from './archives.js'
35
+ import { normalizePermissionMode } from './chief-executor.js'
36
+ import {
37
+ newId,
38
+ nowMs,
39
+ emptyBoard,
40
+ CAP_TASK_EVIDENCE,
41
+ reconcileTaskDependencies,
42
+ normalizeNote,
43
+ normalizeBoard,
44
+ pushLog,
45
+ guardLogText,
46
+ } from './board-schema.js'
47
+
48
+ export function createRuntimeHooks(deps) {
49
+
50
+ const boardFile = (...args) => deps.boardFile(...args)
51
+ const boardFileFor = (...args) => deps.boardFileFor(...args)
52
+ const boardForSession = (...args) => deps.boardForSession(...args)
53
+ const boardTool = (...args) => deps.boardTool(...args)
54
+ const boundariesTool = (...args) => deps.boundariesTool(...args)
55
+ const clearPending = (...args) => deps.clearPending(...args)
56
+ const clearPendingDeploy = (...args) => deps.clearPendingDeploy(...args)
57
+ const collectDigestArchiveContext = (...args) => deps.collectDigestArchiveContext(...args)
58
+ const deployStateToTargetChief = (...args) => deps.deployStateToTargetChief(...args)
59
+ const getSessionCwd = (...args) => deps.getSessionCwd(...args)
60
+ const getSubagentRoster = (...args) => deps.getSubagentRoster(...args)
61
+ const handoffTool = (...args) => deps.handoffTool(...args)
62
+ const injectInto = (...args) => deps.injectInto(...args)
63
+ const linkedPeersForSession = (...args) => deps.linkedPeersForSession(...args)
64
+ const loadBoard = (...args) => deps.loadBoard(...args)
65
+ const makeChiefDeps = (...args) => deps.makeChiefDeps(...args)
66
+ const memoryTool = (...args) => deps.memoryTool(...args)
67
+ const pendingFile = (...args) => deps.pendingFile(...args)
68
+ const probeSubagentSupport = (...args) => deps.probeSubagentSupport(...args)
69
+ const readPending = (...args) => deps.readPending(...args)
70
+ const readPendingDeploy = (...args) => deps.readPendingDeploy(...args)
71
+ const refreshSubagentTree = (...args) => deps.refreshSubagentTree(...args)
72
+ const resolveAgentIdentity = (...args) => deps.resolveAgentIdentity(...args)
73
+ const resolveEffectiveHandoff = (...args) => deps.resolveEffectiveHandoff(...args)
74
+ const resolveRootSessionId = (...args) => deps.resolveRootSessionId(...args)
75
+ const routeTable = (...args) => deps.routeTable(...args)
76
+ const saveBoard = (...args) => deps.saveBoard(...args)
77
+ const sessionBoardFile = (...args) => deps.sessionBoardFile(...args)
78
+ const syncObjective = (...args) => deps.syncObjective(...args)
79
+ const syncPlanFromTodos = (...args) => deps.syncPlanFromTodos(...args)
80
+ const syncSubagentToolCall = (...args) => deps.syncSubagentToolCall(...args)
81
+ const withBoardLock = (...args) => deps.withBoardLock(...args)
82
+
83
+ /* ------------------------------------------------------------------------ apply */
84
+
85
+ function apply(ctx) {
86
+ const runtime = {
87
+ get(name) {
88
+ try {
89
+ return typeof ctx.get === 'function' ? ctx.get(name) : undefined
90
+ } catch {
91
+ return undefined
92
+ }
93
+ },
94
+ }
95
+ deps.hostState.activeRuntime = runtime
96
+
97
+ // 1) Not inflated, not reminded: every prompt assembly carries a small digest,
98
+ // so a compacted transcript does not take the objective and the open steps
99
+ // away from the next turn.
100
+ // Migrate a pre-split shared board into per-session boards ONCE: the first
101
+ // session that claims it copies it, so anchors are not lost and no session
102
+ // silently inherits another's tasks.
103
+ ;(function migrateSharedBoard() {
104
+ try {
105
+ const sharedFile = boardFile()
106
+ const dir = path.join(path.dirname(sharedFile), 'boards')
107
+ const flag = path.join(path.dirname(sharedFile), '.split-done')
108
+ if (fs.existsSync(flag)) return
109
+ let stat
110
+ try { stat = fs.statSync(sharedFile) } catch { return }
111
+ if (!stat || !stat.isFile()) return
112
+ const board = normalizeBoard(JSON.parse(fs.readFileSync(sharedFile, 'utf8')))
113
+ const touched = Object.keys(board.sessions || {})
114
+ const targets = new Set(touched)
115
+ // Every note/task that carries a session id also seeds that board; a
116
+ // session with only a heartbeat still gets the shared anchors.
117
+ for (const note of board.notes || []) if (note.session) targets.add(String(note.session))
118
+ for (const task of board.tasks || []) if (task.session) targets.add(String(task.session))
119
+ // No owner at all → keep it as the shared/anchor board only.
120
+ if (!targets.size) return
121
+ const anchors = (board.notes || []).filter(note => (note.tags || []).includes('anchor'))
122
+ fs.mkdirSync(dir, { recursive: true })
123
+ for (const sid of targets) {
124
+ const dst = sessionBoardFile(sid)
125
+ if (fs.existsSync(dst)) continue
126
+ // Seed only what is machine-wide: settings, the heartbeat table, the log
127
+ // tail and the shared anchors. NOT the objective, NOT the plan, NOT the
128
+ // bounds — those stay on the shared board and are inherited on every
129
+ // read (boardForSession), so freezing a copy into each session would
130
+ // recreate exactly the cross-session pollution the split removed.
131
+ const seed = emptyBoard()
132
+ seed.settings = board.settings || seed.settings
133
+ seed.notes = anchors
134
+ seed.sessions = board.sessions || {}
135
+ seed.log = board.log || []
136
+ fs.writeFileSync(dst, JSON.stringify(seed, null, 2), 'utf8')
137
+ }
138
+ fs.writeFileSync(flag, JSON.stringify({ at: nowMs(), seeded: [...targets] }, null, 2), 'utf8')
139
+ // Shrink the shared board to the machine-wide facts only: the objective,
140
+ // the plan, the bounds and the anchors are what a new session inherits,
141
+ // while tasks/notes/memory stay per-session.
142
+ withBoardLock(sharedFile, () => {
143
+ const slim = emptyBoard()
144
+ slim.settings = board.settings || slim.settings
145
+ slim.bounds = board.bounds || slim.bounds
146
+ slim.notes = anchors
147
+ slim.sessions = board.sessions || {}
148
+ slim.log = board.log || []
149
+ slim.objective = board.objective
150
+ slim.objectiveBy = board.objectiveBy
151
+ slim.objectiveAt = board.objectiveAt
152
+ slim.plan = board.plan
153
+ saveBoard(slim, sharedFile)
154
+ })
155
+ } catch {}
156
+ })()
157
+
158
+ // Precipitate legacy shared-board engineering notes into `archives.json` ONCE
159
+ // (after creating `board.pre-archive-backup.json`), sealing them as cold lazy-loaded dossiers.
160
+ bootstrapArchivesFromSharedBoard({
161
+ sharedFile: boardFile(),
162
+ loadBoard,
163
+ saveBoard,
164
+ pushLog,
165
+ })
166
+
167
+ const isRootStopped = (rootKey, sid) => {
168
+ try {
169
+ const st = loadChiefState()
170
+ const rk = resolveRootSessionId(rootKey || sid) || rootKey || sid
171
+ const cfg = resolveWorkspaceConfig(st, rk)
172
+ return Boolean(cfg.stopped || cfg.paceMode === 'stopped')
173
+ } catch {
174
+ return false
175
+ }
176
+ }
177
+
178
+ const autoContinue = createAutoContinueEngine({
179
+ createMessage: (text, sourceKind) => buildMessageEnvelope(text, sourceKind),
180
+ getAgent: async (sid) => {
181
+ try {
182
+ const agents = runtime && runtime.get ? runtime.get('agents') : null
183
+ const direct = agents && typeof agents.get === 'function' ? agents.get(sid) : null
184
+ if (direct) return direct
185
+ const ctrl = runtime && runtime.get ? runtime.get('sessionController') : null
186
+ if (ctrl && typeof ctrl.resolveAgent === 'function') {
187
+ const resolved = await ctrl.resolveAgent(sid)
188
+ if (resolved && resolved.agent) return resolved.agent
189
+ }
190
+ return null
191
+ } catch {
192
+ return null
193
+ }
194
+ },
195
+ isChiefStopped: (rootId, sid) => isRootStopped(rootId, sid),
196
+ canAutoContinue: ({ sessionId, rootId, trigger, detail }) => {
197
+ try {
198
+ const key = rootId || sessionId || 'global'
199
+ const state = loadChiefState()
200
+ const ws = state && state.workspaces && state.workspaces[key] ? state.workspaces[key] : null
201
+ const effCfg = resolveWorkspaceConfig(state, key)
202
+ const hasAck = hasValidChiefRiskAck(ws)
203
+ const mode = normalizePermissionMode(effCfg && effCfg.permissionMode, {
204
+ requireAck: true,
205
+ hasChiefRiskAck: hasAck,
206
+ })
207
+ if (mode === 'advisor') {
208
+ return { allowed: false, skipped: 'advisor-readonly', logMessage: 'L0 顾问模式(只读):禁止自动向主对话续跑' }
209
+ }
210
+ if (mode === 'assistant') {
211
+ return { allowed: false, skipped: 'assistant-no-workflow', logMessage: 'L1 助手模式:仅维护参谋系统,跳过主对话断线自动续跑' }
212
+ }
213
+ if (mode === 'strategist') {
214
+ const apr = queueChiefApproval(key, {
215
+ category: 'main_workflow',
216
+ operationLabel: '断线自动续跑主对话',
217
+ targetLabel: '主对话 (@lead)',
218
+ reason: `检测到会话中断或未收口(${trigger}),L2 参谋模式需您允许后再发送续跑指令`,
219
+ impact: '点击「允许本次操作」后将立即唤醒主对话继续推进当前任务',
220
+ preview: detail ? String(detail).slice(0, 220) : `触发原因:${trigger}`,
221
+ dedupeKey: `autocont:${sessionId}:${trigger}:${Math.floor(Date.now() / 15_000)}`,
222
+ kind: 'auto_continue',
223
+ payload: { sessionId, trigger, detail: detail || '' },
224
+ by: 'auto-continue',
225
+ })
226
+ appendChiefAuditLog(key, {
227
+ mode,
228
+ stage: 'permission_gate',
229
+ decision: 'pending_approval',
230
+ operation: '断线自动续跑主对话',
231
+ target: sessionId,
232
+ reason: `触发源:${trigger}`,
233
+ outcome: 'pending',
234
+ by: 'auto-continue',
235
+ })
236
+ return {
237
+ allowed: false,
238
+ skipped: 'pending-approval',
239
+ approvalId: apr && apr.id,
240
+ logMessage: `L2 参谋模式:已提交断线续跑逐项授权弹窗(${trigger})`,
241
+ }
242
+ }
243
+ return { allowed: true }
244
+ } catch {
245
+ return { allowed: false, skipped: 'permission-error' }
246
+ }
247
+ },
248
+ resolveRootSessionId: (sid) => resolveRootSessionId(sid) || sid,
249
+ onLog: (sid, msg) => {
250
+ try {
251
+ const rootId = resolveRootSessionId(sid) || sid
252
+ if (!rootId) return
253
+ const file = boardFileFor(rootId)
254
+ withBoardLock(file, () => {
255
+ const board = loadBoard(file)
256
+ pushLog(board, `🔄 断线续跑:${msg}`, 'chief', sid)
257
+ saveBoard(board, file)
258
+ })
259
+ } catch {}
260
+ },
261
+ })
262
+ deps.hostState.activeAutoContinue = autoContinue
263
+ ctx.effect(() => () => {
264
+ if (deps.hostState.activeAutoContinue === autoContinue) deps.hostState.activeAutoContinue = null
265
+ autoContinue.dispose()
266
+ }, 'dsh-chief: auto-continue cleanup')
267
+
268
+ ctx.inject(['llm'], llmCtx => {
269
+ const ownLlm = (llmCtx && llmCtx.llm) || (llmCtx && llmCtx.get ? llmCtx.get('llm') : null)
270
+ if (ownLlm) deps.hostState.activeLlm = ownLlm
271
+ llmCtx.effect(() => () => {
272
+ if (deps.hostState.activeLlm === ownLlm) deps.hostState.activeLlm = null
273
+ }, 'dsh-chief: chief llm service')
274
+ })
275
+ ctx.on?.('llm/adapters-updated', () => invalidateChiefModelCatalog())
276
+ ctx.on?.('settings/document-updated', () => invalidateChiefModelCatalog())
277
+
278
+ ctx.effect(() => ctx.on('agent/pre-step', async ({ agent, signal }, next) => {
279
+ const decision = await next()
280
+ try {
281
+ if (!decision || decision.kind === 'reject' || signal?.aborted || !Array.isArray(decision.messages)) {
282
+ return decision
283
+ }
284
+ const deltaMsg = await consumePreStepDelta(makeChiefDeps(runtime), agent)
285
+ if (!deltaMsg) return decision
286
+ return { ...decision, messages: [deltaMsg, ...decision.messages] }
287
+ } catch {
288
+ return decision
289
+ }
290
+ }), 'dsh-chief: chief pre-step delta')
291
+
292
+ ctx.inject(['systemPrompt'], spCtx => {
293
+ const systemPrompt = spCtx.get ? spCtx.get('systemPrompt') : undefined
294
+ if (!systemPrompt || typeof systemPrompt.section !== 'function') return
295
+ // Always on, and always FIRST. A model that only meets the chief after
296
+ // ten thousand tokens of other context writes for a while and forgets it,
297
+ // which is exactly the failure the operator kept hitting. The section is
298
+ // registered unconditionally so the board is in front of the model from the
299
+ // first turn; -10000 sorts ahead of every built-in section (they use small
300
+ // positive orders, and equal orders fall back to name order), and the host
301
+ // only requires the order to be a finite number.
302
+ const fallbackAgentId = spCtx && spCtx.agent && spCtx.agent.id ? String(spCtx.agent.id)
303
+ : (spCtx && spCtx.get && spCtx.get('agent') && spCtx.get('agent').id ? String(spCtx.get('agent').id) : '')
304
+ spCtx.effect(() => systemPrompt.section({
305
+ name: 'dsh-chief',
306
+ order: -10000,
307
+ text: (promptCtx) => {
308
+ const liveAgent = (promptCtx && promptCtx.agent) || (spCtx && spCtx.agent) || null
309
+ const curId = liveAgent && liveAgent.id ? String(liveAgent.id) : fallbackAgentId
310
+ const rootId = resolveRootSessionId(curId, liveAgent) || curId
311
+ let teamTasks
312
+ try {
313
+ const svc = runtime.get('agentTeams')
314
+ if (svc && typeof svc.listTasks === 'function' && liveAgent) {
315
+ teamTasks = svc.listTasks(liveAgent)
316
+ }
317
+ } catch {}
318
+ const board = boardForSession(boardFileFor(rootId))
319
+ const agentIdentity = resolveAgentIdentity(runtime, curId, liveAgent)
320
+ const subagents = getSubagentRoster(runtime, rootId, board)
321
+ const linked = linkedPeersForSession(runtime, rootId || 'global')
322
+ const archCtx = collectDigestArchiveContext(runtime, rootId, board.activeCabinetId)
323
+ if (rootId) refreshSubagentTree(runtime, rootId, board).catch(() => {})
324
+ return renderDigest(board, {
325
+ teamTasks,
326
+ agentIdentity,
327
+ subagents,
328
+ linkedPeersCount: linked.linkedPeersCount,
329
+ linkedPeersProgress: linked.linkedPeersProgress,
330
+ takenOutArchives: archCtx.takenOutArchives,
331
+ sessionArchiveBriefs: archCtx.sessionArchiveBriefs,
332
+ smartCompactActive: archCtx.smartCompactActive,
333
+ chiefPermissionMode: archCtx.chiefPermissionMode,
334
+ })
335
+ },
336
+ }), 'dsh-chief: prompt digest')
337
+ })
338
+
339
+ // 2) Whatever plan or subagent delegation the model executed is mirrored into the board.
340
+ ctx.effect(() => ctx.on('tools/result', (exec, result) => {
341
+ try {
342
+ if (!exec || !result || result.isError) return
343
+ const caller = exec.agent || null
344
+ const sessionId = caller && caller.id ? String(caller.id) : ''
345
+ const rootId = resolveRootSessionId(sessionId, caller) || sessionId
346
+ if (exec.name === 'todo_write') syncPlanFromTodos(exec.arguments, rootId)
347
+ else if (exec.name === 'create_goal' || exec.name === 'update_goal') syncObjective(exec.name, exec.arguments, rootId)
348
+ else if (exec.name === 'subagent' || exec.name === 'subagent_fork' || exec.name === 'send_message' || exec.name === 'interrupt_agent') {
349
+ syncSubagentToolCall(runtime, exec, result)
350
+ }
351
+ } catch {}
352
+ }), 'dsh-chief: plan & subagent mirror')
353
+
354
+ // 2b) A transferred packet + staged Chief deployment waits for one new Session.
355
+ ctx.effect(() => ctx.on('agent/created', async payload => {
356
+ try {
357
+ const agent = payload && payload.agent
358
+ if (!agent || !agent.id) return
359
+ const id = String(agent.id)
360
+
361
+ const pendingDeploy = readPendingDeploy()
362
+ if (pendingDeploy && pendingDeploy.fromSessionId && pendingDeploy.fromSessionId !== id) {
363
+ clearPendingDeploy()
364
+ try {
365
+ deployStateToTargetChief(runtime, {
366
+ fromSessionId: pendingDeploy.fromSessionId,
367
+ toSessionId: id,
368
+ archiveTransferPolicy: pendingDeploy.archiveTransferPolicy || 'none',
369
+ archiveDrawer: pendingDeploy.archiveDrawer || '',
370
+ toCabinetId: pendingDeploy.toCabinetId || '',
371
+ customNote: pendingDeploy.customNote || '',
372
+ })
373
+ } catch {}
374
+ }
375
+
376
+ const pending = readPending()
377
+ if (!pending) return
378
+ const delivered = await injectInto(agent, pending.text)
379
+ if (delivered.ok) clearPending()
380
+ const file = boardFileFor(id)
381
+ const short = id.replace(/^session-/, '').slice(0, 8)
382
+ withBoardLock(file, () => {
383
+ const board = loadBoard(file)
384
+ pushLog(
385
+ board,
386
+ (delivered.ok ? '交接单已被本会话领取 ' : '交接单投放失败(' + delivered.error + '),仍待领取:') + short,
387
+ 'agent',
388
+ id,
389
+ )
390
+ // An injected packet only reaches the conversation, so the board the
391
+ // claimant actually opens would look empty. Keep the packet itself on
392
+ // that board, as a note, so the next reader sees the handover there.
393
+ if (delivered.ok) {
394
+ const title = '接手:' + (String(pending.text).split('\n')[0] || '上一段对话').replace(/^#\s*交接单\s*·\s*/, '').slice(0, 120)
395
+ const body = String(pending.text).slice(0, 6000)
396
+ const same = board.notes.find(note => note.title === title)
397
+ if (same) {
398
+ same.body = body
399
+ same.updatedAt = nowMs()
400
+ same.session = id
401
+ } else {
402
+ board.notes.unshift(normalizeNote({ id: newId('n'), title, body, tags: ['handoff'], by: 'agent', session: id }))
403
+ }
404
+ }
405
+ return saveBoard(board, file)
406
+ })
407
+ } catch {}
408
+ }), 'dsh-chief: deliver pending transfer')
409
+
410
+ // 2c) Incremental record of what each turn actually did + Auto-Continue detection
411
+ // on interruptions / transient failures / empty outputs (unless Chief is stopped).
412
+ ctx.effect(() => ctx.on('session/event', (session, event) => {
413
+ try {
414
+ if (!event || !session || !session.id) return
415
+ const id = String(session.id)
416
+ if (event.type === 'tool/call' && event.data) {
417
+ const turn = event.data.turn
418
+ noteToolCall(id, turn)
419
+ if (isPlanWrite(event.data.name, event.data.arguments)) notePlanWrite(id, turn)
420
+ noteCallTrail(id, event.data.name, event.data.arguments)
421
+ }
422
+ autoContinue.onSessionEvent(session, event)
423
+
424
+ if (event.type === 'turn/end') {
425
+ const rawReason = event.data && event.data.reason
426
+ const reason = String(rawReason && typeof rawReason === 'object' ? (rawReason.kind || '') : (rawReason || '')).toLowerCase()
427
+ const nestedReason = String(rawReason && typeof rawReason === 'object' && rawReason.reason && typeof rawReason.reason === 'object' ? (rawReason.reason.kind || '') : '').toLowerCase()
428
+ const isStoppedByUserOrPolicy = reason === 'aborted' || reason === 'blocked' || nestedReason === 'aborted' || nestedReason === 'blocked'
429
+ const turnNum = Number(event.data && event.data.turn)
430
+ const steerKey = `${id}:${turnNum}`
431
+ const steeredAt = deps.hostState.autoSteeredTurns.get(steerKey) || 0
432
+ if (steeredAt) deps.hostState.autoSteeredTurns.delete(steerKey)
433
+ if (!isStoppedByUserOrPolicy && !(steeredAt && Date.now() - steeredAt < 30_000)) {
434
+ const rootId = resolveRootSessionId(id) || id
435
+ if (!isRootStopped(rootId, id)) {
436
+ const agents = runtime && runtime.get ? runtime.get('agents') : null
437
+ const liveAgent = agents && typeof agents.get === 'function' ? agents.get(id) : null
438
+ if (liveAgent) {
439
+ scheduleChiefTurnReview(makeChiefDeps(runtime), { agent: liveAgent, sessionId: id, turn: event.data && event.data.turn })
440
+ }
441
+ }
442
+ }
443
+ }
444
+ } catch {}
445
+ }), 'dsh-chief: tool call ledger & auto-continue')
446
+
447
+ // 3) One heartbeat per finished turn: which Sessions are still warm — and the
448
+ // idle guard: a turn that closes with a short answer, no tool call, and open
449
+ // work still on the board gets one more step instead of closing.
450
+ ctx.effect(() => ctx.on('agent/turn-stopping', payload => {
451
+ let id = ''
452
+ try {
453
+ const agent = payload && payload.agent
454
+ id = agent && agent.id ? String(agent.id) : ''
455
+ if (!id) return
456
+
457
+ const turn = Number(payload && payload.turn)
458
+ const file = boardFileFor(id)
459
+
460
+ // One critical section: heartbeat, memory line and the guard verdict all
461
+ // read and rewrite the same board, so a route landing mid-way must not be
462
+ // able to overwrite any of them.
463
+ withBoardLock(file, () => {
464
+ const board = loadBoard(file)
465
+
466
+ // Heartbeat, inlined so the three edits share one load and one save.
467
+ try {
468
+ const entry = board.sessions[id] || { lastSeen: 0, cwd: '', turns: 0 }
469
+ entry.lastSeen = nowMs()
470
+ entry.turns = (entry.turns || 0) + 1
471
+ const resolvedCwd = getSessionCwd(runtime, id)
472
+ if (resolvedCwd) entry.cwd = resolvedCwd
473
+ board.sessions[id] = entry
474
+ const ids = Object.keys(board.sessions)
475
+ if (ids.length > 40) {
476
+ ids.sort((a, b) => (board.sessions[a].lastSeen || 0) - (board.sessions[b].lastSeen || 0))
477
+ for (const stale of ids.slice(0, ids.length - 40)) delete board.sessions[stale]
478
+ }
479
+ } catch {}
480
+
481
+ // Memory first: every finished turn leaves one line in the board's memory
482
+ // before the guard can decide anything, so asking "what did we do" works
483
+ // even when the turn was idle.
484
+ let capturedEntry = null
485
+ const identity = resolveAgentIdentity(runtime, id, agent)
486
+ try {
487
+ capturedEntry = captureTurn(agent && agent.session, turn, null)
488
+ if (capturedEntry) {
489
+ capturedEntry.session = id
490
+ if (identity && identity.isChild && identity.self) {
491
+ capturedEntry.by = identity.self
492
+ }
493
+ appendMemory(board, capturedEntry)
494
+ }
495
+ } catch {}
496
+
497
+ // If a child subagent just finished its turn, auto-settle its assigned
498
+ // 'doing' task on the shared root board and unlock downstream dependencies.
499
+ if (identity && identity.isChild) {
500
+ const selfName = String(identity.self || '').toLowerCase()
501
+ const shortSelf = selfName.split('/').pop()
502
+ let settledCount = 0
503
+ for (const task of board.tasks || []) {
504
+ if (!task || task.status !== 'doing') continue
505
+ const tSub = String(task.subagent || '').toLowerCase()
506
+ const tOwn = String(task.owner || '').toLowerCase()
507
+ const matched = (selfName && (tSub === selfName || tOwn === selfName || tSub.split('/').pop() === shortSelf || tOwn.split('/').pop() === shortSelf))
508
+ || (task.session && String(task.session) === id)
509
+ if (matched && capturedEntry && capturedEntry.text) {
510
+ task.status = 'done'
511
+ if (!task.evidence) {
512
+ task.evidence = String(capturedEntry.title || capturedEntry.text).slice(0, CAP_TASK_EVIDENCE)
513
+ }
514
+ task.updatedAt = nowMs()
515
+ settledCount += 1
516
+ pushLog(board, '✅ 子代理 ' + identity.self + ' 完成任务 #' + task.id + '「' + task.title.slice(0, 36) + '」', identity.self, id)
517
+ }
518
+ }
519
+ if (settledCount > 0) {
520
+ reconcileTaskDependencies(board, identity.self, id)
521
+ }
522
+ saveBoard(board, file)
523
+ const childRoot = resolveRootSessionId(id, agent) || id
524
+ if (!isRootStopped(childRoot, id)) {
525
+ scheduleChiefTurnReview(makeChiefDeps(runtime), { agent, sessionId: id, turn })
526
+ }
527
+ return
528
+ }
529
+
530
+ const rootId = resolveRootSessionId(id, agent) || id
531
+ if (isRootStopped(rootId, id)) {
532
+ saveBoard(board, file)
533
+ return
534
+ }
535
+
536
+ // autoInject is machine-wide on the shared board; guardIdle follows the
537
+ // same rule so one switch turns the guard off everywhere.
538
+ const shared = loadBoard(boardFile())
539
+ const settings = { ...(board.settings || {}), ...(shared.settings || {}) }
540
+ const verdict = shouldGuard({ board, session: agent && agent.session, sessionId: id, turn, settings })
541
+ if (!verdict) {
542
+ saveBoard(board, file)
543
+ scheduleChiefTurnReview(makeChiefDeps(runtime), { agent, sessionId: id, turn })
544
+ return
545
+ }
546
+
547
+ if (typeof agent.steer !== 'function') {
548
+ pushLog(board, '空转拦截:这个 agent 没有 steer 方法,转由断线续跑模块跟进', 'guard', id)
549
+ saveBoard(board, file)
550
+ autoContinue.notifyIdleOrInterrupt(id, { kind: 'idle-stall', reason: verdict.reason || '' })
551
+ return
552
+ }
553
+
554
+ // Steer inside the lock: the notice is queued before another request can
555
+ // observe a board that claims an intervention that never happened.
556
+ const notice = buildNotice({ ...verdict, board })
557
+ agent.steer(notice)
558
+ deps.hostState.autoSteeredTurns.set(`${id}:${turn}`, Date.now())
559
+ if (deps.hostState.autoSteeredTurns.size > 120) {
560
+ const oldest = deps.hostState.autoSteeredTurns.keys().next().value
561
+ if (oldest) deps.hostState.autoSteeredTurns.delete(oldest)
562
+ }
563
+ noteIntervention(id, turn)
564
+ // Clear the trail only once the steer landed: a loop that survived a
565
+ // failed steer deserves the next nudge, not a silent reset.
566
+ if (verdict.kind === 'loop') clearCallTrail(id)
567
+ pushLog(board, guardLogText(verdict, turn, remainingInterventions(id, settings)), 'guard', id)
568
+
569
+ // Auto-handoff: when the guard has spent its last intervention and the
570
+ // session still has open work, the turn is not idle — it is stuck in a
571
+ // context that has grown too long to be productive. Generate the
572
+ // handover packet right now so the next Session (or a manual reopen)
573
+ // inherits it instead of a blank board. The steer already fired above
574
+ // tells the model to wrap up; this packet is what the next one reads.
575
+ if (remainingInterventions(id, settings) === 0) {
576
+ try {
577
+ const packet = resolveEffectiveHandoff(runtime, id, board).text
578
+ const pendingFile_ = pendingFile()
579
+ fs.writeFileSync(pendingFile_, JSON.stringify({ text: packet, at: nowMs(), from: id }))
580
+ pushLog(board, '上下文压力:干预计数耗尽,交接单已自动生成并放入待领取', 'handoff', id)
581
+ } catch (handoffError) {
582
+ pushLog(board, '自动交接单生成失败:' + String(handoffError && handoffError.message ? handoffError.message : handoffError).slice(0, 160), 'handoff', id)
583
+ }
584
+ }
585
+ saveBoard(board, file)
586
+ })
587
+ } catch (error) {
588
+ // Never let the guard break the turn boundary.
589
+ try {
590
+ if (!id) return
591
+ const file = boardFileFor(id)
592
+ withBoardLock(file, () => {
593
+ const board = loadBoard(file)
594
+ pushLog(board, '空转拦截自身出错:' + String(error && error.message ? error.message : error).slice(0, 160), 'guard', id)
595
+ saveBoard(board, file)
596
+ })
597
+ } catch {}
598
+ }
599
+ }), 'dsh-chief: session heartbeat and idle guard')
600
+
601
+ // Routes: the browser half of this same package calls them same-origin.
602
+ ctx.inject(['webServer'], webCtx => {
603
+ for (const route of routeTable(runtime)) {
604
+ webCtx.effect(() => webCtx.webServer.register(route), 'dsh-chief: route ' + route.path)
605
+ }
606
+ })
607
+
608
+ // Model tools: the cross-Session half of the same operations.
609
+ ctx.inject(['tools'], toolCtx => {
610
+ for (const tool of [boardTool(runtime), boundariesTool(runtime), handoffTool(runtime), memoryTool(runtime)]) {
611
+ toolCtx.effect(() => toolCtx.tools.register(tool), 'dsh-chief: tool ' + tool.name)
612
+ }
613
+ })
614
+
615
+ // Runtime capability probe for DSH >= 0.2.2-rc.2 named subagent APIs
616
+ ctx.inject(['subagents'], () => {
617
+ const compat = probeSubagentSupport(runtime)
618
+ if (compat.present && !compat.namedSubagentsSupported) {
619
+ try {
620
+ console.warn('[dsh-chief] ' + compat.warning)
621
+ } catch {}
622
+ }
623
+ })
624
+ }
625
+
626
+ return {
627
+ apply,
628
+ }
629
+ }