dsh-chief 1.6.0 → 1.7.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,9 +1,9 @@
1
1
  {
2
2
  "name": "dsh-chief",
3
- "version": "1.6.0",
3
+ "version": "1.7.0",
4
4
  "icon": "icon.svg",
5
5
  "type": "module",
6
- "description": "Right-sidebar supervisor for DeepSeek Harness (DSH): prevents context-compaction amnesia, monitors subagent DAGs, gates file edits and shell commands behind per-action approvals, breaks runaway loops, and hands off long sessions without bloating prompt tokens.",
6
+ "description": "Right-sidebar supervisor plugin for DeepSeek Harness (DSH): saves findings before compaction, monitors subagent workflows, checks file edits and shell commands against guard rules, stops repeat-error loops, and hands off long sessions.",
7
7
  "author": "gluztm",
8
8
  "license": "AGPL-3.0-only",
9
9
  "repository": {
@@ -100,6 +100,12 @@
100
100
  "chief-review.js",
101
101
  "chief-approvals.js",
102
102
  "chief-executor.js",
103
+ "board-handoff.js",
104
+ "network-harness.js",
105
+ "state-schema.js",
106
+ "state-media.js",
107
+ "command-helpers.js",
108
+ "command-ops.js",
103
109
  "safety/*.js",
104
110
  "auto-continue.js",
105
111
  "archives.js",
package/runtime-hooks.js CHANGED
@@ -42,6 +42,8 @@ import {
42
42
  normalizeSuggestion,
43
43
  ensureWorkspace,
44
44
  recordWorkspaceAlertEvent,
45
+ isChiefSessionEnabled,
46
+ activateChiefSession,
45
47
  SUGGESTIONS_CAP,
46
48
  CHAT_CAP,
47
49
  nextId,
@@ -203,6 +205,17 @@ export function createRuntimeHooks(deps) {
203
205
  }
204
206
  }
205
207
 
208
+ const isSessionActive = (sid, agentObj = null) => {
209
+ try {
210
+ const raw = String(sid || (agentObj && agentObj.id) || '').trim()
211
+ const rk = resolveRootSessionId(raw, agentObj) || raw
212
+ if (!rk || rk === 'global') return false
213
+ return isChiefSessionEnabled(loadChiefState(), rk)
214
+ } catch {
215
+ return false
216
+ }
217
+ }
218
+
206
219
  const autoContinue = createAutoContinueEngine({
207
220
  createMessage: (text, sourceKind) => buildMessageEnvelope(text, sourceKind),
208
221
  getAgent: async (sid) => {
@@ -237,7 +250,8 @@ export function createRuntimeHooks(deps) {
237
250
  const cwdForCheck = (key && key !== 'global' && getSessionCwd(runtime, key)) || process.cwd()
238
251
  const board = key && key !== 'global' ? boardForSession(boardFileFor(key)) : null
239
252
  const detailSample = `${trigger || ''} ${detail || ''}`.trim()
240
- const safetyGuard = evaluateSafetyGuardHardRules({ tool: 'relay', opClass: 'workflow', command: detailSample, board })
253
+ const safetyGuardEnabled = !(effCfg && effCfg.tacticalModes && effCfg.tacticalModes.safetyGuardEnabled === false)
254
+ const safetyGuard = evaluateSafetyGuardHardRules({ tool: 'relay', opClass: 'workflow', command: detailSample, board, safetyGuardEnabled })
241
255
  if (safetyGuard && safetyGuard.blocked) {
242
256
  appendChiefAuditLog(key, {
243
257
  mode: effCfg.permissionMode || 'advisor',
@@ -392,6 +406,7 @@ export function createRuntimeHooks(deps) {
392
406
  if (!decision || decision.kind === 'reject' || signal?.aborted || !Array.isArray(decision.messages)) {
393
407
  return decision
394
408
  }
409
+ if (!isSessionActive(agent && agent.id, agent)) return decision
395
410
  const deltaMsg = await consumePreStepDelta(makeChiefDeps(runtime), agent)
396
411
  if (!deltaMsg) return decision
397
412
  return { ...decision, messages: [deltaMsg, ...decision.messages] }
@@ -419,6 +434,7 @@ export function createRuntimeHooks(deps) {
419
434
  const liveAgent = (promptCtx && promptCtx.agent) || (spCtx && spCtx.agent) || null
420
435
  const curId = liveAgent && liveAgent.id ? String(liveAgent.id) : fallbackAgentId
421
436
  const rootId = resolveRootSessionId(curId, liveAgent) || curId
437
+ if (!isSessionActive(rootId, liveAgent)) return ''
422
438
  let teamTasks
423
439
  try {
424
440
  const svc = runtime.get('agentTeams')
@@ -438,6 +454,7 @@ export function createRuntimeHooks(deps) {
438
454
  subagents,
439
455
  linkedPeersCount: linked.linkedPeersCount,
440
456
  linkedPeersProgress: linked.linkedPeersProgress,
457
+ bubbleSquad: linked.bubbleSquad,
441
458
  takenOutArchives: archCtx.takenOutArchives,
442
459
  sessionHookedArchives: archCtx.sessionHookedArchives,
443
460
  desktopUsedTokens: archCtx.desktopUsedTokens,
@@ -455,6 +472,7 @@ export function createRuntimeHooks(deps) {
455
472
  const caller = exec.agent || null
456
473
  const sessionId = caller && caller.id ? String(caller.id) : ''
457
474
  const rootId = resolveRootSessionId(sessionId, caller) || sessionId
475
+ if (!isSessionActive(rootId, caller)) return
458
476
  if (exec.name === 'todo_write') syncPlanFromTodos(exec.arguments, rootId)
459
477
  else if (exec.name === 'create_goal' || exec.name === 'update_goal') syncObjective(exec.name, exec.arguments, rootId)
460
478
  else if (exec.name === 'subagent' || exec.name === 'subagent_fork' || exec.name === 'send_message' || exec.name === 'interrupt_agent') {
@@ -473,6 +491,7 @@ export function createRuntimeHooks(deps) {
473
491
  const pendingDeploy = readPendingDeploy()
474
492
  if (pendingDeploy && pendingDeploy.fromSessionId && pendingDeploy.fromSessionId !== id) {
475
493
  clearPendingDeploy()
494
+ activateChiefSession(id, { force: true })
476
495
  try {
477
496
  deployStateToTargetChief(runtime, {
478
497
  fromSessionId: pendingDeploy.fromSessionId,
@@ -487,6 +506,7 @@ export function createRuntimeHooks(deps) {
487
506
 
488
507
  const pending = readPending()
489
508
  if (!pending) return
509
+ activateChiefSession(id, { force: true })
490
510
  const delivered = await injectInto(agent, pending.text)
491
511
  if (delivered.ok) clearPending()
492
512
  const file = boardFileFor(id)
@@ -648,6 +668,7 @@ export function createRuntimeHooks(deps) {
648
668
  if (!event || !session || !session.id) return
649
669
  const id = String(session.id)
650
670
  const rootIdForAct = resolveRootSessionId(id) || id
671
+ if (!isSessionActive(rootIdForAct)) return
651
672
  if (event.type === 'turn/start' || event.type === 'message/user' || event.type === 'tool/call' || event.type === 'turn/end') {
652
673
  touchWorkspaceActivity(rootIdForAct)
653
674
  }
@@ -708,6 +729,8 @@ export function createRuntimeHooks(deps) {
708
729
  const agent = payload && payload.agent
709
730
  id = agent && agent.id ? String(agent.id) : ''
710
731
  if (!id) return
732
+ const turnRootId = resolveRootSessionId(id, agent) || id
733
+ if (!isSessionActive(turnRootId, agent)) return
711
734
 
712
735
  const turn = Number(payload && payload.turn)
713
736
  const file = boardFileFor(id)
@@ -892,6 +915,10 @@ export function createRuntimeHooks(deps) {
892
915
  const caller = exec.agent || null
893
916
  const sid = caller && caller.id ? String(caller.id) : ''
894
917
  const rootId = resolveRootSessionId(sid, caller) || sid || 'global'
918
+ if (!isSessionActive(rootId, caller)) return next()
919
+ const preState = loadChiefState()
920
+ const preEffCfg = resolveWorkspaceConfig(preState, rootId)
921
+ const safetyGuardEnabled = !(preEffCfg && preEffCfg.tacticalModes && preEffCfg.tacticalModes.safetyGuardEnabled === false)
895
922
  const cwd = (sid && getSessionCwd(runtime, sid)) || (rootId !== 'global' && getSessionCwd(runtime, rootId)) || process.cwd()
896
923
  const board = rootId && rootId !== 'global' ? boardForSession(boardFileFor(rootId)) : loadBoard(boardFile())
897
924
  const verdict = evaluatePreExecuteDefense({
@@ -899,6 +926,7 @@ export function createRuntimeHooks(deps) {
899
926
  args: exec.arguments && typeof exec.arguments === 'object' ? exec.arguments : {},
900
927
  cwd,
901
928
  board,
929
+ safetyGuardEnabled,
902
930
  })
903
931
  if (verdict && verdict.decision === 'deny') {
904
932
  const st = loadChiefState()
@@ -997,7 +1025,7 @@ export function createRuntimeHooks(deps) {
997
1025
  }
998
1026
  })
999
1027
 
1000
- // Runtime capability probe for DSH >= 0.2.2-rc.2 named subagent APIs
1028
+ // Runtime capability probe for DSH >= 0.2.2-rc.2 named subagent APIs & external Harness provider tracking
1001
1029
  ctx.inject(['subagents'], () => {
1002
1030
  const compat = probeSubagentSupport(runtime)
1003
1031
  if (compat.present && !compat.namedSubagentsSupported) {
@@ -1005,7 +1033,45 @@ export function createRuntimeHooks(deps) {
1005
1033
  console.warn('[dsh-chief] ' + compat.warning)
1006
1034
  } catch {}
1007
1035
  }
1036
+ try {
1037
+ const sub = runtime && typeof runtime.get === 'function' ? runtime.get('subagents') : null
1038
+ if (sub && sub.providers instanceof Map) {
1039
+ for (const [pname, prov] of sub.providers.entries()) {
1040
+ if (pname && pname !== 'spawn' && pname !== 'fork') {
1041
+ deps.hostState.detectedHarnessProviders.set(pname, prov || { name: pname })
1042
+ }
1043
+ }
1044
+ }
1045
+ } catch {}
1008
1046
  })
1047
+ try {
1048
+ ctx.on?.('subagent/provider-added', (prov) => {
1049
+ const pname = String((prov && prov.name) || '').trim()
1050
+ if (!pname || pname === 'spawn' || pname === 'fork') return
1051
+ if (typeof prov?.prepareContinuable === 'function') return
1052
+ deps.hostState.detectedHarnessProviders.set(pname, prov)
1053
+ })
1054
+ ctx.on?.('subagent/provider-removed', (pname) => {
1055
+ if (pname) deps.hostState.detectedHarnessProviders.delete(String(pname))
1056
+ })
1057
+ ctx.on?.('subagent/end', (info) => {
1058
+ const cid = String((info && info.id) || '').trim()
1059
+ if (!cid) return
1060
+ for (const [k, run] of deps.hostState.activeBubbleRuns.entries()) {
1061
+ if (run && String(run.childId || '') === cid) {
1062
+ deps.hostState.activeBubbleRuns.delete(k)
1063
+ }
1064
+ }
1065
+ })
1066
+ } catch {}
1067
+ try {
1068
+ ctx.inject(['subprocess'], (subProcCtx) => {
1069
+ const rt = deps.hostState.activeRuntime
1070
+ deps.hostState.activeSubprocess = (subProcCtx && subProcCtx.subprocess)
1071
+ || (rt && typeof rt.get === 'function' ? rt.get('subprocess') : null)
1072
+ || null
1073
+ })
1074
+ } catch {}
1009
1075
 
1010
1076
  // Cold-start safety reconciliation for persistent TaskLedger (stale running/resuming -> interrupted; past TTL -> expired)
1011
1077
  try {
@@ -1030,6 +1096,7 @@ export function createRuntimeHooks(deps) {
1030
1096
  if (!agId) continue
1031
1097
  const rootId = resolveRootSessionId(agId, ag) || agId
1032
1098
  if (rootId !== agId) continue
1099
+ if (!isChiefSessionEnabled(state, rootId)) continue
1033
1100
  const effCfg = resolveWorkspaceConfig(state, rootId)
1034
1101
  if (effCfg.stopped || effCfg.paceMode === 'stopped') continue
1035
1102
  if (!(effCfg.tacticalModes && effCfg.tacticalModes.intervention)) continue
@@ -807,6 +807,7 @@ export function evaluatePreExecuteDefense({
807
807
  cwd = '',
808
808
  board = null,
809
809
  walls = null,
810
+ safetyGuardEnabled = true,
810
811
  } = {}) {
811
812
  const toolName = String(tool || '').trim()
812
813
  const lower = toolName.toLowerCase()
@@ -862,6 +863,10 @@ export function evaluatePreExecuteDefense({
862
863
  }
863
864
  }
864
865
 
866
+ if (safetyGuardEnabled === false) {
867
+ return { decision: 'allow', bypassedBySafetyGuardToggle: true }
868
+ }
869
+
865
870
  const extraText = [
866
871
  argObj.content,
867
872
  argObj.new_string,
@@ -22,13 +22,14 @@ export const HARD_GUARD_RULE_IDS = Object.freeze([
22
22
  ])
23
23
 
24
24
  const DESTRUCTIVE_COMMAND_PATTERNS = [
25
- /\brm\s+-[a-z]*(?:r[a-z]*f|f[a-z]*r)[a-z]*\s+(?:\/(?:etc|usr|bin|sbin|var|lib|boot|dev|proc|sys|root|home|\*)?(?=$|[\s/])|~|\*|\.\.)/i,
25
+ /\brm\s+-[a-z]*(?:r[a-z]*f|f[a-z]*r)[a-z]*\s+(?:\/(?:etc|usr|bin|sbin|var|lib|boot|dev|proc|sys|root|home|\*)?(?=$|[\s/'")])|~|\*|\.\.)/i,
26
26
  /\bgit\s+(?:reset\s+--hard|clean\s+-[a-z]*f[a-z]*d|push\s+(?:--force|-f)\b)/i,
27
- /\b(?:diskpart|cipher\s+\/w|bcdedit)\b/i,
27
+ /(?:^|[;&|]\s*|(?:(?:sudo|doas|nohup|command)\s+)+|(?:cmd(?:\.exe)?\s+\/[ck]|(?:powershell|pwsh)(?:\.exe)?\s+-[a-z]*c\w*|(?:bash|sh|zsh)\s+-[a-z]*c)\s+["']?)\b(?:diskpart(?:\.exe)?|cipher(?:\.exe)?\s+\/w|bcdedit(?:\.exe)?)\b/i,
28
28
  /(?:^|[;&|]\s*|(?:cmd(?:\.exe)?\s+\/c|powershell(?:\.exe)?\s+-[a-z]*c\w*|pwsh(?:\.exe)?\s+-[a-z]*c\w*)\s+["']?)\bformat(?:\.com)?\s+(?:[a-z]:|\/(?:fs|q|v|x|p|y)\b)/i,
29
29
  /\bdel\s+\/[fqs][^\n]*[a-z]:\\/i,
30
30
  /\bRemove-Item\b[^\n]*-Recurse[^\n]*-Force[^\n]*(?:[a-z]:\\|\*)/i,
31
- /\b(?:shutdown(?:\.exe)?|restart-computer|stop-computer|mkfs|dd\s+if=.*of=\/dev\/)\b/i,
31
+ /(?:^|[;&|]\s*|(?:(?:sudo|doas|nohup|command)\s+)+|(?:cmd(?:\.exe)?\s+\/[ck]|(?:powershell|pwsh)(?:\.exe)?\s+-[a-z]*c\w*|(?:bash|sh|zsh)\s+-[a-z]*c)\s+["']?)(?:(?:\/usr)?\/s?bin\/)?(?:shutdown(?:\.exe)?|restart-computer|stop-computer|mkfs(?:\.[a-z0-9]+)?)(?=$|[\s;'"])/i,
32
+ /\b(?:shutdown(?:\.exe)?\s+(?:-[hrspPfk]|\/[srphtl]|now\b)|mkfs(?:\.[a-z0-9]+)?\s+\/dev\/|dd\s+if=\S+[^\n]*\bof=\/dev\/)/i,
32
33
  /\breg(?:\.exe)?\s+delete\s+(?:hklm|hkcr|hkcu\\software\\microsoft)\b/i,
33
34
  /\bdrop\s+(?:database|schema)\b/i,
34
35
  ]
@@ -54,12 +55,126 @@ function expandEnvPlaceholdersForCheck(text) {
54
55
  .replace(/\$\{[A-Za-z0-9_]+\}/g, '/')
55
56
  }
56
57
 
58
+ const DANGEROUS_PIPE_CONSUMER_RE = /\|\s*(?:sudo\s+)?(?:(?:\/usr)?\/s?bin\/)?(?:sh|bash|zsh|dash|ksh|cmd(?:\.exe)?|powershell(?:\.exe)?|pwsh(?:\.exe)?|node(?:\.exe)?|python\d*|py|perl|ruby|php|mysql|psql|sqlite3?|sqlcmd|eval|iex|xargs)\b/i
59
+ const EXEC_SCRIPT_EXT_RE = /\.(?:sh|bash|zsh|ps1|bat|cmd)$/i
60
+
61
+ function stripLeadingEnvAssignments(seg) {
62
+ return String(seg || '')
63
+ .trim()
64
+ .replace(/^(?:export\s+)?(?:[A-Za-z_][A-Za-z0-9_]*=(?:'[^']*'|"[^"]*"|\S*)\s+)*/i, '')
65
+ .trim()
66
+ }
67
+
68
+ function stripNonExecHeredocBodies(command) {
69
+ const raw = String(command || '')
70
+ if (!raw.includes('<<')) return raw
71
+ const lines = raw.split(/\r?\n/)
72
+ const out = []
73
+ for (let i = 0; i < lines.length; i += 1) {
74
+ const line = lines[i]
75
+ out.push(line)
76
+ const hdMatch = line.match(/<<-?\s*(['"]?)([A-Za-z_][A-Za-z0-9_-]*)\1/)
77
+ if (!hdMatch || !hdMatch[2]) continue
78
+ const delim = hdMatch[2]
79
+ let endIdx = -1
80
+ for (let j = i + 1; j < lines.length; j += 1) {
81
+ if (lines[j].trim() === delim) {
82
+ endIdx = j
83
+ break
84
+ }
85
+ }
86
+ if (endIdx < 0) continue
87
+
88
+ const lastSeg = line.split(/;|&&|\|\|/).pop() || ''
89
+ const hasDangerPipe = DANGEROUS_PIPE_CONSUMER_RE.test(line)
90
+ const cmdHead = stripLeadingEnvAssignments(lastSeg)
91
+ const cmdM = cmdHead.match(/^([^\s;&|]+)/)
92
+ const primaryCmd = cmdM ? path.basename(cmdM[1]).toLowerCase() : ''
93
+ const isCatOrTee = primaryCmd === 'cat' || primaryCmd === 'tee' || primaryCmd === 'cat.exe' || primaryCmd === 'tee.exe'
94
+
95
+ const redirM = lastSeg.match(/>>?\s*(?:"([^"]+)"|'([^']+)'|([^\s;&|]+))/)
96
+ const teeArgM = primaryCmd.startsWith('tee')
97
+ ? cmdHead.replace(/^tee(?:\.exe)?(?:\s+-[a-z]+)*\s+/i, '').match(/^(?:"([^"]+)"|'([^']+)'|([^\s;&|<>]+))/)
98
+ : null
99
+ const targetFile = (redirM && (redirM[1] || redirM[2] || redirM[3]))
100
+ || (teeArgM && (teeArgM[1] || teeArgM[2] || teeArgM[3]))
101
+ || ''
102
+ const safeTarget = Boolean(targetFile)
103
+ && !/^\/dev\//i.test(targetFile)
104
+ && !EXEC_SCRIPT_EXT_RE.test(targetFile.trim())
105
+
106
+ if (isCatOrTee && safeTarget && !hasDangerPipe) {
107
+ for (let k = i + 1; k < endIdx; k += 1) out.push('')
108
+ out.push(lines[endIdx])
109
+ i = endIdx
110
+ }
111
+ }
112
+ return out.join('\n')
113
+ }
114
+
115
+ function isBenignGitReadOrCommit(cmdText) {
116
+ const tokens = String(cmdText || '').trim().split(/\s+/).filter(Boolean)
117
+ if (!tokens.length || !/^git(?:\.exe)?$/i.test(path.basename(tokens[0]))) return false
118
+ const valFlags = new Set(['-C', '--git-dir', '--work-tree'])
119
+ const boolFlags = new Set(['-p', '--paginate', '-P', '--no-pager', '--bare'])
120
+ let i = 1
121
+ while (i < tokens.length) {
122
+ const tok = tokens[i]
123
+ if (valFlags.has(tok)) {
124
+ i += 2
125
+ continue
126
+ }
127
+ if (boolFlags.has(tok) || /^--(?:git-dir|work-tree)=/i.test(tok)) {
128
+ i += 1
129
+ continue
130
+ }
131
+ if (tok.startsWith('-')) return false
132
+ break
133
+ }
134
+ const sub = tokens[i] ? tokens[i].toLowerCase() : ''
135
+ return sub === 'log' || sub === 'show' || sub === 'diff' || sub === 'status' || sub === 'branch' || sub === 'commit'
136
+ }
137
+
138
+ function isBenignTextOnlySegment(seg, hasDangerousConsumer) {
139
+ const s = String(seg || '').trim()
140
+ if (!s) return false
141
+ if (/\$\(|`|>\s*\/dev\/|>>?\s*["']?[^\s"']+\.(?:sh|bash|zsh|ps1|bat|cmd)(?:["'\s]|$)/i.test(s)) {
142
+ return false
143
+ }
144
+ const cleaned = stripLeadingEnvAssignments(s)
145
+ if (!cleaned) return true
146
+ if (/^(?:grep|egrep|fgrep|rg|ag|ack)(?:\.exe)?(?=\s|$)/i.test(cleaned)) {
147
+ return true
148
+ }
149
+ if (isBenignGitReadOrCommit(cleaned)) {
150
+ return true
151
+ }
152
+ if (/^(?:echo|printf)(?:\.exe)?(?=\s|$)/i.test(cleaned) && !hasDangerousConsumer) {
153
+ return true
154
+ }
155
+ return false
156
+ }
157
+
57
158
  export function isDestructiveShellCommand(command) {
58
159
  const raw = String(command || '').trim()
59
160
  if (!raw) return false
60
- const analysis = analyzeCommand(raw)
61
- const probes = [raw, analysis.normalized, ...analysis.segments, ...analysis.inlinePayloads]
62
- return probes.some(p => p && DESTRUCTIVE_COMMAND_PATTERNS.some(re => re.test(p)))
161
+ const sanitized = stripNonExecHeredocBodies(raw)
162
+ const hasDangerousConsumer = DANGEROUS_PIPE_CONSUMER_RE.test(sanitized)
163
+ const analysis = analyzeCommand(sanitized)
164
+ for (const seg of analysis.segments) {
165
+ if (!seg) continue
166
+ if (isBenignTextOnlySegment(seg, hasDangerousConsumer)) continue
167
+ if (DESTRUCTIVE_COMMAND_PATTERNS.some(re => re.test(seg))) return true
168
+ const normSeg = normalizeCommandForSecurity(seg)
169
+ if (normSeg && DESTRUCTIVE_COMMAND_PATTERNS.some(re => re.test(normSeg))) return true
170
+ }
171
+ for (const payload of analysis.inlinePayloads) {
172
+ if (!payload) continue
173
+ if (DESTRUCTIVE_COMMAND_PATTERNS.some(re => re.test(payload))) return true
174
+ const normPayload = normalizeCommandForSecurity(payload)
175
+ if (normPayload && DESTRUCTIVE_COMMAND_PATTERNS.some(re => re.test(normPayload))) return true
176
+ }
177
+ return false
63
178
  }
64
179
 
65
180
  export function commandTouchesSensitiveCredential(command) {
@@ -198,7 +313,11 @@ export function evaluateSafetyGuardHardRules({
198
313
  args = null,
199
314
  cwd = '',
200
315
  board = null,
316
+ safetyGuardEnabled = true,
201
317
  } = {}) {
318
+ if (safetyGuardEnabled === false) {
319
+ return { blocked: false, bypassedBySafetyGuardToggle: true }
320
+ }
202
321
  const argObj = args && typeof args === 'object' ? args : {}
203
322
  const resolvedPath = targetPath || (typeof argObj.path === 'string' ? argObj.path : '')
204
323
  const resolvedCommand = command || (typeof argObj.command === 'string' ? argObj.command : (typeof argObj.cmd === 'string' ? argObj.cmd : ''))
@@ -173,6 +173,7 @@ export function evaluateUnifiedToolGate({
173
173
  args = null,
174
174
  cwd = '',
175
175
  board = null,
176
+ safetyGuardEnabled = true,
176
177
  permissionMode = DEFAULT_CHIEF_PERMISSION_MODE,
177
178
  hasChiefRiskAck = false,
178
179
  approvedOnce = false,
@@ -187,6 +188,7 @@ export function evaluateUnifiedToolGate({
187
188
  args,
188
189
  cwd,
189
190
  board,
191
+ safetyGuardEnabled,
190
192
  })
191
193
  if (hardGuard.blocked) {
192
194
  return {
package/state-media.js ADDED
@@ -0,0 +1,173 @@
1
+ /**
2
+ * state-media.js — 参谋附件图片落盘、路径解析与档案目标目录映射
3
+ *
4
+ * 【核心职责】
5
+ * 承载 `resolveSessionWorkspaceCwd`、`archiveTargetForRoot`、`persistChiefImagesToWorkspace` 与
6
+ * `admitChiefImages`(含 `@deepseek-ai/dsh-attachment` 惰性加载),处理多模态附件安全入库。
7
+ *
8
+ * 【边界约定】
9
+ * - 仅依赖 `state-schema.js` 的纯函数(如 `clamp`),不反向导入 `chief-state.js` 状态锁层。
10
+ */
11
+
12
+ import fs from 'node:fs'
13
+ import path from 'node:path'
14
+ import { clamp } from './state-schema.js'
15
+
16
+ let dshAttachmentModulePromise = null
17
+
18
+ export async function loadDshAttachment() {
19
+ if (!dshAttachmentModulePromise) {
20
+ dshAttachmentModulePromise = import('@deepseek-ai/dsh-attachment').catch(() => null)
21
+ }
22
+ return dshAttachmentModulePromise
23
+ }
24
+
25
+ const CHIEF_MAX_IMAGES = 4
26
+
27
+ const CHIEF_IMAGE_MEDIA_TYPES = new Set(['image/png', 'image/jpeg', 'image/webp', 'image/gif'])
28
+
29
+ export function normalizeUploadedImage(raw, idx = 0) {
30
+ if (!raw || typeof raw !== 'object') return null
31
+ let mediaType = String(raw.mediaType || raw.mimeType || raw.type || '').trim().toLowerCase()
32
+ let data = String(raw.data || raw.base64 || '').trim()
33
+ const dataUrlMatch = data.match(/^data:([^;]+);base64,(.+)$/is)
34
+ if (dataUrlMatch) {
35
+ if (!mediaType) mediaType = dataUrlMatch[1].trim().toLowerCase()
36
+ data = dataUrlMatch[2].trim()
37
+ }
38
+ if (mediaType === 'image/jpg') mediaType = 'image/jpeg'
39
+ data = data.replace(/\s+/g, '')
40
+ if (!CHIEF_IMAGE_MEDIA_TYPES.has(mediaType) || !data) return null
41
+ const ext = mediaType === 'image/jpeg' ? 'jpg' : (mediaType.split('/')[1] || 'png')
42
+ const name = typeof raw.name === 'string' && raw.name.trim()
43
+ ? clamp(raw.name.trim(), 80)
44
+ : `chief-image-${idx + 1}.${ext}`
45
+ return { name, mediaType, data }
46
+ }
47
+
48
+ export function resolveSessionWorkspaceCwd(deps, sessionId) {
49
+ const rootId = (deps && typeof deps.resolveRootSessionId === 'function' ? deps.resolveRootSessionId(sessionId) : '') || sessionId
50
+ try {
51
+ if (deps && typeof deps.getSessionCwd === 'function') {
52
+ const c = deps.getSessionCwd(rootId) || deps.getSessionCwd(sessionId)
53
+ if (c && fs.existsSync(c)) return c
54
+ }
55
+ if (deps && typeof deps.boardForSession === 'function' && typeof deps.boardFileFor === 'function') {
56
+ const b = deps.boardForSession(deps.boardFileFor(rootId))
57
+ const sess = b && b.sessions && (b.sessions[rootId] || b.sessions[sessionId])
58
+ if (sess && sess.cwd && fs.existsSync(sess.cwd)) return sess.cwd
59
+ }
60
+ } catch {}
61
+ return process.cwd()
62
+ }
63
+
64
+ export function archiveTargetForRoot(deps, rootId, extra = '') {
65
+ const opts = extra && typeof extra === 'object' ? extra : { cabinetId: String(extra || '') }
66
+ const vaultScope = opts.vaultScope === 'global' ? 'global' : 'session'
67
+ const sharedFile = deps && (typeof deps.sharedBoardFile === 'function' ? deps.sharedBoardFile() : deps.sharedBoardFile)
68
+ const cwd = resolveSessionWorkspaceCwd(deps, rootId)
69
+ let cab = opts.cabinetId ? String(opts.cabinetId).trim() : ''
70
+ if (vaultScope !== 'global' && !cab && deps && typeof deps.boardForSession === 'function' && typeof deps.boardFileFor === 'function' && rootId && rootId !== 'global') {
71
+ try {
72
+ const b = deps.boardForSession(deps.boardFileFor(rootId))
73
+ if (b && typeof b.activeCabinetId === 'string') cab = b.activeCabinetId.trim()
74
+ } catch {}
75
+ }
76
+ return {
77
+ customSharedBoardFile: sharedFile || '',
78
+ cwd,
79
+ vaultScope,
80
+ ...(vaultScope !== 'global' && rootId && rootId !== 'global' ? { rootSessionId: String(rootId).trim() } : {}),
81
+ ...(cab ? { cabinetId: cab } : {}),
82
+ }
83
+ }
84
+
85
+ /**
86
+ * Chief-of-Staff visibility matrix (Three-Tier Hook Architecture):
87
+ * - Session Working Cabinet: Chief can always read session items + `recentlyUnpinnedWatch`.
88
+ * - Global Vault: Unorganized global items (without hooks) are 0-token invisible to Chief!
89
+ * Organized global items expose ONLY lightweight `globalHookIndex` (`hasHook: true`),
90
+ * until Chief explicitly pulls/mounts them (`chiefMountedSessions` / `chiefPulledSessions`).
91
+ * - Precipitated Cold Vault: 100% invisible to Chief (0 disk read, 0 hook leak) unless User explicitly `flippedOut`!
92
+ */
93
+
94
+ export function persistChiefImagesToWorkspace(deps, sessionId, rawImages) {
95
+ const list = Array.isArray(rawImages) ? rawImages.slice(0, CHIEF_MAX_IMAGES) : []
96
+ if (!list.length) return []
97
+ const normalized = list.map((item, idx) => normalizeUploadedImage(item, idx)).filter(Boolean)
98
+ if (!normalized.length) return []
99
+
100
+ const cwd = resolveSessionWorkspaceCwd(deps, sessionId)
101
+ const uploadDir = path.join(cwd, '.dsh-chief', 'uploads')
102
+ fs.mkdirSync(uploadDir, { recursive: true })
103
+
104
+ const d = new Date()
105
+ const stamp = [
106
+ d.getFullYear(),
107
+ String(d.getMonth() + 1).padStart(2, '0'),
108
+ String(d.getDate()).padStart(2, '0'),
109
+ ].join('') + '-' + [
110
+ String(d.getHours()).padStart(2, '0'),
111
+ String(d.getMinutes()).padStart(2, '0'),
112
+ String(d.getSeconds()).padStart(2, '0'),
113
+ ].join('')
114
+
115
+ const saved = []
116
+ for (let idx = 0; idx < normalized.length; idx += 1) {
117
+ const img = normalized[idx]
118
+ const ext = img.mediaType === 'image/jpeg' ? 'jpg' : (img.mediaType.split('/')[1] || 'png')
119
+ const baseRaw = path.basename(String(img.name || `image-${idx + 1}`), path.extname(String(img.name || '')))
120
+ const safeName = baseRaw.replace(/[^a-zA-Z0-9._-]+/g, '-').replace(/^-+|-+$/g, '').slice(0, 48) || `image-${idx + 1}`
121
+ const fileName = `${stamp}-${idx + 1}-${safeName}.${ext}`
122
+ const absPath = path.join(uploadDir, fileName)
123
+ const buf = Buffer.from(img.data, 'base64')
124
+ fs.writeFileSync(absPath, buf)
125
+ saved.push({
126
+ index: idx + 1,
127
+ path: absPath,
128
+ name: img.name || fileName,
129
+ mediaType: img.mediaType,
130
+ bytes: buf.length,
131
+ })
132
+ }
133
+ return saved
134
+ }
135
+
136
+ export async function admitChiefImages(deps, rawImages) {
137
+ const list = Array.isArray(rawImages) ? rawImages.slice(0, CHIEF_MAX_IMAGES) : []
138
+ if (!list.length) return []
139
+ const normalized = list.map((item, idx) => normalizeUploadedImage(item, idx)).filter(Boolean)
140
+ if (!normalized.length) {
141
+ throw new Error('上传的图片格式不受支持(仅支持 PNG / JPEG / WebP / GIF Base64)')
142
+ }
143
+
144
+ if (deps && typeof deps.admitImagesOverride === 'function') {
145
+ const refs = await deps.admitImagesOverride(normalized)
146
+ return (Array.isArray(refs) ? refs : []).filter(Boolean).map(attachment => ({ type: 'image', attachment }))
147
+ }
148
+
149
+ const attachmentsSvc = deps && typeof deps.getAttachments === 'function'
150
+ ? deps.getAttachments()
151
+ : (deps && deps.runtime && typeof deps.runtime.get === 'function' ? deps.runtime.get('attachments') : null)
152
+ if (!attachmentsSvc) {
153
+ throw new Error('当前 DSH 运行环境未挂载 attachments 图片服务,无法处理图片上传')
154
+ }
155
+
156
+ const attMod = await loadDshAttachment()
157
+ if (attMod && typeof attMod.admitEncodedImages === 'function') {
158
+ const refs = await attMod.admitEncodedImages(attachmentsSvc, normalized)
159
+ return (Array.isArray(refs) ? refs : []).map(attachment => ({ type: 'image', attachment }))
160
+ }
161
+
162
+ if (typeof attachmentsSvc.saveImages === 'function') {
163
+ const payload = normalized.map(img => ({
164
+ data: Uint8Array.from(Buffer.from(img.data, 'base64')),
165
+ mediaType: img.mediaType,
166
+ name: img.name,
167
+ }))
168
+ const refs = await attachmentsSvc.saveImages(payload)
169
+ return (Array.isArray(refs) ? refs : []).map(attachment => ({ type: 'image', attachment }))
170
+ }
171
+
172
+ throw new Error('attachments 服务缺少 saveImages / admitEncodedImages 接口')
173
+ }