@sshirkit/dsh-orchestrator 1.0.2 → 1.0.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/supervise.js CHANGED
@@ -85,11 +85,6 @@ const NOTICE_HINT = [
85
85
  'B) 跑偏或打转:禁止回复「巡检:正常」,请直接用调研工具或 send_message 纠偏;',
86
86
  'C) 需中止或换路:禁止回复「巡检:正常」,请先说明原因并用中断/控制或已有工具调整执行路线。',
87
87
  ]
88
- const ATTENTION_WARNING = '待确认审计项不得验收为通过;「巡检:正常」仅表示运行方向无须干预,不代表审计通过。'
89
- const ATTENTION_HINT = [
90
- '请对仍在运行的子代理作出决定(本回合已硬禁止调用 todo_write):',
91
- ...NOTICE_HINT.slice(1),
92
- ]
93
88
 
94
89
  // ---------------------------------------------------------------------------
95
90
  // Event adapters: the one place that knows the host field names.
@@ -694,21 +689,9 @@ function formatDuration(ms) {
694
689
  return `${seconds}s`
695
690
  }
696
691
 
697
- function renderAttentionRow(row, number, childId, label, textLimit) {
698
- const status = row.auditState === 'pending' ? '审计仍 pending' : '审计未通过(failed)'
699
- const lines = [
700
- `${number}) 子代理 ${childId}(已结束,${status};不得验收为通过)`,
701
- ` 任务:${label}`,
702
- ]
703
- const summary = oneLine(row.summary, textLimit)
704
- if (summary !== '') lines.push(` 审计摘要:${summary}`)
705
- return lines.join('\n')
706
- }
707
-
708
692
  function renderRow(row, number, textLimit, at, threshold) {
709
693
  const childId = typeof row.childId === 'string' && row.childId !== '' ? row.childId : '(未知)'
710
694
  const label = typeof row.label === 'string' && row.label !== '' ? row.label : '未命名'
711
- if (row.kind === 'attention') return renderAttentionRow(row, number, childId, label, textLimit)
712
695
 
713
696
  const started = asNumber(row.startedAt)
714
697
  const runMs = started === undefined ? 0 : Math.max(0, at - started)
@@ -751,8 +734,8 @@ function renderRow(row, number, textLimit, at, threshold) {
751
734
 
752
735
  /**
753
736
  * Build one parent's panoramic notice. Legacy rows without `kind` are treated
754
- * as triggers. Trim excerpts first, then omit siblings before triggers and
755
- * audit warnings. The unabridged rows remain available to the delivery adapter.
737
+ * as triggers. Trim excerpts first, then omit siblings before triggers.
738
+ * The unabridged running and sibling rows remain available to the delivery adapter.
756
739
  * `index`/`max` describe the trigger budget (`max = 0` means unlimited).
757
740
  */
758
741
  export function composeNotice(rows, { now, index, max, maxChars = 2000, repeatThreshold = 3 } = {}) {
@@ -762,12 +745,10 @@ export function composeNotice(rows, { now, index, max, maxChars = 2000, repeatTh
762
745
  const limitChars = positiveInteger(maxChars, DEFAULTS.noticeMaxChars)
763
746
  const threshold = positiveInteger(repeatThreshold, DEFAULTS.repeatThreshold)
764
747
  const allRows = Array.isArray(rows) ? rows.filter((row) => row !== null && typeof row === 'object') : []
748
+ // Ignore legacy attention rows rather than presenting ended children as running.
765
749
  const triggers = allRows.filter((row) => row.kind !== 'attention' && row.kind !== 'sibling')
766
- const attention = allRows.filter((row) => row.kind === 'attention')
767
750
  const siblings = allRows.filter((row) => row.kind === 'sibling')
768
- // Keep the first trigger and at least one audit warning ahead of extra rows.
769
- const orderedRows = [...triggers.slice(0, 1), ...attention, ...triggers.slice(1), ...siblings]
770
- const hint = attention.length > 0 ? ATTENTION_HINT : NOTICE_HINT
751
+ const orderedRows = [...triggers, ...siblings]
771
752
 
772
753
  const header =
773
754
  noticeMax > 0
@@ -776,13 +757,12 @@ export function composeNotice(rows, { now, index, max, maxChars = 2000, repeatTh
776
757
 
777
758
  const build = (keep, textLimit) => {
778
759
  const parts = [header]
779
- if (attention.length > 0) parts.push(ATTENTION_WARNING)
780
760
  for (let i = 0; i < keep; i += 1) {
781
761
  parts.push(renderRow(orderedRows[i], i + 1, textLimit, at, threshold))
782
762
  }
783
763
  const dropped = orderedRows.length - keep
784
764
  if (dropped > 0) parts.push(`另有 ${dropped} 个子代理未列出。`)
785
- parts.push(...hint)
765
+ parts.push(...NOTICE_HINT)
786
766
  return parts.join('\n')
787
767
  }
788
768
 
@@ -832,16 +812,15 @@ function errorMessage(error) {
832
812
  /**
833
813
  * The stateful half. Every host capability is injected:
834
814
  *
835
- * - `config`: a plain object read on every `tick`, so an interval change applies
836
- * from the next tick; partially specified fields fall back to `DEFAULTS`.
815
+ * - `config`: an object or a synchronous getter keyed by parent ID. It is read
816
+ * when tracking, restoring, and inspecting children; missing fields use `DEFAULTS`.
837
817
  * `intervalSeconds` is the minimum age before a child can trigger a notice.
838
818
  * - `now()`, `isParentAlive(parentId)`, `isChildAlive(childId)`,
839
819
  * `readEvents(childId)`, `hasPendingNotice(parentId)`, optional
840
- * `hasActiveSupervisionTurn(parentId)` and `listAttentionItems(parentId)`,
820
+ * `hasActiveSupervisionTurn(parentId)`,
841
821
  * `deliver(parentId, text, childIds, { rows, composeMeta })`, `logger`.
842
822
  * The adapters other than `now` may return a value or a Promise.
843
- * - `deliver` receives active child ids only. Rows tagged `attention` are ended
844
- * children with unconfirmed audits; `sibling` rows are display-only.
823
+ * - `deliver` receives active child ids only. `sibling` rows are display-only.
845
824
  * - `track` accepts optional child metadata: `writeScope`, `readOnly`, `cwd`.
846
825
  *
847
826
  * `tick` never throws because of one child or parent: read, summarize, pending
@@ -879,6 +858,37 @@ export function createSupervisor(options = {}) {
879
858
  ? scope.map((claim) => isNormalizedScope([claim]) ? { ...claim } : claim)
880
859
  : scope
881
860
 
861
+ const configFor = (parentId) => {
862
+ try {
863
+ return readConfig(typeof opts.config === 'function' ? opts.config(parentId) : opts.config)
864
+ } catch (error) {
865
+ warn(`orchestrator: supervision: cannot read config for ${parentId}: ${errorMessage(error)}`)
866
+ return readConfig({ enabled: false })
867
+ }
868
+ }
869
+ const isEnabled = (config) => config.enabled && (config.unlimited || config.maxNoticesPerChild > 0)
870
+ const withinBudget = (entry, config) => config.unlimited || entry.noticesSent < config.maxNoticesPerChild
871
+
872
+ function refreshDeadline(entry, intervalMs) {
873
+ // Preserve an advance made for a skipped notice while replacing the interval.
874
+ entry.nextDueAt += intervalMs - entry.intervalMs
875
+ entry.intervalMs = intervalMs
876
+ }
877
+
878
+ function refreshConfig(matchesParent = () => true) {
879
+ const intervals = new Map()
880
+ const changed = []
881
+ for (const entry of entries.values()) {
882
+ if (!matchesParent(entry.parentId)) continue
883
+ if (!intervals.has(entry.parentId)) intervals.set(entry.parentId, intervalMsOf(configFor(entry.parentId)))
884
+ const intervalMs = intervals.get(entry.parentId)
885
+ if (intervalMs === entry.intervalMs) continue
886
+ refreshDeadline(entry, intervalMs)
887
+ changed.push(entry.childId)
888
+ }
889
+ return changed
890
+ }
891
+
882
892
  const track = (entry) => {
883
893
  if (entry === null || typeof entry !== 'object') return
884
894
  const childId = entry.childId
@@ -886,6 +896,7 @@ export function createSupervisor(options = {}) {
886
896
  if (typeof childId !== 'string' || childId === '') return
887
897
  if (typeof parentId !== 'string' || parentId === '') return
888
898
 
899
+ const intervalMs = intervalMsOf(configFor(parentId))
889
900
  const runId = idOrNull(entry.runId)
890
901
  const previous = entries.get(childId)
891
902
  if (runId !== null && previous?.runId === runId && previous.parentId === parentId) {
@@ -894,10 +905,9 @@ export function createSupervisor(options = {}) {
894
905
  if (typeof entry.readOnly === 'boolean') previous.readOnly = entry.readOnly
895
906
  if (entry.writeScope !== undefined) previous.writeScope = copyScope(entry.writeScope)
896
907
  if (entry.cwd !== undefined) previous.cwd = entry.cwd
908
+ refreshDeadline(previous, intervalMs)
897
909
  return
898
910
  }
899
- const config = readConfig(opts.config)
900
- const intervalMs = intervalMsOf(config)
901
911
  const startedAt = asNumber(entry.startedAt) ?? currentTime()
902
912
  // A resumed worker is a new run of the same task: the interrupt that stopped it was
903
913
  // not the child's fault, so its notice budget starts over. Its log still holds the
@@ -947,7 +957,7 @@ export function createSupervisor(options = {}) {
947
957
  const runId = idOrNull(currentRunId) ?? previous?.runId ?? savedRunId
948
958
  const sameRun = runId === savedRunId
949
959
  const at = timeOr(now, currentTime())
950
- const configuredInterval = intervalMsOf(readConfig(opts.config))
960
+ const configuredInterval = intervalMsOf(configFor(parentId))
951
961
  const intervalMs = sameRun ? positiveNumber(cursor.intervalMs, configuredInterval) : configuredInterval
952
962
  const head = countOr(currentHeadSeq, 0)
953
963
  const startedAt = sameRun ? timeOr(cursor.startedAt, at) : at
@@ -959,8 +969,8 @@ export function createSupervisor(options = {}) {
959
969
  if (previous?.runId === runId && (previous.lastSeq > lastSeq || previous.noticesSent > noticesSent ||
960
970
  (previous.lastInspectionAt ?? -Infinity) > (lastInspectionAt ?? -Infinity))) return false
961
971
  entries.set(childId, {
962
- childId, parentId, runId, startedAt, intervalMs, lastSeq, runSinceSeq, lastInspectionAt, noticesSent,
963
- nextDueAt: sameRun ? Math.max(at, savedDeadline) : at + intervalMs,
972
+ childId, parentId, runId, startedAt, intervalMs: configuredInterval, lastSeq, runSinceSeq, lastInspectionAt, noticesSent,
973
+ nextDueAt: sameRun ? Math.max(at, savedDeadline + configuredInterval - intervalMs) : at + configuredInterval,
964
974
  label: typeof cursor.label === 'string' ? cursor.label : previous?.label ?? '',
965
975
  readOnly: typeof cursor.readOnly === 'boolean' ? cursor.readOnly : previous?.readOnly ?? false,
966
976
  writeScope: copyScope(cursor.writeScope ?? previous?.writeScope),
@@ -998,46 +1008,21 @@ export function createSupervisor(options = {}) {
998
1008
  return false
999
1009
  }
1000
1010
 
1001
- const getAttentionRows = async (parentId) => {
1002
- try {
1003
- const items = typeof opts.listAttentionItems === 'function' ? await opts.listAttentionItems(parentId) : []
1004
- if (!Array.isArray(items)) return []
1005
- return items
1006
- .filter((item) => typeof item?.childId === 'string' && item.childId.trim() !== '' &&
1007
- (item.auditState === 'pending' || item.auditState === 'failed'))
1008
- .map((item) => ({ ...item, kind: 'attention' }))
1009
- } catch (error) {
1010
- warn(`orchestrator: supervision: listAttentionItems(${parentId}) failed: ${errorMessage(error)}`)
1011
- return []
1012
- }
1013
- }
1014
-
1015
1011
  const tick = async (nowOverride) => {
1016
- let config
1017
- try {
1018
- config = readConfig(opts.config)
1019
- } catch (error) {
1020
- // A malformed config object must not break the host's timer.
1021
- warn(`orchestrator: supervision: cannot read config: ${errorMessage(error)}`)
1022
- return
1023
- }
1024
- // Off means fully off: no cleanup, no wake-up, no registry changes.
1025
- if (!config.enabled) return
1026
- // A zero budget is the second way to switch supervision off, unless the unlimited
1027
- // switch overrides it. The registry is deliberately kept: a child that is still
1028
- // running must be supervised again the moment the user raises the budget or turns
1029
- // the unlimited switch on, without waiting for a re-dispatch.
1030
- if (!config.unlimited && config.maxNoticesPerChild === 0) return
1031
1012
  if (ticking) return
1032
1013
  ticking = true
1033
1014
  try {
1034
1015
  const at = asNumber(nowOverride) ?? currentTime()
1035
- const intervalMs = intervalMsOf(config)
1016
+ const configs = new Map()
1036
1017
 
1037
1018
  // A parent that is gone takes every registration with it, before any reads.
1038
1019
  const parentIds = new Set()
1039
1020
  for (const entry of entries.values()) parentIds.add(entry.parentId)
1040
1021
  for (const parentId of parentIds) {
1022
+ const config = configFor(parentId)
1023
+ configs.set(parentId, config)
1024
+ // Retain paused registrations so live settings can re-arm them.
1025
+ if (!isEnabled(config)) continue
1041
1026
  let alive = true
1042
1027
  if (typeof opts.isParentAlive === 'function') {
1043
1028
  try {
@@ -1060,6 +1045,12 @@ export function createSupervisor(options = {}) {
1060
1045
  // A callback may have forgotten it while we awaited a previous entry.
1061
1046
  if (entries.get(entry.childId) !== entry) continue
1062
1047
 
1048
+ const config = configs.get(entry.parentId)
1049
+ if (!config) continue
1050
+ const intervalMs = intervalMsOf(config)
1051
+ refreshDeadline(entry, intervalMs)
1052
+ if (!isEnabled(config)) continue
1053
+
1063
1054
  let childAlive = true
1064
1055
  if (typeof opts.isChildAlive === 'function') {
1065
1056
  try {
@@ -1083,22 +1074,13 @@ export function createSupervisor(options = {}) {
1083
1074
  }
1084
1075
  batch.push(child)
1085
1076
 
1086
- // A changed interval takes effect at once. Shift the deadline by the same
1087
- // delta, so shrinking can make it due right now and growing delays it,
1088
- // without losing an advance already made for a skipped notice.
1089
- if (entry.intervalMs !== intervalMs) {
1090
- const scheduledFrom = entry.nextDueAt - entry.intervalMs
1091
- entry.nextDueAt = scheduledFrom + intervalMs
1092
- entry.intervalMs = intervalMs
1093
- }
1094
-
1095
1077
  if (at < entry.nextDueAt) {
1096
1078
  child.status = '同行在跑,暂未到下一次巡检点'
1097
1079
  continue
1098
1080
  }
1099
1081
 
1100
1082
  // Retain capped children so a config change can resume supervision.
1101
- if (!config.unlimited && entry.noticesSent >= config.maxNoticesPerChild) {
1083
+ if (!withinBudget(entry, config)) {
1102
1084
  child.status = '同行在跑,巡检预算已用完'
1103
1085
  continue
1104
1086
  }
@@ -1146,8 +1128,8 @@ export function createSupervisor(options = {}) {
1146
1128
  child.summary = summary
1147
1129
  }
1148
1130
 
1149
- const nextDueAt = at + intervalMs
1150
1131
  for (const [parentId, batch] of activeByParent) {
1132
+ const nextDueAt = at + intervalMsOf(configFor(parentId))
1151
1133
  if (!batch.some((child) => child.summary && isCurrent(child))) continue
1152
1134
 
1153
1135
  // Pending or claimed notices delay the whole batch, without spending budget
@@ -1162,9 +1144,11 @@ export function createSupervisor(options = {}) {
1162
1144
  continue
1163
1145
  }
1164
1146
 
1165
- const attentionRows = await getAttentionRows(parentId)
1166
1147
  const active = batch.filter(isCurrent)
1167
- const triggers = active.filter(({ summary }) => summary !== undefined)
1148
+ const config = configFor(parentId)
1149
+ if (!isEnabled(config)) continue
1150
+ const triggers = active.filter(({ entry, summary }) =>
1151
+ summary !== undefined && entry.nextDueAt <= at && withinBudget(entry, config))
1168
1152
  if (triggers.length === 0) continue
1169
1153
 
1170
1154
  const index = triggers.reduce((highest, { entry }) => Math.max(highest, entry.noticesSent), 0) + 1
@@ -1183,7 +1167,6 @@ export function createSupervisor(options = {}) {
1183
1167
  newEvents: summary.newEvents,
1184
1168
  semantic: summary.semantic,
1185
1169
  }))
1186
- const activeIds = new Set(active.map(({ entry }) => entry.childId))
1187
1170
  // A child whose log could not be inspected retains the existing skip behavior.
1188
1171
  const siblingRows = active.filter(({ status }) => status !== undefined).map(({ entry, status }) => ({
1189
1172
  childId: entry.childId,
@@ -1192,8 +1175,8 @@ export function createSupervisor(options = {}) {
1192
1175
  startedAt: entry.startedAt,
1193
1176
  status,
1194
1177
  }))
1195
- const childIds = [...rows, ...siblingRows].map(({ childId }) => childId)
1196
- rows.push(...attentionRows.filter(({ childId }) => !activeIds.has(childId)), ...siblingRows)
1178
+ rows.push(...siblingRows)
1179
+ const childIds = rows.map(({ childId }) => childId)
1197
1180
  const composeMeta = {
1198
1181
  now: at,
1199
1182
  index,
@@ -1218,9 +1201,10 @@ export function createSupervisor(options = {}) {
1218
1201
 
1219
1202
  if (result === 'stale') continue
1220
1203
  if (result === 'queued') {
1221
- for (const { entry, summary } of active.filter(isCurrent)) {
1222
- entry.nextDueAt = nextDueAt
1223
- if (summary === undefined) continue
1204
+ for (const child of active.filter(isCurrent)) {
1205
+ const { entry, summary } = child
1206
+ entry.nextDueAt = at + entry.intervalMs
1207
+ if (!triggers.includes(child)) continue
1224
1208
  entry.noticesSent += 1
1225
1209
  // A tail window can report a lower max than a previous read; never go backwards.
1226
1210
  entry.lastSeq = Math.max(entry.lastSeq, summary.lastSeq)
@@ -1248,5 +1232,5 @@ export function createSupervisor(options = {}) {
1248
1232
  const has = (childId) => entries.has(childId)
1249
1233
  const size = () => entries.size
1250
1234
 
1251
- return { track, forget, has, tick, size, exportCursor, exportCursors, hydrateCursor, hydrateCursors }
1235
+ return { track, forget, has, tick, size, refreshConfig, exportCursor, exportCursors, hydrateCursor, hydrateCursors }
1252
1236
  }
@@ -35,7 +35,7 @@ export function switchNoticeText(enabled) {
35
35
  return (
36
36
  '【插件状态变更】调度模式已切换为「关闭」。' +
37
37
  '你现在可以直接使用 read / write / edit / bash / glob / grep 等常规工具执行任务,' +
38
- '不要再调用 delegate 或 orchestrate(它们已被拦截)。'
38
+ '不要再调用 delegate、orchestrate、delegate_status 或 worktree_manage(它们已被拦截)。'
39
39
  )
40
40
  }
41
41
 
@@ -79,7 +79,7 @@ export function createSwitchNotices({ readEnabled, logger } = {}) {
79
79
  if (typeof agentId !== 'string' || agentId === '') return
80
80
  let current
81
81
  try {
82
- current = readEnabled() === true
82
+ current = readEnabled(agentId) === true
83
83
  } catch (error) {
84
84
  warn(`orchestrator: switch notice: cannot read the switch: ${error instanceof Error ? error.message : String(error)}`)
85
85
  return