dsh-chief 1.2.0 → 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/model-tools.js ADDED
@@ -0,0 +1,755 @@
1
+ /**
2
+ * model-tools.js
3
+ *
4
+ * Model tool definitions and execution handlers (chief_board, chief_memory, chief_boundaries, chief_handoff).
5
+ */
6
+
7
+ import { MEMORY_SECTIONS } from './memory.js'
8
+ import {
9
+ listPeerDirectory,
10
+ deliverCrossMessage,
11
+ requestSmartCompactFromLead,
12
+ proposeBoundToChief,
13
+ readMailboxForAgent,
14
+ requestChiefElevation,
15
+ CHIEF_PERMISSION_META,
16
+ } from './chief.js'
17
+ import { normalizePermissionMode } from './chief-executor.js'
18
+ import {
19
+ STATUSES,
20
+ PRIORITIES,
21
+ nowMs,
22
+ emptyBoard,
23
+ str,
24
+ asBool,
25
+ normalizeBoundFieldName,
26
+ BOUND_CAP,
27
+ pushLog,
28
+ summary,
29
+ } from './board-schema.js'
30
+
31
+ export function createModelTools(deps) {
32
+
33
+ const boardFileFor = (...args) => deps.boardFileFor(...args)
34
+ const boardForSession = (...args) => deps.boardForSession(...args)
35
+ const boundaries = (...args) => deps.boundaries(...args)
36
+ const executeSubagentAction = (...args) => deps.executeSubagentAction(...args)
37
+ const fetchTeamTasks = (...args) => deps.fetchTeamTasks(...args)
38
+ const loadBoard = (...args) => deps.loadBoard(...args)
39
+ const makeChiefDeps = (...args) => deps.makeChiefDeps(...args)
40
+ const refreshSubagentTree = (...args) => deps.refreshSubagentTree(...args)
41
+ const resolveAgentIdentity = (...args) => deps.resolveAgentIdentity(...args)
42
+ const resolveEffectiveHandoff = (...args) => deps.resolveEffectiveHandoff(...args)
43
+ const resolveRootSessionId = (...args) => deps.resolveRootSessionId(...args)
44
+ const runAction = (...args) => deps.runAction(...args)
45
+ const saveBoard = (...args) => deps.saveBoard(...args)
46
+ const transferChief = (...args) => deps.transferChief(...args)
47
+ const withBoardLock = (...args) => deps.withBoardLock(...args)
48
+
49
+ /* ----------------------------------------------------------------------- tools */
50
+
51
+ const BOARD_PARAMETERS = {
52
+ type: 'object',
53
+ properties: {
54
+ action: {
55
+ type: 'string',
56
+ enum: [
57
+ 'snapshot',
58
+ 'graph.plan',
59
+ 'task.batch',
60
+ 'task.add',
61
+ 'task.update',
62
+ 'task.claim',
63
+ 'task.release',
64
+ 'task.remove',
65
+ 'task.verify',
66
+ 'task.dispatch',
67
+ 'team.steer',
68
+ 'team.interrupt',
69
+ 'team.list',
70
+ 'mail.send',
71
+ 'mail.inbox',
72
+ 'plan.set',
73
+ 'objective.set',
74
+ 'mode.set',
75
+ 'bounds.propose',
76
+ 'bounds.add',
77
+ 'bounds.pin',
78
+ 'bounds.remove',
79
+ 'bounds.edit',
80
+ 'bounds.consolidate',
81
+ 'bounds.set',
82
+ 'settings.set',
83
+ 'handoff.mark',
84
+ 'cursor.set',
85
+ 'log.add',
86
+ 'note.add',
87
+ 'note.write',
88
+ 'note.pin',
89
+ 'note.unpin',
90
+ 'note.remove',
91
+ 'note.read',
92
+ 'archive.search',
93
+ 'archive.read',
94
+ 'archive.save',
95
+ 'context.compact',
96
+ 'permission.request',
97
+ 'memory.add',
98
+ 'memory.remove',
99
+ 'memory.ask',
100
+ ],
101
+ description:
102
+ 'Board operation (MUST be called whenever recording tasks/status/conclusions or relaying messages; plain text alone does NOT update the board or notify peers). '
103
+ + 'Use "graph.plan" (or "task.batch") to plan a hierarchical/DAG task graph in one call (supports parentId, blockedBy, owner/subagent, intent, evidence). '
104
+ + 'Use "task.dispatch" to spawn or message a subagent, "team.steer" to steer a subagent, and "mail.send" to relay messages across lead/subagents/sessions. '
105
+ + 'Use "bounds.propose" (field: "forbidden"|"allowed"|"notes", item, reason) when hitting a permission/sandbox/environment wall or summarizing boundaries ("allowed" = 必做事项, "forbidden" = 禁止红线, "notes" = 注意事项) so DSH Chief can request user approval. '
106
+ + 'Use "permission.request" (targetMode: "assistant"|"strategist"|"chief", reason) when requesting higher DSH Chief permission tier from the user. '
107
+ + 'Session Engineering Archives ("archive.search", "archive.read", "archive.save") access ONLY the current conversation\'s Session Cabinet (never Global Cabinet or unflipped Precipitated cold vault). '
108
+ + 'When Smart Co-Managed Compaction ("✦ 智选") is enabled, call "context.compact" with a concise phase-summary in "text" at clean phase boundaries to ask DSH Chief to harvest details into this session\'s cabinet and compact.',
109
+ },
110
+ tasks: {
111
+ type: 'array',
112
+ description: 'graph.plan / task.batch: array of task nodes to create or update in the DAG. Items may reference each other via id/key in parentId and blockedBy.',
113
+ items: {
114
+ type: 'object',
115
+ properties: {
116
+ id: { type: 'string', description: 'Task id or temporary symbolic key (e.g. "t1", "api-design") referenced by parentId or blockedBy.' },
117
+ title: { type: 'string', description: 'Short task title.' },
118
+ parentId: { type: 'string', description: 'Parent task id/key for hierarchical decomposition.' },
119
+ blockedBy: { type: 'array', items: { type: 'string' }, description: 'Upstream task ids/keys that must finish (done) before this task unlocks.' },
120
+ owner: { type: 'string', description: 'Assigned subagent name (e.g. "researcher", "coder", "verifier") or owner.' },
121
+ subagent: { type: 'string', description: 'Subagent name to bind to this task.' },
122
+ preset: { type: 'string', description: 'Optional subagent provider/preset ("spawn", "fork", or preset id).' },
123
+ intent: { type: 'string', description: 'Why this task exists / goal.' },
124
+ evidence: { type: 'string', description: 'Verification criteria (before done) or verification proof (when done).' },
125
+ note: { type: 'string', description: 'Detailed notes or context.' },
126
+ priority: { type: 'string', enum: PRIORITIES },
127
+ status: { type: 'string', enum: STATUSES },
128
+ assumption: { type: 'string', description: 'Optional assumption to track and verify.' },
129
+ },
130
+ required: ['title'],
131
+ additionalProperties: false,
132
+ },
133
+ },
134
+ replace: {
135
+ type: 'boolean',
136
+ description: 'graph.plan: when true, replaces existing tasks instead of merging.',
137
+ },
138
+ agent: {
139
+ type: 'string',
140
+ description: 'task.dispatch / team.steer / team.interrupt: target subagent name (e.g. "coder", "reviewer").',
141
+ },
142
+ subagent: {
143
+ type: 'string',
144
+ description: 'Alias for agent/owner on task operations.',
145
+ },
146
+ provider: {
147
+ type: 'string',
148
+ enum: ['spawn', 'fork'],
149
+ description: 'task.dispatch: subagent provider ("spawn" for fresh context, "fork" to inherit conversation history). Default "spawn".',
150
+ },
151
+ preset: {
152
+ type: 'string',
153
+ description: 'task.dispatch / task.add: optional agent_preset for the child subagent.',
154
+ },
155
+ prompt: {
156
+ type: 'string',
157
+ description: 'task.dispatch / team.steer: extra instructions or steering message delivered to the subagent.',
158
+ },
159
+ message: {
160
+ type: 'string',
161
+ description: 'team.steer: message to deliver to the target subagent.',
162
+ },
163
+ force: {
164
+ type: 'boolean',
165
+ description: 'task.dispatch: when true, dispatch even if upstream blockedBy tasks are not done yet.',
166
+ },
167
+ mode: {
168
+ type: 'string',
169
+ enum: ['plan', 'goal'],
170
+ description: 'mode.set: how this board is run. plan = a list of steps being ticked off. goal = one persistent objective steered toward.',
171
+ },
172
+ id: { type: 'string', description: 'Task id for update/claim/release/remove/dispatch/verify, or archive id for archive.read / archive.save.' },
173
+ noteId: { type: 'string', description: 'Note id for note.write / note.pin / note.unpin / note.remove; omit to create a new note.' },
174
+ archiveId: { type: 'string', description: 'Archive dossier id for archive.read / archive.save (on-demand cold archive lookup/update).' },
175
+ query: { type: 'string', description: 'Keyword query for archive.search (searched only on explicit user demand).' },
176
+ folder: { type: 'string', description: 'Filing cabinet drawer id for archive.search / archive.save (coords / incidents / contracts / ops / plans / inbox).' },
177
+ paperclip: { type: 'string', enum: ['gold', 'silver', 'copper'], description: 'Paperclip importance badge for archive.save ("gold" anchor, "silver" verified, "copper" historical).' },
178
+ summary: { type: 'string', description: 'Concise 1-line summary for archive.save.' },
179
+ points: {
180
+ type: 'array',
181
+ description: 'Structured memory points for archive.save: [{ title, cue?, detail }].',
182
+ items: {
183
+ type: 'object',
184
+ properties: {
185
+ id: { type: 'string' },
186
+ title: { type: 'string' },
187
+ cue: { type: 'string' },
188
+ detail: { type: 'string' },
189
+ },
190
+ required: ['title', 'detail'],
191
+ additionalProperties: false,
192
+ },
193
+ },
194
+ step: { type: 'string', description: 'cursor.set: which plan step is open right now, in your own words.' },
195
+ next: { type: 'string', description: 'cursor.set: the very next action — concrete enough to execute without re-reading the transcript.' },
196
+ blocked: { type: 'string', description: 'cursor.set: what is blocking right now, or empty when nothing is.' },
197
+ clear: { type: 'boolean', description: 'cursor.set: wipe step / next / blocked instead of overwriting them.' },
198
+ expectedTaskId: { type: 'string', description: 'cursor.set: task id this cursor is working on — the panel highlights that node in the tree.' },
199
+ memoryId: { type: 'string', description: 'Memory entry id for memory.remove.' },
200
+ question: { type: 'string', description: 'Question for memory.ask; answered only from what this conversation already recorded.' },
201
+ section: {
202
+ type: 'string',
203
+ enum: ['progress', 'decision', 'verify', 'open', 'other'],
204
+ description: 'Memory section for memory.add: progress / decision / verify / open / other.',
205
+ },
206
+ body: { type: 'string', description: 'Note body, Markdown allowed.' },
207
+ tags: { type: 'array', items: { type: 'string' }, description: 'Note tags.' },
208
+ pinned: { type: 'boolean', description: 'note.write: mark this note pinned (anchor); bounds.add / bounds.pin / bounds.consolidate: when true, pin boundary globally across ALL tasks/sessions (📌); when false, keep boundary scoped to current task only.' },
209
+ title: { type: 'string', description: 'Task title for task.add (or a rename in task.update); note.write: the note headline.' },
210
+ note: { type: 'string', description: 'Free-form detail for the task.' },
211
+ owner: { type: 'string', description: 'task.add / task.claim: who holds this task; defaults to the caller.' },
212
+ intent: { type: 'string', description: 'task.add / task.update: why this task exists — the reason that survives a compaction.' },
213
+ evidence: { type: 'string', description: 'task.add / task.update: what would prove it done — a command, a file, a probe name.' },
214
+ blockedBy: { type: 'array', items: { type: 'string' }, description: 'task.add / task.update: task ids this task waits on — claim refuses while any of them is not done.' },
215
+ assumption: { type: 'string', description: 'task.add / task.update: record an assumption you are making — stays visible until task.verify marks it true.' },
216
+ assumptionIndex: { type: 'number', description: 'task.verify: which assumption (0-based) to mark as verified.' },
217
+ taskId: { type: 'string', description: 'task id for task.update / task.claim / task.release / task.remove / task.verify / task.dispatch (alias for id).' },
218
+ target: { type: 'string', description: 'task.add / task.update / task.dispatch: who this task is assigned to — visible in tree view as owner label.' },
219
+ parentId: { type: 'string', description: 'task.add / task.update: parent task id for tree hierarchy — renders the child indented under its parent.' },
220
+ status: { type: 'string', enum: STATUSES, description: 'Task status.' },
221
+ priority: { type: 'string', enum: PRIORITIES, description: 'Task priority.' },
222
+ field: {
223
+ type: 'string',
224
+ enum: ['allowed', 'must', 'forbidden', 'notes'],
225
+ description: 'bounds.propose / bounds.set: target boundary column ("forbidden" = 禁止红线, "allowed"/"must" = 必做事项, or "notes" = 注意事项).',
226
+ },
227
+ item: { type: 'string', description: 'bounds.propose / bounds.add / bounds.pin / bounds.remove / bounds.edit / bounds.consolidate: boundary rule text.' },
228
+ oldItem: { type: 'string', description: 'bounds.edit: existing boundary rule text to replace.' },
229
+ removeItems: { type: 'array', items: { type: 'string' }, description: 'bounds.consolidate: scattered boundary rules to remove and replace with item.' },
230
+ reason: { type: 'string', description: 'bounds.propose / permission.request: justification for why this boundary or permission tier is needed.' },
231
+ targetMode: { type: 'string', enum: ['assistant', 'strategist', 'chief'], description: 'permission.request: requested DSH Chief permission tier.' },
232
+ items: { type: 'array', items: { type: 'string' }, description: 'bounds.propose (multiple rules) or bounds.set (new contents of column named by field).' },
233
+ allowed: { type: 'array', items: { type: 'string' }, description: 'bounds.set: the whole 必做 (allowed) column.' },
234
+ forbidden: { type: 'array', items: { type: 'string' }, description: 'bounds.set: the whole 禁止 column.' },
235
+ notes: { type: 'array', items: { type: 'string' }, description: 'bounds.set: the whole 注意 column.' },
236
+ autoInject: { type: 'boolean', description: 'settings.set: hand the digest to every turn of this machine.' },
237
+ guardIdle: { type: 'boolean', description: 'settings.set: keep steering a turn that closes without doing anything.' },
238
+ guardMaxPerSession: { type: 'number', description: 'settings.set: how many nudges one Session may take before the guard goes quiet (0-20, default 3).' },
239
+ guardShortAnswer: { type: 'number', description: 'settings.set: the answer length below which a silent turn counts as an idle close (0-10000, default 600).' },
240
+ objective: { type: 'string', description: 'The plan objective for plan.set / graph.plan / objective.set.' },
241
+ steps: {
242
+ type: 'array',
243
+ description: 'Ordered plan steps for plan.set; each step is { id?, text, done }.',
244
+ items: {
245
+ type: 'object',
246
+ properties: {
247
+ id: { type: 'string', description: 'Existing step id from the board; omit for a new step.' },
248
+ text: { type: 'string' },
249
+ done: { type: 'boolean' },
250
+ },
251
+ required: ['text'],
252
+ additionalProperties: false,
253
+ },
254
+ },
255
+ text: { type: 'string', description: 'One handoff log line for log.add, or message text for team.steer / mail.send.' },
256
+ subject: { type: 'string', description: 'mail.send: optional short subject line.' },
257
+ delivery: {
258
+ type: 'string',
259
+ enum: ['steer', 'followup', 'silent'],
260
+ description: 'mail.send: delivery posture ("steer" cuts into next step boundary, "followup" queues/wakes next turn, "silent" drops into chief inbox for next pre-step).',
261
+ },
262
+ unreadOnly: { type: 'boolean', description: 'mail.inbox: when true, returns only unread messages.' },
263
+ by: { type: 'string', description: 'Who acts: an agent label or a user name. Defaults to "agent".' },
264
+ session: { type: 'string', description: 'Session id that owns the change; the GUI fills it automatically.' },
265
+ scope: { type: 'string', enum: ['session', 'shared'], description: 'Board to hit. Default "session" = the caller\'s own (or root tree) board; "shared" = the machine-wide anchor board.' },
266
+ },
267
+ required: ['action'],
268
+ additionalProperties: false,
269
+ }
270
+
271
+ function boardTool(runtime) {
272
+ return {
273
+ name: 'chief_board',
274
+ description:
275
+ 'Shared task graph, subagent team controller, cross-session communication bus, plan, and anchor chief (参谋看板, coordinated by DSH 参谋长). '
276
+ + 'MANDATORY DISCIPLINE: (1) Always call this tool to record objectives, task status changes (doing/blocked/done + evidence), or pinned conclusions — oral text alone counts as NOT recorded. '
277
+ + '(2) Always call "mail.send", "task.dispatch", or "team.steer" when relaying information or delegating across lead/subagents/sessions — oral @mentions do NOT reach peers. '
278
+ + '(3) When you hit a permission/sandbox/environment wall or are asked to summarize boundaries, call action="bounds.propose" (field="forbidden"|"allowed"|"notes", item, reason; note "allowed" represents 必做事项) to submit to DSH Chief (宰相), who requests user approval before injecting into global bounds.',
279
+ parameters: BOARD_PARAMETERS,
280
+ output: {
281
+ schema: { type: 'object', description: 'The board summary after the operation.' },
282
+ render(_args, value) {
283
+ const view = value && typeof value === 'object' ? value : {}
284
+ const lines = []
285
+ if (view.ok === false) {
286
+ lines.push('failed: ' + String(view.error))
287
+ if (/bounds list too long/.test(String(view.error))) lines.push('bounds: one column holds at most ' + BOUND_CAP + ' entries')
288
+ }
289
+ if (view.archiveSearch) {
290
+ const hits = Array.isArray(view.archiveSearch.hits) ? view.archiveSearch.hits : []
291
+ lines.push('🗄️ archive search (' + hits.length + ' / ' + (view.archiveSearch.totalArchives || 0) + ' cold dossiers):')
292
+ for (const h of hits) {
293
+ lines.push(' 📎 [' + h.folderLabel + '] «' + h.title + '» (' + h.id + ') — ' + h.summary)
294
+ }
295
+ if (!hits.length) lines.push(' (no matching cold archives)')
296
+ }
297
+ if (view.archiveItem) {
298
+ const it = view.archiveItem
299
+ lines.push('📎 archive «' + it.title + '» [' + it.folder + ' · ' + it.paperclip + '] (' + it.id + ')')
300
+ lines.push('summary: ' + (it.summary || ''))
301
+ for (const pt of Array.isArray(it.points) ? it.points : []) {
302
+ lines.push(' • ' + pt.title + ': ' + (pt.detail || pt.cue || ''))
303
+ }
304
+ if (it.body) lines.push('--- raw body ---\n' + it.body)
305
+ }
306
+ if (view.archiveSaved) {
307
+ lines.push('🗄️ archived dossier «' + view.archiveSaved.title + '» → drawer [' + view.archiveSaved.folder + '] (' + view.archiveSaved.id + ', cold-sealed)')
308
+ }
309
+ if (view.mailDelivered) {
310
+ lines.push('📨 mail delivered → ' + view.mailDelivered.target + ' (' + view.mailDelivered.mode + ')')
311
+ }
312
+ if (view.boundProposed) {
313
+ lines.push('🏛 ' + view.boundProposed.message)
314
+ for (const p of view.boundProposed.proposed || []) {
315
+ lines.push(' [' + p.field + '] ' + p.item + ' (by ' + p.from + ')')
316
+ }
317
+ }
318
+ if (view.elevationRequested) {
319
+ const elv = view.elevationRequested
320
+ const tgt = CHIEF_PERMISSION_META[elv.targetMode] || {}
321
+ lines.push(`🔐 elevation requested → ${tgt.level || ''} ${tgt.title || elv.targetMode}: ${elv.reason || ''}`)
322
+ } else if (view.elevationMessage) {
323
+ lines.push('🔐 ' + view.elevationMessage)
324
+ }
325
+ if (Array.isArray(view.inbox)) {
326
+ lines.push('📬 mailbox (' + view.inbox.length + ' messages):')
327
+ for (const m of view.inbox.slice(-10)) {
328
+ lines.push(' ' + (m.unread ? '[NEW] ' : '') + m.from + ' → ' + m.to + (m.subject ? ' (' + m.subject + ')' : '') + ': ' + String(m.text || '').slice(0, 140))
329
+ }
330
+ if (Array.isArray(view.peers) && view.peers.length) {
331
+ lines.push('📡 addressable peers: ' + view.peers.map(p => p.handle + '[' + p.status + ']').join(' · '))
332
+ }
333
+ }
334
+ if (view.dispatched) {
335
+ lines.push('🚀 dispatched task #' + view.dispatched.taskId + ' → subagent ' + view.dispatched.agent + ' (' + view.dispatched.mode + ')')
336
+ }
337
+ if (view.interrupted) {
338
+ lines.push('⏹ interrupted subagent ' + view.interrupted)
339
+ }
340
+ if (view.messageId && view.agent) {
341
+ lines.push('💬 steered subagent ' + view.agent + ' (messageId: ' + view.messageId + ')')
342
+ }
343
+ const subagents = Array.isArray(view.subagents) ? view.subagents.filter(a => a && a.name !== 'lead') : []
344
+ if (subagents.length) {
345
+ lines.push('子代理团队 (' + subagents.length + '): ' + subagents.map(a => a.name + '[' + a.status + ']').join(' · '))
346
+ }
347
+ const teamTasks = Array.isArray(view.teamTasks) ? view.teamTasks : []
348
+ if (teamTasks.length) {
349
+ lines.push('团队共享任务 ' + teamTasks.length + ' 项:')
350
+ for (const t of teamTasks) {
351
+ const st = t.status === 'in_progress' ? 'doing' : t.status === 'completed' ? 'done' : t.status
352
+ lines.push(' [' + st + '] ' + t.id + ' ' + t.subject + (t.owner ? ' → ' + t.owner : '') + (t.blockedBy.length ? ' [等 ' + t.blockedBy.join(',') + ']' : ''))
353
+ }
354
+ }
355
+ const counts = view.counts || {}
356
+ lines.push('todo ' + (counts.todo || 0) + ' / doing ' + (counts.doing || 0) + ' / blocked ' + (counts.blocked || 0) + ' / done ' + (counts.done || 0))
357
+ for (const task of Array.isArray(view.tasks) ? view.tasks : []) {
358
+ const unverified = (Array.isArray(task.assumptions) ? task.assumptions : []).filter(a => !a.verified).length
359
+ const parentInfo = task.parentId ? ' [父:' + task.parentId + ']' : ''
360
+ const depInfo = (Array.isArray(task.blockedBy) ? task.blockedBy : []).length && task.status !== 'done'
361
+ ? ' [等 ' + task.blockedBy.join(',') + ']'
362
+ : ''
363
+ const evInfo = task.evidence ? ' ✓证据:' + String(task.evidence).slice(0, 40) : ''
364
+ lines.push('[' + task.status + '] #' + task.id + ' ' + task.title + (task.owner ? ' — @' + task.owner : '') + parentInfo + depInfo + (unverified > 0 ? ' ⚠' + unverified + '假设' : '') + evInfo)
365
+ }
366
+ const notesShown = Array.isArray(view.notes) ? view.notes : []
367
+ for (const note of notesShown) {
368
+ lines.push('note «' + (note.title || '(untitled)') + '» ' + (note.tags || []).join('/') + ' (' + note.id + ')')
369
+ }
370
+ const notesTotal = typeof view.notesCount === 'number' ? view.notesCount : notesShown.length
371
+ const notesHidden = Math.max(0, notesTotal - notesShown.length)
372
+ if (notesHidden > 0) {
373
+ lines.push('notes: ' + notesShown.length + ' of ' + notesTotal + ' shown — ' + notesHidden + ' older note(s) are not in this answer')
374
+ } else {
375
+ lines.push('notes: ' + notesTotal + ' (all shown)')
376
+ }
377
+ const logShown = Array.isArray(view.log) ? view.log.length : 0
378
+ const logTotal = typeof view.logCount === 'number' ? view.logCount : logShown
379
+ if (logTotal > logShown) {
380
+ lines.push('log: ' + logShown + ' of ' + logTotal + ' lines shown')
381
+ }
382
+ const truncated = Array.isArray(view.truncated) ? view.truncated : []
383
+ if (truncated.length > 0) {
384
+ const parts = truncated.map(item => item.field + ' ' + item.sent + ' → ' + item.kept + ' chars')
385
+ lines.push('truncated: ' + parts.join('; '))
386
+ }
387
+ return [{ type: 'text', text: lines.join('\n') }]
388
+ },
389
+ },
390
+ async execute(args, exec) {
391
+ const passed = args && typeof args === 'object' ? args : {}
392
+ const callerAgent = exec && exec.agent ? exec.agent : null
393
+ const rawSession = typeof passed.session === 'string' && passed.session
394
+ ? passed.session
395
+ : (callerAgent && callerAgent.id ? String(callerAgent.id) : '')
396
+ const session = resolveRootSessionId(rawSession, callerAgent) || rawSession
397
+ const identity = resolveAgentIdentity(runtime, rawSession, callerAgent)
398
+ const byDefault = passed.by || (identity && identity.isChild ? identity.self : 'agent')
399
+
400
+ if (passed.action === 'team.list') {
401
+ try {
402
+ const board = session ? loadBoard(boardFileFor(session)) : emptyBoard()
403
+ const roster = await refreshSubagentTree(runtime, session, board)
404
+ const svc = runtime.get('agentTeams')
405
+ const rawTeamTasks = (svc && typeof svc.listTasks === 'function' && callerAgent) ? (svc.listTasks(callerAgent) || []) : []
406
+ return {
407
+ ok: true,
408
+ subagents: roster,
409
+ teamTasks: rawTeamTasks.map(t => ({
410
+ id: t.id, subject: t.subject, status: t.status,
411
+ owner: t.ownerName || '', blockedBy: t.blockedBy || [],
412
+ ready: t.ready, revision: t.revision,
413
+ })),
414
+ ...summary(board, roster),
415
+ }
416
+ } catch (err) {
417
+ return { ok: false, error: 'team.list: ' + String(err && err.message || err) }
418
+ }
419
+ }
420
+
421
+ if (passed.action === 'bounds.propose') {
422
+ const propRes = proposeBoundToChief(makeChiefDeps(runtime), {
423
+ sessionId: rawSession,
424
+ callerAgent,
425
+ by: byDefault,
426
+ field: normalizeBoundFieldName(passed.field) || 'forbidden',
427
+ item: str(passed.item || passed.text || passed.note || passed.body, ''),
428
+ items: Array.isArray(passed.items) ? passed.items : undefined,
429
+ reason: str(passed.reason || passed.intent || passed.subject, ''),
430
+ })
431
+ if (!propRes.ok) return { ok: false, error: propRes.error }
432
+ const board = session ? boardForSession(boardFileFor(session)) : emptyBoard()
433
+ const roster = session ? await refreshSubagentTree(runtime, session, board) : []
434
+ return {
435
+ ok: true,
436
+ boundProposed: propRes,
437
+ ...summary(board, roster),
438
+ }
439
+ }
440
+
441
+ if (passed.action === 'mail.send') {
442
+ const target = str(passed.target || passed.agent || passed.subagent, 'lead').trim() || 'lead'
443
+ const msgText = str(passed.text || passed.message || passed.prompt || passed.body || passed.note, '').trim()
444
+ const deliv = await deliverCrossMessage(makeChiefDeps(runtime), {
445
+ fromSession: rawSession,
446
+ fromLabel: byDefault,
447
+ target,
448
+ subject: str(passed.subject || passed.title, ''),
449
+ text: msgText,
450
+ mode: ['steer', 'followup', 'silent'].includes(passed.delivery) ? passed.delivery : 'steer',
451
+ })
452
+ if (!deliv.ok) return { ok: false, error: deliv.error }
453
+ const board = session ? loadBoard(boardFileFor(session)) : emptyBoard()
454
+ const roster = session ? await refreshSubagentTree(runtime, session, board) : []
455
+ return {
456
+ ok: true,
457
+ mailDelivered: {
458
+ target: deliv.broadcast ? 'all' : deliv.target,
459
+ mode: deliv.broadcast ? 'broadcast' : deliv.deliveryMode,
460
+ },
461
+ ...summary(board, roster),
462
+ }
463
+ }
464
+
465
+ if (passed.action === 'mail.inbox') {
466
+ const secDeps = makeChiefDeps(runtime)
467
+ const inbox = readMailboxForAgent(secDeps, {
468
+ sessionId: rawSession,
469
+ callerAgent,
470
+ unreadOnly: Boolean(passed.unreadOnly),
471
+ })
472
+ const dir = await listPeerDirectory(secDeps, session || rawSession)
473
+ const board = session ? loadBoard(boardFileFor(session)) : emptyBoard()
474
+ const roster = session ? await refreshSubagentTree(runtime, session, board) : []
475
+ return {
476
+ ok: true,
477
+ inbox,
478
+ peers: dir.targets,
479
+ ...summary(board, roster),
480
+ }
481
+ }
482
+
483
+ if (passed.action === 'context.compact') {
484
+ const scRes = await requestSmartCompactFromLead(makeChiefDeps(runtime), {
485
+ sessionId: rawSession || session,
486
+ reason: str(passed.text || passed.summary || passed.body || passed.note, ''),
487
+ by: byDefault,
488
+ })
489
+ if (!scRes || scRes.ok === false) {
490
+ return { ok: false, error: (scRes && scRes.error) || '智选压缩请求未能执行' }
491
+ }
492
+ const board = session ? boardForSession(boardFileFor(session)) : emptyBoard()
493
+ const roster = session ? await refreshSubagentTree(runtime, session, board) : []
494
+ return {
495
+ ok: true,
496
+ smartCompact: scRes,
497
+ ...summary(board, roster),
498
+ }
499
+ }
500
+
501
+ if (passed.action === 'permission.request') {
502
+ const reqTarget = normalizePermissionMode(passed.targetMode || 'strategist')
503
+ const reasonTxt = str(passed.reason || passed.text || passed.note || passed.intent, '主对话/子代理申请提升 DSH 参谋系统权限以继续任务')
504
+ const elv = requestChiefElevation(session || rawSession || 'global', {
505
+ targetMode: reqTarget,
506
+ reason: reasonTxt,
507
+ requestedActionSummary: str(passed.item || passed.title || passed.text, ''),
508
+ by: byDefault,
509
+ })
510
+ const board = session ? boardForSession(boardFileFor(session)) : emptyBoard()
511
+ const roster = session ? await refreshSubagentTree(runtime, session, board) : []
512
+ return {
513
+ ok: true,
514
+ elevationRequested: elv,
515
+ elevationMessage: elv
516
+ ? `已向用户弹出提权申请(请求升至 ${CHIEF_PERMISSION_META[reqTarget]?.level || reqTarget} · ${CHIEF_PERMISSION_META[reqTarget]?.title || reqTarget}),等待用户点击确认。`
517
+ : '当前权限已满足或高于目标档位,无需重复提权。',
518
+ ...summary(board, roster),
519
+ }
520
+ }
521
+
522
+ if (passed.action === 'task.dispatch' || passed.action === 'team.steer' || passed.action === 'team.interrupt') {
523
+ const subRes = await executeSubagentAction(runtime, { ...passed, by: byDefault, session }, callerAgent, exec && exec.signal)
524
+ if (!subRes.ok) return { ok: false, error: subRes.error }
525
+ return {
526
+ ok: true,
527
+ ...(subRes.dispatched ? { dispatched: subRes.dispatched } : {}),
528
+ ...(subRes.interrupted ? { interrupted: subRes.interrupted } : {}),
529
+ ...(subRes.messageId ? { messageId: subRes.messageId, agent: subRes.agent } : {}),
530
+ ...summary(subRes.board, subRes.subagents),
531
+ }
532
+ }
533
+
534
+ const result = runAction(session ? { ...passed, by: byDefault, session } : { ...passed, by: byDefault })
535
+ if (!result.ok) return { ok: false, error: result.error }
536
+ const mergedBoard = session && result.board ? boardForSession(boardFileFor(session)) : result.board
537
+ const roster = session ? await refreshSubagentTree(runtime, session, mergedBoard) : []
538
+ return {
539
+ ok: true,
540
+ ...summary(mergedBoard, roster),
541
+ ...(result.archiveSearch ? { archiveSearch: result.archiveSearch } : {}),
542
+ ...(result.archiveItem ? { archiveItem: result.archiveItem } : {}),
543
+ ...(result.archiveSaved ? { archiveSaved: result.archiveSaved } : {}),
544
+ ...(result.truncated ? { truncated: result.truncated } : {}),
545
+ }
546
+ },
547
+ }
548
+ }
549
+
550
+ function memoryTool(runtime) {
551
+ return {
552
+ name: 'chief_memory',
553
+ description:
554
+ 'Rolling memory of THIS conversation, kept on its own board: one entry per finished turn, plus anything the human or you mark as worth keeping. '
555
+ + 'Ask with "memory.ask" (question) to get the entries that match — answered only from what was actually recorded, and it says so when nothing matches. '
556
+ + 'Write with "memory.add" (text, optional title/section) when a decision, a gate, or a constraint must survive the next turn; '
557
+ + '"memory.remove" drops one entry by id. Sections: progress / decision / verify / open / other.',
558
+ parameters: {
559
+ type: 'object',
560
+ properties: {
561
+ action: { type: 'string', enum: ['memory.add', 'memory.remove', 'memory.ask'], description: 'Memory operation.' },
562
+ text: { type: 'string', description: 'Entry body for memory.add.' },
563
+ title: { type: 'string', description: 'Short headline for memory.add; defaults to the first 80 chars of text.' },
564
+ section: { type: 'string', enum: MEMORY_SECTIONS.map(section => section.key), description: 'Section for memory.add.' },
565
+ memoryId: { type: 'string', description: 'Entry id for memory.remove.' },
566
+ question: { type: 'string', description: 'Natural-language question for memory.ask.' },
567
+ session: { type: 'string', description: 'Session whose memory to hit; defaults to the calling Agent.' },
568
+ scope: { type: 'string', enum: ['session', 'shared'], description: 'Board to hit. Default "session" = this conversation\'s own memory.' },
569
+ },
570
+ required: ['action'],
571
+ additionalProperties: false,
572
+ },
573
+ output: {
574
+ schema: { type: 'object', description: 'The answer for memory.ask, or the entry that changed.' },
575
+ render(_args, value) {
576
+ const view = value && typeof value === 'object' ? value : {}
577
+ if (view.ok === false) return [{ type: 'text', text: 'failed: ' + String(view.error) }]
578
+ if (typeof view.reply === 'string') {
579
+ const lines = [view.reply]
580
+ if (Array.isArray(view.terms) && view.terms.length) lines.push('terms: ' + view.terms.join('/'))
581
+ return [{ type: 'text', text: lines.join('\n') }]
582
+ }
583
+ const lines = ['memory entries: ' + (view.memoryCount === undefined ? '?' : view.memoryCount)]
584
+ for (const item of Array.isArray(view.memory) ? view.memory : []) {
585
+ lines.push('[' + item.section + '] ' + item.title)
586
+ }
587
+ return [{ type: 'text', text: lines.join('\n') }]
588
+ },
589
+ },
590
+ async execute(args, exec) {
591
+ const passed = args && typeof args === 'object' ? args : {}
592
+ const session = typeof passed.session === 'string' && passed.session
593
+ ? passed.session
594
+ : (exec && exec.agent && exec.agent.id ? String(exec.agent.id) : '')
595
+ if (!session && passed.scope !== 'shared') {
596
+ return { ok: false, error: 'no session bound — memory is per-conversation now' }
597
+ }
598
+ const result = runAction(session ? { ...passed, session } : passed)
599
+ if (!result.ok) return { ok: false, error: result.error }
600
+ if (passed.action === 'memory.ask') {
601
+ return { ok: true, reply: result.reply, hits: result.hits, terms: result.terms }
602
+ }
603
+ return {
604
+ ok: true,
605
+ memory: summary(result.board).memory,
606
+ memoryCount: summary(result.board).memoryCount,
607
+ ...(result.truncated ? { truncated: result.truncated } : {}),
608
+ }
609
+ },
610
+ }
611
+ }
612
+
613
+ function boundariesTool(runtime) {
614
+ return {
615
+ name: 'chief_boundaries',
616
+ description:
617
+ 'Report this Harness deployment’s live limits: working directory, sandbox mode, workspace-write roots, '
618
+ + 'profile, the shared chief file, advertised web URL, tool count and process facts. '
619
+ + 'Use it whenever the answer depends on what this Session is actually allowed to touch.',
620
+ parameters: {
621
+ type: 'object',
622
+ properties: {
623
+ session: { type: 'string', description: 'Session to report on; defaults to the calling Agent. Every per-session field is resolved for that Session, not for the process.' },
624
+ },
625
+ additionalProperties: false,
626
+ },
627
+ output: {
628
+ schema: { type: 'object', description: 'Boundary facts for this deployment.' },
629
+ render(_args, value) {
630
+ const view = value && typeof value === 'object' ? value : {}
631
+ return [{
632
+ type: 'text',
633
+ text: Object.keys(view).map(key => key + ': ' + JSON.stringify(view[key])).join('\n'),
634
+ }]
635
+ },
636
+ },
637
+ async execute(args, exec) {
638
+ const passed = args && typeof args === 'object' ? args : {}
639
+ const session = str(passed.session, '') || str(exec && exec.agent && exec.agent.id, '')
640
+ return boundaries(runtime, session)
641
+ },
642
+ }
643
+ }
644
+
645
+ function handoffTool(runtime) {
646
+ return {
647
+ name: 'chief_handoff',
648
+ description:
649
+ 'Produce the handover packet for this machine: objective, where the work stands, the ordered next actions with the intent behind each, '
650
+ + 'the safety bounds to respect before touching anything, key coordinates, what was already tried and failed, and what still waits on the human. '
651
+ + 'Hand it to a fresh Session when the current context is too heavy, so that Session can continue WITHOUT re-reading or decompressing the old transcript. '
652
+ + 'A new Session should call this first. Pass mark:true once the packet was actually handed over.',
653
+ parameters: {
654
+ type: 'object',
655
+ properties: {
656
+ mark: { type: 'boolean', description: 'Stamp handoff.at/by/session to record that this packet was handed over.' },
657
+ session: { type: 'string', description: 'Session handing over; defaults to the calling Agent.' },
658
+ target: { type: 'string', description: 'Deliver instead of just rendering: "new" waits for the next new Session, or pass a live Session id to hand it over now. Only the operator decides this; nothing is transferred on its own.' },
659
+ autoInject: { type: 'boolean', description: 'Turn the per-turn digest on or off. On by default: the digest is registered at the head of the system prompt so the model keeps the board in view for the whole task. Setting false records the preference; it does not remove the section.' },
660
+ guardIdle: { type: 'boolean', description: 'Turn the idle-turn guard on or off (on by default): a turn that closes without moving the plan — no plan written, or open steps left untouched, or a short silent answer while work is still open — is steered one more step.' },
661
+ },
662
+ additionalProperties: false,
663
+ },
664
+ output: {
665
+ schema: { type: 'object', description: 'The packet plus a short structural summary.' },
666
+ render(_args, value) {
667
+ const view = value && typeof value === 'object' ? value : {}
668
+ return [{ type: 'text', text: String(view.text || '') }]
669
+ },
670
+ },
671
+ async execute(args, exec) {
672
+ const passed = args && typeof args === 'object' ? args : {}
673
+ const session = typeof passed.session === 'string' && passed.session
674
+ ? passed.session
675
+ : (exec && exec.agent && exec.agent.id ? String(exec.agent.id) : '')
676
+
677
+ const auto = asBool(passed.autoInject)
678
+ if (auto !== undefined) {
679
+ // autoInject lives on the shared board — it is a machine-level flag, not
680
+ // per-session content.
681
+ runAction({ action: 'settings.set', autoInject: auto, session, by: 'agent', scope: 'shared' })
682
+ }
683
+
684
+ const guard = asBool(passed.guardIdle)
685
+ if (guard !== undefined) {
686
+ runAction({ action: 'settings.set', guardIdle: guard, session, by: 'agent', scope: 'shared' })
687
+ }
688
+
689
+ if (typeof passed.target === 'string' && passed.target) {
690
+ const delivered = await transferChief(runtime, { ...passed, by: 'agent' }, session)
691
+ const after = loadBoard(boardFileFor(session))
692
+ const result = {
693
+ ok: delivered.ok,
694
+ mode: delivered.mode,
695
+ text: delivered.text,
696
+ counts: {
697
+ plan: (after.plan || []).length,
698
+ openSteps: (after.plan || []).filter(step => !step.done).length,
699
+ tasks: (after.tasks || []).length,
700
+ openTasks: (after.tasks || []).filter(task => task.status !== 'done').length,
701
+ },
702
+ }
703
+ // undefined is not lossless JSON, so a success carries no error key at all
704
+ if (delivered.ok === false && delivered.error) result.error = String(delivered.error)
705
+ return result
706
+ }
707
+
708
+ const selfFile = boardFileFor(session)
709
+ if (asBool(passed.mark) === true) {
710
+ // The tool half writes boards too, so it has to take the same lock as the
711
+ // routes: a mark landing between a route's load and its save would be
712
+ // dropped by whichever rename finished second.
713
+ withBoardLock(selfFile, () => {
714
+ const marked = loadBoard(selfFile)
715
+ marked.handoff = { ...(marked.handoff || {}), at: nowMs(), by: 'agent', session }
716
+ pushLog(marked, '交接单已生成并交出', 'agent', session)
717
+ saveBoard(marked, selfFile)
718
+ })
719
+ }
720
+ // Render the inherited view: a packet handed over before the session ever
721
+ // wrote bounds/objective must still tell the successor what the operator
722
+ // forbade and what the machine is working on.
723
+ const board = boardForSession(selfFile)
724
+ const hInfo = resolveEffectiveHandoff(
725
+ runtime,
726
+ session,
727
+ board,
728
+ fetchTeamTasks(runtime, exec && exec.agent ? exec.agent : null),
729
+ )
730
+ return {
731
+ ok: true,
732
+ text: hInfo.text,
733
+ pinned: hInfo.pinned,
734
+ source: hInfo.source,
735
+ counts: {
736
+ plan: (board.plan || []).length,
737
+ openSteps: (board.plan || []).filter(step => !step.done).length,
738
+ tasks: (board.tasks || []).length,
739
+ openTasks: (board.tasks || []).filter(task => task.status !== 'done').length,
740
+ bounds: board.bounds,
741
+ handoffAt: board.handoff ? board.handoff.at : 0,
742
+ },
743
+ }
744
+ },
745
+ }
746
+ }
747
+
748
+ return {
749
+ BOARD_PARAMETERS,
750
+ boardTool,
751
+ memoryTool,
752
+ boundariesTool,
753
+ handoffTool,
754
+ }
755
+ }