@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/index.js CHANGED
@@ -2,22 +2,23 @@ import { randomUUID } from 'node:crypto'
2
2
  import { existsSync } from 'node:fs'
3
3
  import z from '@deepseek-ai/schemastery'
4
4
  import { defineTool } from '@deepseek-ai/dsh-tools'
5
- import { DELEGATE_STATUS_TOOL_NAME, ORCHESTRATE_TOOL } from './api.js'
5
+ import { DELEGATE_STATUS_TOOL_NAME, DELEGATE_TOOL, ORCHESTRATE_TOOL, disabledToolMessage } from './api.js'
6
6
  import { createCatalogPublisher } from './catalog.js'
7
7
  import { createDelegateStatusTool } from './delegate-status.js'
8
8
  import {
9
- READ_ONLY_NOTICE, auditNotice, captureDispatchBaseline, createDelegateTool, settleDispatchWrite,
10
- worktreeAuditSummary, worktreePromptNote,
9
+ READ_ONLY_NOTICE, assertReadOnlyArgumentEnabled, createDelegateTool, validateDispatchWrite,
10
+ worktreeDetails, worktreePromptNote,
11
11
  } from './delegate.js'
12
- import { createSupervisionTurnState, installGate, isDelegatedChild } from './gate.js'
13
- import { auditGitBaseline, captureGitBaseline } from './git-audit.js'
12
+ import { createSupervisionTurnState, installGate, isDelegatedChild, isDispatchTool } from './gate.js'
14
13
  import { createOrchestrateTool } from './orchestrate.js'
14
+ import { createReadIndex, PEER_CONSULT_SOURCE_KIND } from './read-index.js'
15
+ import { mainAgentRule } from './rules.js'
15
16
  import { RETRY_SOURCE_KIND, createRetry } from './retry.js'
16
17
  import {
17
18
  createActionLedger, evaluateWakeupGate, inspectHostChildState, makeResumeActionKey,
18
19
  makeSettleActionKey, reconcileOnStartup,
19
20
  } from './reconcile.js'
20
- import { createSessionTools, mountSessionToolsRemote } from './session-tools.js'
21
+ import { createSessionTools, mountSessionToolsRemote, rootSessionIdOf } from './session-tools.js'
21
22
  import { createStateStore } from './state-store.js'
22
23
  import { normalizeScope } from './write-scope.js'
23
24
  import {
@@ -31,15 +32,15 @@ import {
31
32
  summarize,
32
33
  } from './supervise.js'
33
34
  import { SWITCH_SOURCE_KIND, createSwitchNotices } from './switch-notice.js'
34
- import { INLINE_AUDIT_SOURCE_KIND, createDispatchTimeline, formatInlineAuditNotice } from './timeline.js'
35
+ import { createDispatchTimeline } from './timeline.js'
35
36
  import { DEFAULT_ALLOWED_TOOLS, NATIVE_TEAM_TOOLS, installToolSurface } from './tool-surface.js'
36
- import { isDispatchEnabled } from './worker.js'
37
+ import { configValue, isDispatchEnabled, workerRouteFromConfig } from './worker.js'
37
38
  import { createWriteLeases } from './write-lease.js'
38
- import { formatWorktreeError, releaseWriteScope } from './write-scope-tool.js'
39
+ import { formatWorktreeError, leaseFailure, releaseWriteScope, writeScopeFailure, writeScopeNotice } from './write-scope-tool.js'
39
40
  import { createWorktreeManager, probeGitRepo } from './worktree.js'
40
41
  import { createPersistentWorktreeTool } from './worktree-tool.js'
41
42
 
42
- export { DEFAULT_ALLOWED_TOOLS, INLINE_AUDIT_SOURCE_KIND, SUPERVISE_SOURCE_KIND, SWITCH_SOURCE_KIND }
43
+ export { DEFAULT_ALLOWED_TOOLS, SUPERVISE_SOURCE_KIND, SWITCH_SOURCE_KIND }
43
44
 
44
45
  export const name = '@sshirkit/dsh-orchestrator'
45
46
 
@@ -56,11 +57,13 @@ export const inject = ['sessionProjections', 'tools', 'subagents', 'agents', 'se
56
57
  * route is read on every delegation, so it applies from the next `delegate` call.
57
58
  */
58
59
  export const Config = z.object({
59
- /** Hide the creation tools from top-level agents. Delegated children keep them. */
60
+ /** Gate dispatch and governance tools by the root session's effective switch. */
60
61
  enabled: z.boolean().default(true).volatile(),
61
62
  worktreeIsolationEnabled: z.boolean().default(true)
62
- .description('Git 仓库下对写任务默认启用独立 Worktree 隔离与 git diff/log 审计(delegate 与 orchestrate 按 item 隔离),非 Git 目录自动降级逻辑快照')
63
+ .description('Git 仓库下对写任务默认启用独立 Worktree 隔离(orchestrate 按 item 隔离),非 Git 目录使用共享工作区')
63
64
  .volatile(),
65
+ readOnlyEnabled: z.boolean().default(false).volatile(),
66
+ peerReadOnlyConsultEnabled: z.boolean().default(false).volatile(),
64
67
  /**
65
68
  * The only tool whitelist there is. Whitelist-driven: only the names listed here stay
66
69
  * available to the main agent, and every other host, MCP or plugin tool is automatically
@@ -108,7 +111,7 @@ export const Config = z.object({
108
111
  /** How long a child may run before its parent is woken with one summary notice, in seconds. */
109
112
  superviseIntervalSeconds: z.number().min(10).max(86400).step(1).default(600).volatile(),
110
113
  /** Notices allowed per child; 0 turns supervision off unless superviseUnlimited is on. */
111
- superviseMaxNoticesPerChild: z.number().min(0).max(20).default(3).volatile(),
114
+ superviseMaxNoticesPerChild: z.number().min(0).max(20).step(1).default(3).volatile(),
112
115
  /** Ignore the notice cap and keep supervising until the child stops, delivers, or ends. */
113
116
  superviseUnlimited: z.boolean().default(false).volatile(),
114
117
  /** Also notify when a child produced no new events; off saves a model turn. */
@@ -117,17 +120,6 @@ export const Config = z.object({
117
120
  restoreTodoOnSupervision: z.boolean().default(true).volatile(),
118
121
  })
119
122
 
120
- /** Read one config field whether it is a schemastery ref or a plain value. */
121
- function configValue(config, key, fallback) {
122
- try {
123
- const field = config?.[key]
124
- const value = typeof field?.get === 'function' ? field.get() : field
125
- return value === undefined || value === null ? fallback : value
126
- } catch {
127
- return fallback
128
- }
129
- }
130
-
131
123
  function messageOf(error) {
132
124
  return error instanceof Error ? error.message : String(error)
133
125
  }
@@ -378,53 +370,9 @@ function filterSupervisionMessages(messages, { liveNoticeIds, rebuildNotice, age
378
370
  })
379
371
  }
380
372
 
381
- function settledAuditEntries(timeline, parentId, messages) {
382
- const matches = new Map()
383
- for (const message of messages) {
384
- const source = message?.source
385
- if (source?.kind !== 'subagent-settled') continue
386
- const childId = source.senderSessionId
387
- if (typeof childId !== 'string' || matches.has(childId)) continue
388
- const entry = timeline.get(parentId, childId)
389
- if (entry !== null) matches.set(childId, { childId, entry })
390
- }
391
- return [...matches.values()]
392
- }
393
-
394
- /** Commit delivery only for the exact messages entering the model step. */
395
- function attachAuditMessages({ timeline, agent, messages, createMessage, scheduleReconcileInbox, logger }) {
396
- if (createMessage === undefined) return messages
397
- const parentId = agent.id
398
- const attached = settledAuditEntries(timeline, parentId, messages)
399
- if (attached.length === 0) return messages
400
- let notice
401
- try {
402
- notice = createMessage({
403
- content: [{ type: 'text', text: formatInlineAuditNotice(attached) }],
404
- source: { kind: INLINE_AUDIT_SOURCE_KIND, form: 'notice' },
405
- })
406
- } catch (error) {
407
- try {
408
- logger?.warn?.(`orchestrator: cannot build the inline audit notice: ${messageOf(error)}`)
409
- } catch {
410
- // Neither a message constructor nor a logger may break the parent model step.
411
- }
412
- return messages
413
- }
414
-
415
- let changed = false
416
- for (const { childId, entry } of attached) {
417
- if (entry.auditState !== 'passed' && entry.auditState !== 'failed') continue
418
- changed = timeline.markAuditDelivered({ parentId, childId, via: 'inline-pre-step' }) || changed
419
- }
420
- if (changed) scheduleReconcileInbox?.(parentId)
421
- return [...messages, notice]
422
- }
423
-
424
373
  /** Filter claimed inbox messages before any downstream handler can add model context. */
425
374
  export function createSupervisionPreStep({
426
375
  ctx, config, supervisor, supervisionTurnState, todoTracker, nextStep, rebuildNotice, retainNotices,
427
- auditTimeline, loadAuditCreator, scheduleReconcileInbox,
428
376
  liveNoticeIds = (_message, ids) => ids.filter((id) => supervisor.has(id) && ctx?.agents?.get?.(id) !== undefined),
429
377
  }) {
430
378
  const run = async (payload, next) => {
@@ -482,25 +430,12 @@ export function createSupervisionPreStep({
482
430
  current = reconcile(decision.messages)
483
431
  }
484
432
  if (wasSupervision && !current.hasSubstantive) return { kind: 'reject' }
485
- let createMessage
486
- if (auditTimeline !== undefined && current.remaining.some((message) =>
487
- message?.source?.kind === 'subagent-settled' && auditTimeline.get(agent.id, message.source.senderSessionId) !== null)) {
488
- createMessage = await loadAuditCreator?.()
489
- current = reconcile(decision.messages)
490
- if ((wasSupervision && !current.hasSubstantive) || (pure && !current.hasOrdinary)) {
491
- await restoreOnce()
492
- current = reconcile(decision.messages)
493
- }
494
- }
495
433
  if (payload?.signal?.aborted) {
496
434
  supervisionTurnState.clearTurn(agent.id, payload.turn)
497
435
  return decision
498
436
  }
499
437
  if (wasSupervision && !current.hasSubstantive) return { kind: 'reject' }
500
- const enteringMessages = auditTimeline === undefined ? current.remaining : attachAuditMessages({
501
- timeline: auditTimeline, agent, messages: current.remaining, createMessage, scheduleReconcileInbox, logger: ctx?.logger,
502
- })
503
- return enteringMessages === decision.messages ? decision : { ...decision, messages: enteringMessages }
438
+ return current.remaining === decision.messages ? decision : { ...decision, messages: current.remaining }
504
439
  }
505
440
  return async (payload, next) => {
506
441
  const release = retainNotices?.(payload)
@@ -524,7 +459,7 @@ export function createSupervisionPreStep({
524
459
  */
525
460
  export function createSupervision({
526
461
  ctx, config, logger = ctx?.logger, loadLlm = () => import('@deepseek-ai/dsh-llm'),
527
- supervisionTurnState, listAttentionItems = () => [], isActive = () => true,
462
+ supervisionTurnState, listAttentionItems = () => [], isActive = () => true, resolveSessionConfig,
528
463
  }) {
529
464
  let pendingWarned = false
530
465
  const warn = (message) => {
@@ -621,7 +556,7 @@ export function createSupervision({
621
556
  if (row?.kind !== 'attention') return supervisor.has(id) && isChildAlive(id)
622
557
  attentionById ??= new Map(listAttentionItems(parentId).map((entry) => [entry.childId, entry]))
623
558
  const current = attentionById.get(id)
624
- return current !== undefined && current.auditState === row.auditState && current.attemptSeq === row.attemptSeq
559
+ return current !== undefined && current.attemptSeq === row.attemptSeq
625
560
  })
626
561
  }
627
562
  const liveNoticeIds = (message, ids, parentId) =>
@@ -829,23 +764,15 @@ export function createSupervision({
829
764
  /** The retry notice: same delivery, its own `source.kind`. */
830
765
  const deliverRetry = (parentId, text, childIds) => deliverAs(RETRY_SOURCE_KIND, parentId, text, childIds)
831
766
 
832
- // Live getters: an interval change applies without rebuilding the supervisor.
833
- const liveConfig = {
834
- get enabled() {
835
- return configValue(config, 'superviseEnabled', true) !== false
836
- },
837
- get intervalSeconds() {
838
- return configValue(config, 'superviseIntervalSeconds', 600)
839
- },
840
- get maxNoticesPerChild() {
841
- return configValue(config, 'superviseMaxNoticesPerChild', 3)
842
- },
843
- get unlimited() {
844
- return configValue(config, 'superviseUnlimited', false) === true
845
- },
846
- get notifyOnNoProgress() {
847
- return configValue(config, 'superviseNotifyOnNoProgress', false) === true
848
- },
767
+ const liveConfig = (parentId) => {
768
+ const effective = resolveSessionConfig?.(parentId)
769
+ return {
770
+ enabled: configValue(config, 'superviseEnabled', true) !== false,
771
+ intervalSeconds: effective?.superviseIntervalSeconds ?? configValue(config, 'superviseIntervalSeconds', 600),
772
+ maxNoticesPerChild: effective?.superviseMaxNoticesPerChild ?? configValue(config, 'superviseMaxNoticesPerChild', 3),
773
+ unlimited: effective?.superviseUnlimited ?? (configValue(config, 'superviseUnlimited', false) === true),
774
+ notifyOnNoProgress: configValue(config, 'superviseNotifyOnNoProgress', false) === true,
775
+ }
849
776
  }
850
777
 
851
778
  const supervisor = createSupervisor({
@@ -883,7 +810,7 @@ export function createSupervision({
883
810
  return {
884
811
  supervisor, isParentAlive, isChildAlive, readEvents, headSeq, hasPendingNotice,
885
812
  deliver, deliverRetry, rebuildNotice, liveNoticeIds, scheduleReconcileInbox, pendingNoticeMeta,
886
- claimNotice, releaseClaimedNotices, retainNotices, loadAuditCreator: loadCreator,
813
+ claimNotice, releaseClaimedNotices, retainNotices,
887
814
  }
888
815
  }
889
816
 
@@ -1017,32 +944,6 @@ function reserveDomain(facility) {
1017
944
  return { previous, release }
1018
945
  }
1019
946
 
1020
- const MAX_GIT_BASELINE_BYTES = 32 * 1024
1021
- function smallGitBaseline(baseline) {
1022
- if (baseline?.kind !== 'git-worktree') return undefined
1023
- return Buffer.byteLength(JSON.stringify(baseline)) <= MAX_GIT_BASELINE_BYTES ? baseline : undefined
1024
- }
1025
-
1026
- function restoredGitBaseline(row, worktree) {
1027
- const baseline = row.gitBaseline
1028
- if (!worktree || baseline?.kind !== 'git-worktree' || baseline.baselineId !== row.baselineId ||
1029
- baseline.worktreeId !== worktree.id || baseline.worktreePath !== worktree.worktreePath ||
1030
- baseline.execCwd !== worktree.execCwd || baseline.repoRoot !== worktree.repoRoot ||
1031
- baseline.baseCommit !== worktree.baseCommit || baseline.branch !== worktree.branch) return undefined
1032
- return baseline
1033
- }
1034
-
1035
- function missingBaselineAudit(record) {
1036
- return {
1037
- baselineId: record.baselineId, passed: false, readOnly: record.readOnly,
1038
- isolationLevel: record.worktree ? 'git-worktree' : 'logical-post-audit',
1039
- isolationNote: '历史派发基线无法恢复;不能据此确认写入合规。',
1040
- changedFiles: [],
1041
- violations: [{ code: 'audit-incomplete', path: '.', reason: '缺少可核验的历史派发基线' }],
1042
- summary: { added: 0, modified: 0, deleted: 0, violations: 1, truncated: false },
1043
- }
1044
- }
1045
-
1046
947
  export function apply(ctx, config) {
1047
948
  let facility
1048
949
  let startupError
@@ -1069,8 +970,8 @@ export function apply(ctx, config) {
1069
970
  const timeline = createDispatchTimeline()
1070
971
  const supervisionTurnState = createSupervisionTurnState()
1071
972
  const supervision = createSupervision({
1072
- ctx, config, supervisionTurnState, listAttentionItems: timeline.listAttentionItems,
1073
- isActive: () => !disposing,
973
+ ctx, config, supervisionTurnState,
974
+ isActive: () => !disposing, resolveSessionConfig: (parentId) => sessionTools.resolveSessionConfig(parentId),
1074
975
  })
1075
976
  const writeLeases = createWriteLeases()
1076
977
  const worktrees = createWorktreeManager()
@@ -1079,6 +980,8 @@ export function apply(ctx, config) {
1079
980
  const batchStages = new Map()
1080
981
  const detachedBatchLeases = new Set()
1081
982
  const wakeups = new Map()
983
+ const pendingEdits = new Set()
984
+ const settlingChildren = new Set()
1082
985
  // Keep recent shared/readonly delegates resumable in memory as well as in persistent hosts.
1083
986
  const keepWorktreeWrite = (record) => {
1084
987
  const worktree = record.worktree && worktrees.get(record.worktree.id)
@@ -1119,25 +1022,23 @@ export function apply(ctx, config) {
1119
1022
  const row = !disposing && id && exportTree(id)
1120
1023
  return row ? persist(stateStore.putWorktree(row)) : Promise.resolve()
1121
1024
  }
1122
- const putLease = (lease, baselineId) => {
1025
+ const putLease = (lease) => {
1123
1026
  const row = !disposing && lease && writeLeases.exportLeases().find((entry) => entry.leaseId === lease.leaseId)
1124
- return row ? persist(stateStore.putLease({ ...row, baselineId: baselineId ?? row.baselineId })) : Promise.resolve()
1027
+ return row ? persist(stateStore.putLease(row)) : Promise.resolve()
1125
1028
  }
1126
1029
  const deleteLease = (lease) => lease && !disposing
1127
1030
  ? persist(stateStore.deleteLease(lease.leaseId).then(() => true)) : Promise.resolve()
1128
- const persistDelegate = (childId, record, patch = {}) => {
1129
- if (disposing || startupError) return Promise.resolve()
1130
- const entry = timeline.get(record.parentId, childId)
1031
+ const persistDelegate = (childId, record, patch = {}, entry = timeline.get(record.parentId, childId)) => {
1032
+ if (disposing) return Promise.resolve()
1131
1033
  if (!entry) return Promise.resolve()
1132
- const baseline = record.attempt?.baseline
1133
1034
  return persist(stateStore.putDelegate({
1134
- ...stateStore.getDelegate(childId), ...entry, ...patch,
1035
+ ...stateStore.getDelegate(childId), ...entry,
1135
1036
  childId, parentId: record.parentId, rootSessionId: record.rootSessionId ?? record.parentId,
1136
- expectedTargets: record.expectedTargets, worktreeId: record.worktree?.id ?? entry.worktree?.id ?? null,
1037
+ worktreeId: record.worktree?.id ?? entry.worktree?.id ?? null,
1038
+ pendingNextTurn: record.pendingNextTurn ?? null, ...patch,
1137
1039
  wakeActionKey: record.wakeActionKey ?? null,
1138
1040
  retry: retry.exportChildRecord(childId),
1139
1041
  watchCursor: supervision.supervisor.exportCursor(childId),
1140
- gitBaseline: smallGitBaseline(baseline) ?? null,
1141
1042
  }))
1142
1043
  }
1143
1044
  const queueLifecycle = (handler) => (payload) => {
@@ -1148,18 +1049,29 @@ export function apply(ctx, config) {
1148
1049
  }
1149
1050
  return handler(payload)
1150
1051
  }
1151
- const defineReadyTool = (definition) => defineTool({
1152
- ...definition,
1153
- async execute(args, exec) {
1154
- if (restoring) await readyPromise
1155
- if (disposing || definition.name === 'delegate' || definition.name === ORCHESTRATE_TOOL) assertActive()
1156
- return definition.execute(args, exec)
1157
- },
1158
- })
1052
+ const defineReadyTool = (definition) => {
1053
+ const tool = defineTool(definition)
1054
+ const isLauncher = definition.name === DELEGATE_TOOL || definition.name === ORCHESTRATE_TOOL
1055
+ return {
1056
+ ...tool,
1057
+ async execute(args, exec) {
1058
+ if (restoring) await readyPromise
1059
+ if (isDispatchTool(definition.name)) {
1060
+ const effective = sessionTools.resolveSessionConfig(exec?.agent)
1061
+ if (!effective.enabled) throw new Error(disabledToolMessage(definition.name))
1062
+ // Check the disabled key before the host validates against the shared schema.
1063
+ if (isLauncher) assertReadOnlyArgumentEnabled(args, effective.readOnlyEnabled)
1064
+ }
1065
+ if (disposing || isLauncher) assertActive()
1066
+ return tool.execute(args, exec)
1067
+ },
1068
+ }
1069
+ }
1159
1070
  const worktreeResumeRefusal = (childId) => {
1160
1071
  const worktree = worktreeOf(childId)
1161
1072
  const lock = worktrees.isChildLocked(childId)
1162
- const missing = worktree && (!existsSync(worktree.worktreePath) || !existsSync(worktree.execCwd))
1073
+ const missing = worktree && (!worktree.worktreePath || !worktree.execCwd ||
1074
+ !existsSync(worktree.worktreePath) || !existsSync(worktree.execCwd))
1163
1075
  if (!lock.locked && !missing) return undefined
1164
1076
  const detail = missing && !['merged', 'discarded'].includes(worktree.state)
1165
1077
  ? '工作树或执行目录已缺失,已拒绝投递以防写入主工作区。'
@@ -1167,56 +1079,22 @@ export function apply(ctx, config) {
1167
1079
  return `[worktree-child-locked] ${formatWorktreeError('worktree-child-locked', detail)}`
1168
1080
  }
1169
1081
 
1170
- const observeAudit = ({ childId, parentId, audit, itemIndex, worktree }) => {
1171
- try {
1172
- ctx.emit?.('orchestrator/write-audit', { childId, parentId, audit, ...(worktree && { itemIndex, worktreeId: worktree.id }) })
1173
- } catch (error) {
1174
- warn(`无法发布子代理 ${childId} 的审计证据:${messageOf(error)}`)
1175
- }
1176
- // Failed evidence is attached to native settlement or queried, never a new wake-up turn.
1177
- if (!audit.passed) warn(`【${childId}】不得验收为通过。\n${auditNotice(audit)}`)
1178
- }
1179
-
1180
1082
  const closeWrite = (childId, record) => {
1181
- const parentId = record.parentId
1182
- const attempt = record.attempt
1183
- if (attempt === undefined) {
1184
- if (record.ended && record.disposalAudit !== undefined) {
1185
- timeline.recordAudit(record.disposalAudit)
1186
- record.disposalAudit = undefined
1187
- }
1188
- return
1189
- }
1083
+ const { attempt, parentId } = record
1084
+ if (!attempt) return
1085
+ attempt.replacement?.commit?.()
1190
1086
  record.attempt = undefined
1191
1087
  record.releasedLease = attempt.lease
1192
1088
  try {
1193
- const audit = settleDispatchWrite(attempt.baseline, auditGitBaseline) ??
1194
- (record.baselineId ? missingBaselineAudit(record) : undefined)
1195
- if (audit !== undefined) {
1196
- const { summary, violations } = audit
1197
- const evidence = {
1198
- childId, parentId, runId: record.runId, baselineId: audit.baselineId,
1199
- passed: audit.passed, incomplete: summary.truncated || violations.some(({ code }) => code === 'audit-incomplete'),
1200
- violations, summary: `新增 ${summary.added};修改 ${summary.modified};删除 ${summary.deleted};违规 ${summary.violations}`,
1201
- isolation: audit.isolationLevel, at: Date.now(),
1202
- }
1203
- if (record.worktree && audit.isolationLevel === 'git-worktree') {
1204
- const stats = worktreeAuditSummary(audit)
1205
- const review = worktrees.markReadyForReview(record.worktree.id, stats)
1206
- background(putTree(record.worktree.id))
1207
- timeline.recordWorktreeState(childId, { parentId, id: record.worktree.id, state: review?.state, ...stats })
1208
- // Keep the full Git audit for the same-frame notice, including when disposal precedes end.
1209
- evidence.audit = audit
1210
- }
1211
- // A disposal can provide negative evidence and release the lease, but only end certifies a pass.
1212
- if (!record.ended && evidence.passed && !evidence.incomplete) record.disposalAudit = evidence
1213
- else timeline.recordAudit(evidence)
1214
- observeAudit({ childId, parentId, audit })
1089
+ if (!record.batchId && record.worktree) {
1090
+ const review = worktrees.markReadyForReview(record.worktree.id)
1091
+ timeline.recordWorktreeState(childId, { parentId, id: record.worktree.id, state: review?.state })
1092
+ background(putTree(record.worktree.id))
1215
1093
  }
1216
1094
  } finally {
1217
1095
  if (!record.batchId) {
1218
1096
  releaseWriteScope(writeLeases, attempt.lease)
1219
- if (attempt.lease) timeline.recordLeaseReleased({ childId, parentId, leaseId: attempt.lease.leaseId, at: Date.now() })
1097
+ if (attempt.lease) timeline.recordLeaseReleased({ childId, parentId, leaseId: attempt.lease.leaseId })
1220
1098
  }
1221
1099
  supervision.scheduleReconcileInbox(parentId)
1222
1100
  }
@@ -1228,130 +1106,209 @@ export function apply(ctx, config) {
1228
1106
  if (!record.batchId) background(persistDelegate(childId, record).then(() => deleteLease(record.releasedLease)))
1229
1107
  }
1230
1108
 
1231
- const prepareWriteRetry = (childId, record, operation = '自动续跑') => {
1109
+ const nextTurnSettings = (record, { writeScope, readOnly } = {}) => {
1110
+ const previous = record.pendingNextTurn ?? record
1111
+ const mode = readOnly ?? previous.readOnly === true
1112
+ const scope = writeScope ?? (mode ? [] : previous.writeScope)
1113
+ const checked = validateDispatchWrite({ readOnly: mode, writeScope: scope }, DELEGATE_STATUS_TOOL_NAME)
1114
+ if (mode) return { readOnly: true, writeScope: [], entries: [] }
1115
+ const normalized = normalizeScope(checked.entries, record.cwd)
1116
+ if (!normalized.ok) throw writeScopeFailure(normalized)
1117
+ if (record.worktree && normalized.outsideWorkspace.length > 0) {
1118
+ throw new Error(`独立工作树的写作用域须位于子代理执行目录内:${normalized.outsideWorkspace.join('、')}。`)
1119
+ }
1120
+ return { readOnly: false, writeScope: [...checked.entries], entries: normalized.entries }
1121
+ }
1122
+
1123
+ const prepareWriteRetry = (childId, record, { reversible = false } = {}) => {
1232
1124
  const refusal = worktreeResumeRefusal(childId)
1233
1125
  if (refusal) throw new Error(refusal)
1234
1126
  const { parentId } = record
1235
- let lease = null
1236
- if (!record.readOnly) {
1237
- const acquired = writeLeases.acquire({ childId, parentId, entries: record.entries })
1238
- if (!acquired.ok) throw new Error(`已拒绝${operation}(${acquired.code}):${acquired.message}`)
1239
- lease = acquired.lease
1240
- }
1241
- let baseline
1242
- try {
1243
- // Old fingerprints described the original dispatch, not the bytes already written by it.
1244
- const baselineOptions = {
1245
- cwd: record.cwd, writeScope: record.writeScope, readOnly: record.readOnly, expectedTargets: record.expectedTargets,
1246
- }
1247
- baseline = record.worktree
1248
- ? captureGitBaseline({ ...baselineOptions, worktree: record.worktree, repoRoot: record.worktree.repoRoot })
1249
- : captureDispatchBaseline(baselineOptions)
1250
- } catch (error) {
1251
- releaseWriteScope(writeLeases, lease)
1252
- throw error
1253
- }
1254
- record.attempt = { lease, baseline }
1255
- record.baselineId = baseline?.baselineId
1256
- record.ended = false
1257
- record.runId = undefined
1258
- record.agent = null // Await the new residency; an old disposal cannot close this lease.
1259
- timeline.recordRetry({
1260
- parentId, childId, baselineId: baseline?.baselineId, leaseId: lease?.leaseId,
1261
- readOnly: record.readOnly, startedAt: Date.now(),
1262
- })
1127
+ const nextTurn = nextTurnSettings(record)
1128
+ if (record.pendingNextTurn?.readOnly && !sessionTools.resolveSessionConfig(parentId).readOnlyEnabled) {
1129
+ throw new Error('当前会话未启用 readOnly,请重新编辑下一轮配置。')
1130
+ }
1131
+ const replacement = writeLeases.replaceOwnerLease({
1132
+ childId, parentId, readOnly: nextTurn.readOnly, entries: nextTurn.entries,
1133
+ }, { reversible })
1134
+ if (!replacement.ok) throw leaseFailure(replacement)
1135
+ const { lease } = replacement
1136
+ const priorEntry = timeline.get(parentId, childId)
1137
+ const previous = { ...record }
1138
+ const attempt = { lease, replacement, previous, priorEntry: priorEntry ?? previous }
1139
+ record.attempt = attempt
1140
+ Object.assign(record, nextTurn, { pendingNextTurn: null, ended: false, runId: null, agent: null })
1141
+ if (!priorEntry) timeline.hydrateEntries([previous])
1142
+ timeline.recordRetry({ childId, parentId, leaseId: lease?.leaseId, ...nextTurn, pendingNextTurn: null })
1263
1143
  return record.attempt
1264
1144
  }
1265
1145
 
1146
+ const rollbackWake = async (childId, record, attempt) => {
1147
+ attempt.replacement.rollback()
1148
+ Object.assign(record, attempt.previous, { wakeActionKey: attempt.previous.wakeActionKey })
1149
+ timeline.hydrateEntries([{ ...attempt.priorEntry, updatedAt: Date.now() }])
1150
+ const oldLease = attempt.replacement.previousLease
1151
+ if (oldLease && writeLeases.has(oldLease.leaseId)) await putLease(oldLease)
1152
+ else await deleteLease(oldLease)
1153
+ if (attempt.lease?.leaseId !== oldLease?.leaseId) await deleteLease(attempt.lease)
1154
+ await persistDelegate(childId, record)
1155
+ }
1156
+
1266
1157
  const wakeIdentity = (childId, record) => ({
1267
1158
  childId, parentId: record.parentId, rootSessionId: record.rootSessionId ?? record.parentId,
1268
- runId: record.runId, attemptSeq: timeline.get(record.parentId, childId)?.attemptSeq ?? 1,
1159
+ runId: record.runId, attemptSeq: timeline.get(record.parentId, childId)?.attemptSeq ?? record.attemptSeq ?? 1,
1269
1160
  })
1270
1161
  const inspectChild = (identity) => inspectHostChildState({
1271
1162
  childId: identity.childId, expectedParentId: identity.parentId, expectedRootSessionId: identity.rootSessionId,
1272
1163
  agents: ctx.agents, sessions: ctx.sessions, sessionQuery: optionalSessionQuery(), signal: startupAbort.signal,
1273
1164
  })
1274
- const saveAttempt = (childId, record) => Promise.all([
1275
- putLease(record.attempt?.lease, record.baselineId), persistDelegate(childId, record),
1276
- ])
1165
+ const wakeupRefusal = (childId, record) => {
1166
+ if (wakeups.has(childId) || pendingEdits.has(childId)) return 'in-flight'
1167
+ if (record.wakeActionKey) {
1168
+ const status = actionLedger.canInitiate(record.wakeActionKey)
1169
+ if (status.record?.phase !== 'done') return status.allowed ? 'delivery-unknown' : status.reason
1170
+ }
1171
+ }
1172
+ const inactiveEnough = (host, record) => !host.ownershipMismatch && (
1173
+ (host.running === false && ['live-idle', 'persisted-inactive'].includes(host.presence)) ||
1174
+ (!hasStorage && host.presence === 'unknown' && record.ended === true)
1175
+ )
1176
+ const settled = (childId, record) => !record.attempt && !record.batchId && !settlingChildren.has(childId) &&
1177
+ (record.ended === true || ['ended', 'completed', 'failed', 'aborted', 'interrupted'].includes(record.dispatchState)) &&
1178
+ !wakeupRefusal(childId, record) && !worktreeResumeRefusal(childId)
1179
+
1180
+ const listReusableChildren = async (parent, signal) => {
1181
+ const candidates = new Map(stateStore.listDelegates().map((row) => [row.childId, row]))
1182
+ for (const [id, record] of writes) candidates.set(id, record)
1183
+ const rows = await Promise.all([...candidates].filter(([id, record]) =>
1184
+ record.parentId === parent.id && settled(id, record)).map(async ([childId, record]) => {
1185
+ const identity = wakeIdentity(childId, record)
1186
+ const host = await inspectChild(identity)
1187
+ if (!inactiveEnough(host, record) || !settled(childId, record) || identity.runId !== record.runId) return null
1188
+ const tree = worktreeOf(childId)
1189
+ return { childId, agentName: record.agentName ?? childId, readOnly: record.readOnly === true,
1190
+ writeScope: record.writeScope ?? [], worktree: tree ? { ...worktreeDetails(tree), state: tree.state, locked: tree.locked } : null }
1191
+ }))
1192
+ signal?.throwIfAborted?.()
1193
+ return rows.filter(Boolean)
1194
+ }
1195
+
1196
+ const editNextTurn = async (parent, childId, changes, signal) => {
1197
+ assertActive()
1198
+ const row = stateStore.getDelegate(childId)
1199
+ const record = writes.get(childId) ?? row
1200
+ if (!record || record.parentId !== parent.id || record.batchId) throw new Error('只能编辑当前根会话直接委派的子代理。')
1201
+ const refusal = worktreeResumeRefusal(childId)
1202
+ if (refusal) throw new Error(refusal)
1203
+ if (!settled(childId, record)) throw new Error('子代理尚未结算或正在唤醒,请稍后重试。')
1204
+ const identity = wakeIdentity(childId, record)
1205
+ const host = await inspectChild(identity)
1206
+ signal?.throwIfAborted?.()
1207
+ assertActive()
1208
+ const current = writes.get(childId) ?? (row && hydrateWrite(stateStore.getDelegate(childId) ?? row))
1209
+ if (!current || !inactiveEnough(host, current) || !settled(childId, current) || current.runId !== identity.runId) {
1210
+ throw new Error('子代理已不处于可编辑的闲置状态。')
1211
+ }
1212
+ const { entries, ...pendingNextTurn } = nextTurnSettings(current, changes)
1213
+ if (pendingNextTurn.readOnly && !sessionTools.resolveSessionConfig(parent).readOnlyEnabled) {
1214
+ throw new Error('当前会话未启用 readOnly。')
1215
+ }
1216
+ const checked = writeLeases.check({ entries, readOnly: pendingNextTurn.readOnly, ignoreChildId: childId })
1217
+ if (!checked.ok) throw leaseFailure(checked)
1218
+ const entry = timeline.get(parent.id, childId) ?? row
1219
+ if (!entry) throw new Error('无法确认原委派记录。')
1220
+ pendingEdits.add(childId)
1221
+ try {
1222
+ const updatedAt = Date.now()
1223
+ await persistDelegate(childId, current, { pendingNextTurn, updatedAt }, entry)
1224
+ current.pendingNextTurn = pendingNextTurn
1225
+ timeline.hydrateEntries([{ ...entry, pendingNextTurn, updatedAt }])
1226
+ return { childId, parentId: parent.id, pendingNextTurn }
1227
+ } finally {
1228
+ pendingEdits.delete(childId)
1229
+ }
1230
+ }
1231
+
1232
+ const saveAttempt = async (childId, record) => {
1233
+ const { lease, replacement } = record.attempt ?? {}
1234
+ await putLease(lease)
1235
+ if (replacement?.previousLease && !lease) await deleteLease(replacement.previousLease)
1236
+ await persistDelegate(childId, record)
1237
+ }
1238
+
1239
+ const performWake = async ({ childId, record, kind, identity, actionKey, submit }) => {
1240
+ const blocked = wakeupRefusal(childId, record)
1241
+ if (blocked) throw new Error(`唤醒门禁拒绝 ${kind}:${blocked}`)
1242
+ const reservation = { key: actionKey, kind, identity }
1243
+ wakeups.set(childId, reservation)
1244
+ let attempt
1245
+ let prepared = false
1246
+ let rejected = false
1247
+ try {
1248
+ attempt = prepareWriteRetry(childId, record, { reversible: true })
1249
+ const claim = await actionLedger.prepare(actionKey, { ...identity, kind })
1250
+ if (!claim.ok) throw new Error(`唤醒预留失败:${claim.reason}`)
1251
+ prepared = true
1252
+ record.wakeActionKey = actionKey
1253
+ await saveAttempt(childId, record)
1254
+ assertActive()
1255
+ const refusal = worktreeResumeRefusal(childId)
1256
+ if (refusal) throw new Error(refusal)
1257
+ const { result, accepted, messageId } = await submit(reservation, claim.record.requestId)
1258
+ rejected = accepted === false
1259
+ if (accepted || reservation.observed) {
1260
+ attempt.replacement.commit()
1261
+ if (!disposing) await actionLedger.markAccepted(actionKey, { messageId })
1262
+ } else if (!rejected) {
1263
+ // An absent or ambiguous receipt still owns the new scope and the deduplication entry.
1264
+ attempt.replacement.commit()
1265
+ if (!disposing) await actionLedger.markUnknown(actionKey)
1266
+ }
1267
+ return result
1268
+ } catch (error) {
1269
+ if (reservation.submitted && !reservation.observed) {
1270
+ attempt?.replacement.commit()
1271
+ if (!disposing) await actionLedger.markUnknown(actionKey, { detail: messageOf(error) })
1272
+ }
1273
+ throw error
1274
+ } finally {
1275
+ if (!reservation.observed && (!reservation.submitted || rejected)) {
1276
+ // Restore the delegate and lease before cancelling the durable deduplication entry.
1277
+ if (attempt && record.attempt === attempt) await rollbackWake(childId, record, attempt)
1278
+ if (prepared) await actionLedger.cancelPrepared(actionKey)
1279
+ if (wakeups.get(childId) === reservation) wakeups.delete(childId)
1280
+ }
1281
+ }
1282
+ }
1277
1283
 
1278
1284
  // The policy still owns classification and budget; the adapter owns the durable wakeup and lease.
1279
1285
  const retry = createRetry({
1280
1286
  async deliverPrompt(parentId, childId, text) {
1281
1287
  assertActive()
1282
1288
  const record = writes.get(childId)
1283
- if (record === undefined || record.parentId !== parentId || record.attempt !== undefined) {
1284
- throw new Error('没有可安全恢复的原写作用域记录;已拒绝自动续跑')
1289
+ if (!record || record.parentId !== parentId || record.attempt || typeof ctx.subagents?.prompt !== 'function') {
1290
+ throw new Error('没有可安全恢复的委派或宿主续跑能力;已拒绝自动续跑。')
1285
1291
  }
1286
- const refusal = worktreeResumeRefusal(childId)
1287
- if (refusal) throw new Error(refusal)
1288
- let reservation
1289
- let sent = false
1290
- if (hasStorage) {
1291
- const identity = wakeIdentity(childId, record)
1292
- const hostState = await inspectChild(identity)
1293
- assertActive()
1294
- const retryOrdinal = retry.exportChildRecord(childId).records[0]?.retries ?? 1
1295
- const gate = evaluateWakeupGate({ ...identity, kind: 'retry', retryOrdinal, worktrees, hostState, actionLedger })
1296
- if (!gate.allowed || wakeups.has(childId) || record.runId !== identity.runId || record.attempt) {
1297
- throw new Error(`唤醒门禁拒绝自动续跑:${gate.allowed ? 'in-flight' : gate.reason}`)
1298
- }
1299
- reservation = { key: gate.actionKey, kind: 'retry', identity }
1300
- wakeups.set(childId, reservation)
1301
- }
1302
- let attempt
1303
- try {
1304
- attempt = prepareWriteRetry(childId, record)
1305
- if (reservation) {
1306
- const prepared = await actionLedger.prepare(reservation.key, { ...reservation.identity, kind: 'retry' })
1307
- if (!prepared.ok) throw new Error(`唤醒预留失败:${prepared.reason}`)
1308
- reservation.requestId = prepared.record.requestId
1309
- record.wakeActionKey = reservation.key
1310
- await saveAttempt(childId, record)
1311
- assertActive()
1312
- }
1313
- } catch (error) {
1314
- if (reservation && wakeups.get(childId) === reservation) wakeups.delete(childId)
1315
- if (attempt && record.attempt === attempt) {
1316
- record.attempt = undefined
1317
- record.ended = true
1318
- releaseWriteScope(writeLeases, attempt.lease)
1319
- await deleteLease(attempt.lease)
1320
- }
1321
- throw error
1322
- }
1323
- const { lease, baseline } = attempt
1324
- try {
1325
- const baselineNote = baseline === undefined ? '' : `\n本轮写后审计基线:${baseline.baselineId}。`
1326
- const modeNote = record.readOnly ? `\n${READ_ONLY_NOTICE}` : ''
1327
- const worktreeNote = record.worktree ? `\n${worktreePromptNote(record.worktree)}` : ''
1328
- if (reservation?.observed) return undefined
1329
- sent = true
1330
- if (reservation) reservation.submitted = true
1331
- const messageId = await deliverRetryPrompt(ctx, parentId, childId,
1332
- text + modeNote + baselineNote + worktreeNote, reservation?.requestId)
1333
- if (reservation && !disposing) {
1334
- if (!messageId && !record.runId) throw new Error('宿主未确认投递')
1335
- await actionLedger.markAccepted(reservation.key, { messageId })
1336
- if (record.runId) await actionLedger.markDone(reservation.key, { messageId })
1337
- }
1338
- return messageId
1339
- } catch (error) {
1340
- if (reservation && sent) {
1341
- // A transport error is not evidence that no activation happened.
1342
- if (!disposing && !record.runId) await actionLedger.markUnknown(reservation.key, { detail: messageOf(error) })
1343
- throw error
1344
- }
1345
- if (record.attempt === attempt) {
1346
- record.attempt = undefined
1347
- record.ended = true
1348
- timeline.recordDisposed({ childId, parentId, at: Date.now() })
1349
- releaseWriteScope(writeLeases, lease)
1350
- if (lease) timeline.recordLeaseReleased({ childId, parentId, leaseId: lease.leaseId, at: Date.now() })
1351
- }
1352
- supervision.scheduleReconcileInbox(parentId)
1353
- throw error
1292
+ const identity = wakeIdentity(childId, record)
1293
+ const hostState = await inspectChild(identity)
1294
+ assertActive()
1295
+ const retryOrdinal = retry.exportChildRecord(childId).records[0]?.retries ?? 1
1296
+ const host = inactiveEnough(hostState, record) && hostState.presence === 'unknown'
1297
+ ? { ...hostState, presence: 'persisted-inactive', running: false } : hostState
1298
+ const gate = evaluateWakeupGate({ ...identity, kind: 'retry', retryOrdinal, worktrees, hostState: host, actionLedger })
1299
+ if (!gate.allowed || record.runId !== identity.runId || record.attempt) {
1300
+ throw new Error(`唤醒门禁拒绝自动续跑:${gate.allowed ? 'in-flight' : gate.reason}`)
1354
1301
  }
1302
+ return performWake({ childId, record, kind: 'retry', identity, actionKey: gate.actionKey,
1303
+ async submit(reservation, requestId) {
1304
+ if (reservation.observed) return { accepted: true }
1305
+ const mode = record.readOnly ? READ_ONLY_NOTICE : writeScopeNotice(record.attempt?.lease?.scope)
1306
+ const checkout = record.worktree ? `\n${worktreePromptNote(record.worktree)}` : ''
1307
+ reservation.submitted = true
1308
+ const messageId = await deliverRetryPrompt(ctx, parentId, childId, `${text}\n${mode}${checkout}`, requestId)
1309
+ if (!messageId && !reservation.observed) throw new Error('宿主未确认投递')
1310
+ return { result: messageId, accepted: true, messageId }
1311
+ } })
1355
1312
  },
1356
1313
  wakeParent: (...args) => disposing ? undefined : supervision.deliverRetry(...args),
1357
1314
  logger: ctx.logger,
@@ -1372,7 +1329,7 @@ export function apply(ctx, config) {
1372
1329
  // change. A notice pushed at that moment would splice into a turn the user is still reading,
1373
1330
  // so the change is only recorded here and delivered when that agent's next turn begins.
1374
1331
  const switchNotices = createSwitchNotices({
1375
- readEnabled: () => isDispatchEnabled(config),
1332
+ readEnabled: (id) => dispatchEnabled(rootAgents.get(id) ?? id),
1376
1333
  logger: ctx.logger,
1377
1334
  })
1378
1335
 
@@ -1388,6 +1345,13 @@ export function apply(ctx, config) {
1388
1345
  if (!lease || !detachedBatchLeases.has(lease.leaseId)) return
1389
1346
  const stageRows = stateStore.listDelegates().filter((row) => row.leaseId === lease.leaseId)
1390
1347
  if (stageRows.some((row) => row.childId !== childId && row.dispatchState === 'running')) return
1348
+ const tree = record.worktree && worktrees.markReadyForReview(record.worktree.id)
1349
+ if (tree) {
1350
+ await putTree(tree.id)
1351
+ for (const id of tree.childIds) {
1352
+ timeline.recordWorktreeState(id, { parentId: tree.parentId, id: tree.id, state: tree.state })
1353
+ }
1354
+ }
1391
1355
  await deleteLease(lease)
1392
1356
  releaseWriteScope(writeLeases, lease)
1393
1357
  detachedBatchLeases.delete(lease.leaseId)
@@ -1406,6 +1370,8 @@ export function apply(ctx, config) {
1406
1370
  if (hostRuns.get(childId)?.runId === runId && runId) rememberRecent(earlyEnds, childId, info)
1407
1371
  return
1408
1372
  }
1373
+ const wakeKey = wakeups.get(childId)?.key ?? record.wakeActionKey
1374
+ if (wakeKey && (!runId || runId === actionLedger.get(wakeKey)?.runId)) return
1409
1375
  if (typeof info.parentSessionId === 'string' && record.parentId !== info.parentSessionId) return
1410
1376
  if (record.runId && runId && record.runId !== runId) return
1411
1377
  if (runId) {
@@ -1435,22 +1401,29 @@ export function apply(ctx, config) {
1435
1401
  hooks.forget(childId)
1436
1402
  supervision.scheduleReconcileInbox(parentId)
1437
1403
  const lease = record.releasedLease
1438
- const durable = persistDelegate(childId, record).then(() =>
1439
- record.batchId ? finishDetachedBatch(childId, record) : deleteLease(lease))
1440
- if (key) {
1441
- await durable
1442
- if (disposing) return
1443
- await actionLedger.markDone(key)
1444
- } else background(durable)
1445
- if (record.batchId || disposing) return
1404
+ await persistDelegate(childId, record)
1405
+ if (record.batchId) await finishDetachedBatch(childId, record)
1406
+ else await deleteLease(lease)
1407
+ if (key && !disposing) await actionLedger.markDone(key)
1408
+ return true
1409
+ }
1410
+ if (settlingChildren.has(childId)) return
1411
+ settlingChildren.add(childId)
1412
+ return (async () => {
1413
+ let completed
1414
+ try {
1415
+ completed = await settle()
1416
+ } finally {
1417
+ settlingChildren.delete(childId)
1418
+ }
1419
+ if (!completed || record.batchId || disposing) return
1420
+ // Retry may start a new run before the host returns its delivery receipt.
1446
1421
  try {
1447
1422
  await retry.settle(childId, info, runId ?? record.runId)
1448
1423
  } finally {
1449
1424
  await persistDelegate(childId, record)
1450
1425
  }
1451
- }
1452
- const pending = settle().catch((error) => warn(`无法结算子代理 ${childId}:${messageOf(error)}`))
1453
- return pending
1426
+ })().catch((error) => warn(`无法结算子代理 ${childId}:${messageOf(error)}`))
1454
1427
  }
1455
1428
 
1456
1429
  const onDelegateStarted = (parent, started, args, write, agentName) => {
@@ -1458,12 +1431,12 @@ export function apply(ctx, config) {
1458
1431
  const parentId = parent.id
1459
1432
  const cachedRun = hostRuns.get(childId)
1460
1433
  const hostRun = cachedRun?.parentId === undefined || cachedRun.parentId === parentId ? cachedRun : undefined
1461
- const { baseline, lease, ...metadata } = write
1434
+ const { lease, ...metadata } = write
1462
1435
  const runId = hostRun?.runId ?? started.runId
1463
1436
  if (disposing) return
1464
1437
  timeline.recordDispatched({
1465
1438
  parentId, childId, agentName, label: args.description, readOnly: write.readOnly, writeScope: write.writeScope,
1466
- cwd: write.cwd, baselineId: baseline?.baselineId, leaseId: lease?.leaseId, startedAt: Date.now(), worktree: write.worktree,
1439
+ cwd: write.cwd, allowNewReason: write.allowNewReason, leaseId: lease?.leaseId, startedAt: Date.now(), worktree: write.worktree,
1467
1440
  })
1468
1441
  timeline.recordRunStarted({ childId, parentId, runId })
1469
1442
  const record = {
@@ -1471,17 +1444,18 @@ export function apply(ctx, config) {
1471
1444
  parentId,
1472
1445
  rootSessionId: parent.session?.header?.rootSessionId ?? parentId,
1473
1446
  label: args.description,
1474
- baselineId: baseline?.baselineId,
1475
- expectedTargets: baseline?.expectedTargets ?? args.expectedTargets,
1447
+ agentName,
1476
1448
  runId,
1477
1449
  agent: hostRun?.agent ?? ctx.agents?.get?.(childId),
1478
- attempt: { lease, baseline },
1450
+ attempt: { lease },
1479
1451
  }
1480
1452
  writes.set(childId, record)
1481
1453
  // Keep resumable worktree metadata through review, but bound other detached records.
1482
1454
  for (const [id, record] of writes) {
1483
1455
  if (writes.size <= 256) break
1484
- if (record.attempt === undefined && !retry.has(id) && !wakeups.has(id) && !keepWorktreeWrite(record)) writes.delete(id)
1456
+ if (record.attempt === undefined && !record.pendingNextTurn && !retry.has(id) && !wakeups.has(id) && !keepWorktreeWrite(record)) {
1457
+ writes.delete(id)
1458
+ }
1485
1459
  }
1486
1460
  hooks.onStarted(parent, { ...started, runId }, args, write)
1487
1461
  const durable = Promise.all([putTree(write.worktree?.id), saveAttempt(childId, record)])
@@ -1523,7 +1497,7 @@ export function apply(ctx, config) {
1523
1497
  isDisposing: () => disposing,
1524
1498
  async beforeLaunch(write) {
1525
1499
  assertActive()
1526
- await Promise.all([putTree(write.worktree?.id), putLease(write.lease, write.baseline?.baselineId)])
1500
+ await Promise.all([putTree(write.worktree?.id), putLease(write.lease)])
1527
1501
  },
1528
1502
  async afterFailedLaunch(write) {
1529
1503
  await putTree(write.worktree?.id)
@@ -1545,13 +1519,13 @@ export function apply(ctx, config) {
1545
1519
  }
1546
1520
  const record = {
1547
1521
  ...stage, batchId, childId, parentId: parent.id, rootSessionId: parent.session?.header?.rootSessionId ?? parent.id,
1548
- worktree: write.worktree, expectedTargets: write.baseline?.expectedTargets, runId,
1522
+ worktree: write.worktree, runId,
1549
1523
  }
1550
1524
  batch.children.set(childId, { record, ended: false })
1551
1525
  batchStages.set(childId, batch)
1552
- timeline.recordDispatched({ ...record, ...write, baselineId: write.baseline?.baselineId, leaseId: write.lease?.leaseId })
1526
+ timeline.recordDispatched({ ...record, ...write, leaseId: write.lease?.leaseId })
1553
1527
  timeline.recordRunStarted({ childId, parentId: parent.id, runId })
1554
- await Promise.all([putTree(write.worktree?.id), putLease(write.lease, write.baseline?.baselineId),
1528
+ await Promise.all([putTree(write.worktree?.id), putLease(write.lease),
1555
1529
  persistDelegate(childId, record, { ...stage, batchId })])
1556
1530
  },
1557
1531
  async stageEnded(batch, handle, result) {
@@ -1566,19 +1540,14 @@ export function apply(ctx, config) {
1566
1540
  canFinishBatch(batch) {
1567
1541
  return batch.inFlightStarts === 0 && [...batch.children.values()].every((stage) => stage.ended)
1568
1542
  },
1569
- async finishBatch(batch, audit) {
1543
+ async finishBatch(batch) {
1570
1544
  const { write } = batch
1571
1545
  await putTree(write.worktree?.id)
1572
1546
  for (const [childId, { record }] of batch.children) {
1573
1547
  if (disposing) return
1574
1548
  const { parentId } = record
1575
- if (audit) {
1576
- const incomplete = audit.summary.truncated || audit.violations.some(({ code }) => code === 'audit-incomplete')
1577
- timeline.recordAudit({ childId, parentId, baselineId: audit.baselineId, passed: audit.passed,
1578
- incomplete, violations: audit.violations, isolation: audit.isolationLevel, audit })
1579
- }
1580
1549
  const tree = write.worktree && worktrees.get(write.worktree.id)
1581
- if (tree) timeline.recordWorktreeState(childId, { parentId, id: tree.id, state: tree.state, ...tree.auditSummary })
1550
+ if (tree) timeline.recordWorktreeState(childId, { parentId, id: tree.id, state: tree.state })
1582
1551
  if (write.lease) timeline.recordLeaseReleased({ childId, parentId, leaseId: write.lease.leaseId })
1583
1552
  await persistDelegate(childId, record, { batchId: record.batchId, itemIndex: record.itemIndex, stageIndex: record.stageIndex })
1584
1553
  batchStages.delete(childId)
@@ -1601,13 +1570,59 @@ export function apply(ctx, config) {
1601
1570
  return false
1602
1571
  }
1603
1572
  }
1604
- const sessionTools = createSessionTools({ facility, ctx, logger: ctx.logger, globalAllowedFor: () => allowedToolsFor() })
1573
+ const refreshSupervision = (sessionId) => {
1574
+ const changed = supervision.supervisor.refreshConfig((parentId) => {
1575
+ return sessionId === undefined || sessionTools.resolveRootId(parentId) === sessionId
1576
+ })
1577
+ if (!hasStorage || restoring) return
1578
+ for (const childId of changed) {
1579
+ const record = writes.get(childId)
1580
+ if (record?.attempt) background(persistDelegate(childId, record))
1581
+ }
1582
+ }
1583
+ const sessionTools = createSessionTools({
1584
+ facility, ctx, logger: ctx.logger, globalAllowedFor: () => allowedToolsFor(),
1585
+ globalConfigFor: () => ({
1586
+ enabled: isDispatchEnabled(config),
1587
+ worktreeIsolationEnabled: configValue(config, 'worktreeIsolationEnabled', true) !== false,
1588
+ readOnlyEnabled: configValue(config, 'readOnlyEnabled', false) === true,
1589
+ peerReadOnlyConsultEnabled: configValue(config, 'peerReadOnlyConsultEnabled', false) === true,
1590
+ workerRoute: workerRouteFromConfig(config) ?? null,
1591
+ superviseIntervalSeconds: configValue(config, 'superviseIntervalSeconds', 600),
1592
+ superviseMaxNoticesPerChild: configValue(config, 'superviseMaxNoticesPerChild', 3),
1593
+ superviseUnlimited: configValue(config, 'superviseUnlimited', false) === true,
1594
+ }),
1595
+ onConfigChanged(sessionId) {
1596
+ for (const agent of rootAgents.values()) {
1597
+ if (rootSessionIdOf(agent) === sessionId) switchNotices.observe(agent.id)
1598
+ }
1599
+ refreshSupervision(sessionId)
1600
+ },
1601
+ })
1605
1602
  const allowedToolsFor = (subject) => sessionTools.resolveAllowedTools(subject, {
1606
1603
  globalAllowed: configValue(config, 'allowedTools', undefined),
1607
1604
  defaultAllowed: DEFAULT_ALLOWED_TOOLS,
1608
1605
  allowAgentTeam: allowAgentTeam(),
1609
1606
  catalog: catalog.published(),
1610
1607
  })
1608
+ const readIndex = createReadIndex({
1609
+ enabledFor: (id) => sessionTools.resolveSessionConfig(id).peerReadOnlyConsultEnabled,
1610
+ getAgent: (id) => ctx.agents?.get?.(id),
1611
+ listAgents: () => ctx.agents?.list?.(),
1612
+ rootIdOf: sessionTools.resolveRootId,
1613
+ readOnlyOf: (agent) => (writes.get(agent.id) ?? stateStore.getDelegate(agent.id))?.readOnly,
1614
+ nameOf(agent) {
1615
+ try { return ctx.subagents.namesOf?.(agent)?.self } catch { return undefined }
1616
+ },
1617
+ resolvePeerTarget(exec) {
1618
+ const target = exec.arguments?.agent
1619
+ return target && (ctx.subagents.resolveName?.(exec.agent, target, exec.signal) ?? target)
1620
+ },
1621
+ })
1622
+ listen('tools/result', (exec, result) => {
1623
+ if (disposing) return
1624
+ background(readIndex.observe(exec, result).catch((error) => warn(`只读索引采集失败:${messageOf(error)}`)))
1625
+ }, { global: true })
1611
1626
  const sessionToolsRemote = mountSessionToolsRemote(ctx, sessionTools)
1612
1627
  if (!sessionToolsRemote.available && typeof ctx.provide === 'function') warn(sessionToolsRemote.error)
1613
1628
  const nativeToolNote = (allowed) => {
@@ -1619,9 +1634,7 @@ export function apply(ctx, config) {
1619
1634
 
1620
1635
  const worktreeDispatch = {
1621
1636
  worktrees,
1622
- isWorktreeEnabled: () => configValue(config, 'worktreeIsolationEnabled', true) !== false,
1623
- captureGitBaseline,
1624
- auditGitBaseline,
1637
+ resolveSessionConfig: sessionTools.resolveSessionConfig,
1625
1638
  probeGitRepo,
1626
1639
  onCleanupFailed: (error) => warn(`无法清理未启动的工作树:${messageOf(error)}`),
1627
1640
  }
@@ -1634,6 +1647,7 @@ export function apply(ctx, config) {
1634
1647
  subagents: ctx.subagents,
1635
1648
  config,
1636
1649
  onStarted: onDelegateStarted,
1650
+ listReusableChildren,
1637
1651
  nativeToolNote,
1638
1652
  // Direct, unscoped consumers retain the global description. Scoped declarations
1639
1653
  // replace it with describeFor(allowedToolsFor(scope)) without touching the registry.
@@ -1646,11 +1660,10 @@ export function apply(ctx, config) {
1646
1660
  const orchestrateTool = createOrchestrateTool({
1647
1661
  ...worktreeDispatch,
1648
1662
  defineTool: defineReadyTool,
1649
- stageTracking: hasStorage ? stageTracking : undefined,
1663
+ stageTracking,
1650
1664
  subagents: ctx.subagents,
1651
1665
  config,
1652
1666
  leases: writeLeases,
1653
- onAudited: observeAudit,
1654
1667
  })
1655
1668
  own(() => ctx.tools.register(delegateTool), 'orchestrator: delegate tool')
1656
1669
  own(() => ctx.tools.register(orchestrateTool), `orchestrator: ${ORCHESTRATE_TOOL} tool`)
@@ -1658,11 +1671,16 @@ export function apply(ctx, config) {
1658
1671
  defineTool: defineReadyTool,
1659
1672
  timeline,
1660
1673
  toolName: DELEGATE_STATUS_TOOL_NAME,
1674
+ editNextTurn,
1661
1675
  isRootAgent: (agent) => !isDelegatedChild(agent),
1662
1676
  })
1663
1677
  own(() => ctx.tools.register(delegateStatusTool), `orchestrator: ${DELEGATE_STATUS_TOOL_NAME} tool`)
1664
1678
  const worktreeManageTool = createPersistentWorktreeTool({
1665
- worktrees, stateStore, timeline, assertActive, persist, isWakePending: (id) => wakeups.has(id),
1679
+ isWakePending(id) {
1680
+ const record = writes.get(id) ?? stateStore.getDelegate(id)
1681
+ return Boolean(record && wakeupRefusal(id, record))
1682
+ },
1683
+ worktrees, stateStore, timeline, assertActive, persist,
1666
1684
  onClosed(record) {
1667
1685
  const write = writes.get(record.childId)
1668
1686
  if (write?.worktree?.id === record.id && write.attempt === undefined) writes.delete(record.childId)
@@ -1686,27 +1704,26 @@ export function apply(ctx, config) {
1686
1704
  refusal = worktreeResumeRefusal(childId)
1687
1705
  }
1688
1706
  if (refusal) throw new Error(refusal)
1689
- const row = hasStorage ? stateStore.getDelegate(childId) : undefined
1707
+ const row = stateStore.getDelegate(childId)
1690
1708
  const record = writes.get(childId) ?? row
1691
1709
  if (!record) return { childId }
1710
+ const blocked = wakeupRefusal(childId, record)
1711
+ if (blocked) throw new Error(`唤醒门禁拒绝 send_message:${blocked}`)
1692
1712
  const identity = wakeIdentity(childId, record)
1693
- if (wakeups.has(childId)) throw new Error('唤醒门禁拒绝 send_message:in-flight')
1694
- if (hasStorage) {
1695
- const hostState = await inspectChild(identity)
1696
- assertActive()
1697
- if (hostState.running && !hostState.ownershipMismatch) return { childId }
1698
- if (row?.wakeActionKey) {
1699
- const pending = actionLedger.canInitiate(row.wakeActionKey)
1700
- if (!pending.allowed && pending.record?.phase !== 'done') throw new Error(`唤醒门禁拒绝 send_message:${pending.reason}`)
1701
- }
1702
- if (record.batchId) throw new Error('编排阶段不能单独恢复;请新建任务。')
1703
- const gate = evaluateWakeupGate({ ...identity, kind: 'resume', worktrees, hostState, actionLedger })
1704
- if (!gate.allowed) throw new Error(`唤醒门禁拒绝 send_message:${gate.reason}`)
1705
- if (wakeups.has(childId) || identity.runId !== record.runId) throw new Error('唤醒门禁拒绝 send_message:in-flight')
1706
- if (record.attempt) throw new Error('原运行仍在结算,请稍后向同一代理重试。')
1707
- return { childId, row, identity, key: gate.actionKey }
1713
+ const hostState = await inspectChild(identity)
1714
+ assertActive()
1715
+ if (hostState.running && !hostState.ownershipMismatch) return { childId }
1716
+ if (record.batchId) throw new Error('编排阶段不能单独恢复;请新建任务。')
1717
+ const current = writes.get(childId) ?? stateStore.getDelegate(childId)
1718
+ if (current?.parentId !== record.parentId || wakeupRefusal(childId, current) || identity.runId !== current.runId) {
1719
+ throw new Error('唤醒门禁拒绝 send_message:in-flight')
1708
1720
  }
1709
- return { childId, identity }
1721
+ if (current.attempt || !settled(childId, current)) throw new Error('原运行仍在结算,请稍后向同一代理重试。')
1722
+ const host = inactiveEnough(hostState, current) && hostState.presence === 'unknown'
1723
+ ? { ...hostState, presence: 'persisted-inactive', running: false } : hostState
1724
+ const gate = evaluateWakeupGate({ ...identity, kind: 'resume', worktrees, hostState: host, actionLedger })
1725
+ if (!gate.allowed) throw new Error(`唤醒门禁拒绝 send_message:${gate.reason}`)
1726
+ return { childId, row, identity, key: gate.actionKey }
1710
1727
  }
1711
1728
 
1712
1729
  // Early preflight keeps lock refusals visible to direct and Code Mode callers. Reserve
@@ -1726,69 +1743,30 @@ export function apply(ctx, config) {
1726
1743
  listen('tools/execute', async (exec, next) => {
1727
1744
  if (exec.name !== 'send_message') return next()
1728
1745
  if (restoring) await readyPromise
1729
- const { childId, row, identity, key } = await resolveMessageTarget(exec)
1746
+ const { childId, row, identity, key: actionKey } = await resolveMessageTarget(exec)
1730
1747
  if (!identity) return next()
1731
- const refusal = worktreeResumeRefusal(childId)
1732
- if (refusal) throw new Error(refusal)
1733
1748
  const current = writes.get(childId) ?? hydrateWrite(row)
1734
- if (wakeups.has(childId) || identity.runId !== current.runId) throw new Error('唤醒门禁拒绝 send_message:in-flight')
1735
- if (current.attempt) return next() // A live residency still owns its original lease and baseline.
1736
- if (!current.readOnly && !current.entries?.length) throw new Error('无法核验原写作用域')
1737
-
1738
- const previous = { ...current }
1739
- const entry = timeline.get(current.parentId, childId)
1740
- const reservation = { kind: 'resume', key, identity }
1741
- wakeups.set(childId, reservation)
1742
- let attempt
1743
- let prepared = false
1744
- let delivering = false
1745
- let result
1746
- try {
1747
- attempt = prepareWriteRetry(childId, current, 'send_message 续跑')
1748
- if (key) {
1749
- const claim = await actionLedger.prepare(key, { ...identity, kind: 'resume' })
1750
- if (!claim.ok) throw new Error(`唤醒门禁拒绝 send_message:${claim.reason}`)
1751
- prepared = true
1752
- current.wakeActionKey = key
1753
- await saveAttempt(childId, current)
1754
- }
1755
- assertActive()
1756
- const refusal = worktreeResumeRefusal(childId)
1757
- if (refusal) throw new Error(refusal)
1758
- exec.signal?.throwIfAborted?.()
1759
- delivering = true
1760
- result = await next()
1761
- if (key && !result?.isError) await actionLedger.markAccepted(key, { messageId: result?.value?.messageId })
1762
- return result
1763
- } finally {
1764
- // A published start takes ownership, even if a later hook cannot confirm delivery.
1765
- if (!reservation.observed && (!delivering || result?.isError === true)) {
1766
- if (attempt && current.attempt === attempt) {
1767
- Object.assign(current, previous, { wakeActionKey: previous.wakeActionKey })
1768
- releaseWriteScope(writeLeases, attempt.lease)
1769
- if (entry) timeline.hydrateEntries([{ ...entry, updatedAt: Date.now() }])
1770
- }
1771
- try {
1772
- if (prepared) await actionLedger.cancelPrepared(key)
1773
- if (attempt && key) {
1774
- await deleteLease(attempt.lease)
1775
- await persistDelegate(childId, current)
1776
- }
1777
- } finally {
1778
- if (wakeups.get(childId) === reservation) wakeups.delete(childId)
1779
- }
1780
- } else if (key && delivering && !result && !reservation.observed) {
1781
- await actionLedger.markUnknown(key)
1782
- }
1783
- }
1749
+ if (identity.runId !== current.runId || !settled(childId, current)) {
1750
+ throw new Error('唤醒门禁拒绝 send_message:in-flight')
1751
+ }
1752
+ return performWake({ childId, record: current, kind: 'resume', identity, actionKey,
1753
+ async submit(reservation) {
1754
+ exec.signal?.throwIfAborted?.()
1755
+ if (reservation.observed) throw new Error('宿主已启动该子代理,未重复唤醒。')
1756
+ reservation.submitted = true
1757
+ const result = await next()
1758
+ const messageId = result?.value?.messageId
1759
+ const accepted = result?.isError === true ? false : (result?.isError === false || messageId ? true : undefined)
1760
+ return { result, accepted, messageId }
1761
+ },
1762
+ })
1784
1763
  }, { global: true })
1785
-
1786
1764
  /**
1787
1765
  * The live guard of every gated main agent, keyed by agent id. One predicate covers every
1788
1766
  * name — global, scope-local, and calls nested inside `run_code` — so nothing has to be
1789
1767
  * rebuilt when the panel or the registry changes; it is dropped with the agent.
1790
1768
  */
1791
- const dispatchEnabled = () => isDispatchEnabled(config)
1769
+ const dispatchEnabled = (subject) => sessionTools.resolveSessionConfig(subject).enabled
1792
1770
 
1793
1771
  const gates = new Map()
1794
1772
 
@@ -1826,6 +1804,30 @@ export function apply(ctx, config) {
1826
1804
  * (a request built inside that window saw them appear, the next saw them vanish, and the
1827
1805
  * cached prompt prefix was lost each time).
1828
1806
  */
1807
+ const rootRuleContext = ctx.get?.('systemPrompt') ?? ctx.systemPrompt
1808
+ if (typeof rootRuleContext?.context === 'function') {
1809
+ own(() => rootRuleContext.context({
1810
+ name: 'orchestrator:root-dispatch-rule',
1811
+ order: rootRuleContext.getContextOrder?.('SUBAGENT_DELEGATION'),
1812
+ interpolate: false,
1813
+ text: ({ agent, toolSet }) => {
1814
+ if (!agent || !dispatchEnabled(agent)) return ''
1815
+ if (isDelegatedChild(agent)) {
1816
+ const record = writes.get(agent.id)
1817
+ const current = record && timeline.get(record.parentId, agent.id)
1818
+ if (!record?.attempt || !current || current.attemptSeq < 2) return ''
1819
+ const scope = record.attempt.lease?.scope
1820
+ if (record.readOnly) return `本轮委派配置覆盖历史任务中的写入限制。\n${READ_ONLY_NOTICE}`
1821
+ return scope?.length ? `本轮委派配置覆盖历史任务中的写入限制。\n${writeScopeNotice(scope)}` : ''
1822
+ }
1823
+ const allowed = allowedToolsFor(agent)
1824
+ const hasDispatch = ctx.tools.definitions(agent, toolSet).some(({ name }) =>
1825
+ name === 'delegate' || name === ORCHESTRATE_TOOL)
1826
+ if (hasDispatch) return ''
1827
+ return mainAgentRule(allowed, sessionTools.resolveSessionConfig(agent))
1828
+ },
1829
+ }), 'orchestrator: root dispatch rule')
1830
+ }
1829
1831
  own(
1830
1832
  () =>
1831
1833
  installToolSurface({
@@ -1835,6 +1837,8 @@ export function apply(ctx, config) {
1835
1837
  allowAgentTeam,
1836
1838
  isNativeTeamEnabled,
1837
1839
  enabled: dispatchEnabled,
1840
+ readOnlyEnabled: (subject) => sessionTools.resolveSessionConfig(subject).readOnlyEnabled,
1841
+ describeOrchestrate: orchestrateTool.describeFor,
1838
1842
  }),
1839
1843
  'orchestrator: tool surface',
1840
1844
  )
@@ -1845,7 +1849,7 @@ export function apply(ctx, config) {
1845
1849
  const scope = row.readOnly ? null : normalizeScope(row.writeScope ?? [], row.cwd)
1846
1850
  const record = {
1847
1851
  ...row, worktree, agent, ended: !active, entries: lease?.entries ?? scope?.entries,
1848
- attempt: active ? { lease, baseline: restoredGitBaseline(row, worktree) } : undefined,
1852
+ attempt: active ? { lease } : undefined,
1849
1853
  }
1850
1854
  writes.set(row.childId, record)
1851
1855
  if (active && row.batchId && lease) detachedBatchLeases.add(lease.leaseId)
@@ -1860,6 +1864,10 @@ export function apply(ctx, config) {
1860
1864
  })
1861
1865
  }
1862
1866
  const runStarted = (childId, record, agent, runId) => {
1867
+ const reservation = wakeups.get(childId)
1868
+ const actionKey = reservation?.key ?? record.wakeActionKey
1869
+ const previousRun = reservation?.identity.runId ?? actionLedger.get(actionKey)?.runId
1870
+ if (actionKey && (!runId || runId === previousRun)) return
1863
1871
  if (record.worktree) {
1864
1872
  const review = worktrees.reopenForRetry(record.worktree.id)
1865
1873
  timeline.recordWorktreeState(childId, {
@@ -1871,16 +1879,14 @@ export function apply(ctx, config) {
1871
1879
  record.runId = runId ?? record.runId
1872
1880
  record.agent = agent
1873
1881
  timeline.recordRunStarted({ childId, parentId: record.parentId, runId })
1874
- const reservation = wakeups.get(childId)
1875
1882
  if (reservation) {
1876
1883
  reservation.observed = true
1877
- if (!retry.has(childId)) retry.track(childId, { parentId: record.parentId, label: record.label })
1884
+ record.attempt?.replacement?.commit()
1885
+ wakeups.delete(childId)
1878
1886
  }
1887
+ if (actionKey && !retry.has(childId)) retry.track(childId, { parentId: record.parentId, label: record.label })
1879
1888
  if (changedRun && (hasStorage || reservation)) armRun(childId, record, { resumed: true })
1880
- const actionKey = reservation?.key ?? record.wakeActionKey
1881
- const previousRun = reservation?.identity.runId ?? actionLedger.get(actionKey)?.runId
1882
- if (reservation && runId !== previousRun) wakeups.delete(childId)
1883
- if (actionKey && runId && runId !== previousRun) {
1889
+ if (actionKey) {
1884
1890
  record.wakeActionKey = null
1885
1891
  return persistDelegate(childId, record).then(() => actionLedger.markDone(actionKey))
1886
1892
  }
@@ -1894,6 +1900,18 @@ export function apply(ctx, config) {
1894
1900
  const record = writes.get(childId) ?? (row && !row.batchId && hydrateWrite(row))
1895
1901
  if (!record || record.batchId || (parentId && record.parentId !== parentId)) return
1896
1902
  if (record.runId === runId && runId && !record.ended) return
1903
+ const durableWake = record.wakeActionKey && actionLedger.get(record.wakeActionKey)
1904
+ if (durableWake && durableWake.phase !== 'done') {
1905
+ // A new host run can resolve an ambiguous dispatch using the scope already persisted.
1906
+ if (!runId || runId === durableWake.runId) return
1907
+ if (!record.attempt) {
1908
+ const lease = row?.leaseId && writeLeases.get(row.leaseId)
1909
+ if (!record.readOnly && !lease) throw new Error('无法验证宿主已恢复运行的写租约。')
1910
+ record.attempt = { lease }
1911
+ record.ended = false
1912
+ }
1913
+ return runStarted(childId, record, agent, runId)
1914
+ }
1897
1915
  let reservation = wakeups.get(childId)
1898
1916
  if (!reservation) {
1899
1917
  const identity = wakeIdentity(childId, record)
@@ -1914,10 +1932,6 @@ export function apply(ctx, config) {
1914
1932
  await actionLedger.markAccepted(reservation.key)
1915
1933
  }
1916
1934
  if (!record.attempt) {
1917
- if (!record.readOnly && !record.entries?.length) {
1918
- warn(`子代理 ${childId} 缺少可验证的写作用域;未重建活跃追踪`)
1919
- return
1920
- }
1921
1935
  prepareWriteRetry(childId, record)
1922
1936
  record.wakeActionKey = reservation.key
1923
1937
  if (!retry.has(childId)) retry.track(childId, { parentId: record.parentId, label: record.label })
@@ -1999,7 +2013,7 @@ export function apply(ctx, config) {
1999
2013
  prepareWriteRetry(childId, record)
2000
2014
  if (!retry.has(childId)) retry.track(childId, { parentId: record.parentId })
2001
2015
  } catch (error) {
2002
- warn(`无法为子代理 ${childId} 的返工准备审计:${messageOf(error)}`)
2016
+ warn(`无法为子代理 ${childId} 的返工登记租约:${messageOf(error)}`)
2003
2017
  }
2004
2018
  }
2005
2019
  if (record?.attempt !== undefined && (!record.runId || !runId || record.runId === runId)) {
@@ -2025,8 +2039,9 @@ export function apply(ctx, config) {
2025
2039
  rootAgents.set(agent.id, agent)
2026
2040
  sessionToRootAgent.set(agent.session, agent)
2027
2041
  todoTracker.bind(agent)
2042
+ sessionTools.restoreMainRoute(agent)
2028
2043
  switchNotices.observe(agent.id)
2029
- if (!dispatchEnabled()) return
2044
+ if (!dispatchEnabled(agent)) return
2030
2045
  ctx.logger.info(
2031
2046
  `orchestrator: main agent ${agent.id}: armed whitelist gate (${gate.allowed.length} allowed: [${gate.allowed.join(', ')}])`,
2032
2047
  )
@@ -2062,7 +2077,7 @@ export function apply(ctx, config) {
2062
2077
  return resumeFromHost(agent, agent.id, runId, agent.session?.header?.parentSession)
2063
2078
  .catch((error) => warn(`恢复子代理 ${agent.id} 失败:${messageOf(error)}`))
2064
2079
  })
2065
- listen('agent/created', (payload) => {
2080
+ listen('agent/created', async (payload) => {
2066
2081
  if (disposing) return
2067
2082
  const agent = payload?.agent
2068
2083
  // A new root agent is the only place a preset or scope-local tool becomes visible,
@@ -2079,7 +2094,9 @@ export function apply(ctx, config) {
2079
2094
  return
2080
2095
  }
2081
2096
 
2082
- // The same idempotent path handles startup enumeration and later creations.
2097
+ // The persisted model must be installed before the first prepared step.
2098
+ if (hasStorage) await sessionTools.ready
2099
+ if (disposing) return
2083
2100
  registerRootAgent(agent)
2084
2101
  // A resumed agent with a parentSession that still read as a main agent means the
2085
2102
  // depth test degraded: the cold-resume regression looked exactly like this.
@@ -2090,11 +2107,16 @@ export function apply(ctx, config) {
2090
2107
  }
2091
2108
  })
2092
2109
 
2093
- try {
2094
- for (const agent of ctx.agents?.list?.() ?? []) registerRootAgent(agent)
2095
- } catch (error) {
2096
- ctx.logger.warn(`orchestrator: cannot register existing root agents: ${messageOf(error)}`)
2110
+ const registerExistingRoots = () => {
2111
+ if (disposing) return
2112
+ try {
2113
+ for (const agent of ctx.agents?.list?.() ?? []) registerRootAgent(agent)
2114
+ } catch (error) {
2115
+ warn(`cannot register existing root agents: ${messageOf(error)}`)
2116
+ }
2097
2117
  }
2118
+ if (hasStorage) background(sessionTools.ready.then(registerExistingRoots))
2119
+ else registerExistingRoots()
2098
2120
 
2099
2121
  // A gated agent that goes away takes its guard with it: the entry is the only owner of
2100
2122
  // the disposer, so dropping it here must not leave a predicate behind.
@@ -2133,12 +2155,27 @@ export function apply(ctx, config) {
2133
2155
  * the model what changed. Nothing is delivered now: a notice at this moment would splice
2134
2156
  * into a turn the user is still reading.
2135
2157
  */
2158
+ let lastGlobalMainRoute = JSON.stringify(sessionTools.currentMainRoute())
2159
+ const syncInheritedMainRoutes = () => {
2160
+ if (disposing) return
2161
+ const route = sessionTools.currentMainRoute()
2162
+ const fingerprint = JSON.stringify(route)
2163
+ if (fingerprint === lastGlobalMainRoute) return
2164
+ lastGlobalMainRoute = fingerprint
2165
+ for (const agent of rootAgents.values()) {
2166
+ if (!sessionTools.getSessionOverride(rootSessionIdOf(agent)).active) sessionTools.selectMainRoute(agent, route)
2167
+ }
2168
+ }
2169
+
2136
2170
  listen('loader/volatile-update', () => {
2137
2171
  // Restore it before the write's own settings read answers, so the panel never falls
2138
2172
  // back to its built-in copy after a checkbox click.
2139
2173
  catalog.publish()
2140
2174
  for (const id of gates.keys()) switchNotices.observe(id)
2141
- })
2175
+ refreshSupervision()
2176
+ syncInheritedMainRoutes()
2177
+ }, { global: true })
2178
+ listen('settings/document-updated', syncInheritedMainRoutes, { global: true })
2142
2179
 
2143
2180
  /**
2144
2181
  * Deliver a recorded switch change at the start of the agent's next real model step.
@@ -2173,23 +2210,52 @@ export function apply(ctx, config) {
2173
2210
  supervisor: supervision.supervisor,
2174
2211
  rebuildNotice: supervision.rebuildNotice,
2175
2212
  liveNoticeIds: supervision.liveNoticeIds,
2176
- auditTimeline: timeline,
2177
- loadAuditCreator: supervision.loadAuditCreator,
2178
- scheduleReconcileInbox: supervision.scheduleReconcileInbox,
2179
2213
  retainNotices: supervision.retainNotices,
2180
2214
  supervisionTurnState,
2181
2215
  todoTracker,
2182
2216
  nextStep: createSwitchPreStep({ switchNotices, logger: ctx.logger, supervisionTurnState }),
2183
2217
  })
2218
+ const loadPeerMessage = createUserMessageLoader({
2219
+ logger: ctx.logger,
2220
+ scope: 'peer read-only consult',
2221
+ disabledReason: 'peer context injection is disabled',
2222
+ })
2184
2223
  listen('agent/pre-step', async (payload, next) => {
2185
2224
  if (hasStorage) await sessionTools.ready
2186
2225
  if (restoring) await readyPromise
2187
2226
  if (disposing) return next()
2188
- const decision = await preStep(payload, next)
2189
- if (hasStorage && !disposing && Array.isArray(decision?.messages)) {
2190
- for (const { childId, entry } of settledAuditEntries(timeline, payload?.agent?.id, decision.messages)) {
2191
- if (entry.auditDeliveredVia && entry.auditDeliveredVia !== stateStore.getDelegate(childId)?.auditDeliveredVia) {
2192
- await persistDelegate(childId, writes.get(childId) ?? stateStore.getDelegate(childId) ?? entry)
2227
+ const agent = payload?.agent
2228
+ const incoming = payload?.messages
2229
+ const child = isDelegatedChild(agent)
2230
+ const filterRootMessages = (messages) => child || !Array.isArray(messages)
2231
+ ? messages : readIndex.prepare(agent, messages).messages
2232
+ const scoped = filterRootMessages(incoming)
2233
+ // Filter claimed and downstream messages before supervision classifies the batch.
2234
+ const enter = async () => {
2235
+ const result = await next()
2236
+ const messages = filterRootMessages(result?.messages)
2237
+ return messages === result?.messages ? result : { ...result, messages }
2238
+ }
2239
+ let decision = await preStep(scoped === incoming ? payload : { ...payload, messages: scoped }, enter)
2240
+ if (scoped !== incoming && decision?.kind === 'enter' && decision.messages?.every(isRuntimeContext)) {
2241
+ return { kind: 'reject' }
2242
+ }
2243
+ if (child && decision?.kind === 'enter' && !payload?.signal?.aborted && Array.isArray(decision.messages)) {
2244
+ const consultation = readIndex.prepare(agent, decision.messages)
2245
+ if (consultation.text) {
2246
+ const createMessage = await loadPeerMessage()
2247
+ if (createMessage && !disposing && !payload?.signal?.aborted &&
2248
+ sessionTools.resolveSessionConfig(agent).peerReadOnlyConsultEnabled) {
2249
+ try {
2250
+ const note = createMessage({
2251
+ content: [{ type: 'text', text: consultation.text }],
2252
+ source: { kind: PEER_CONSULT_SOURCE_KIND, form: 'notice', summary: '平级只读咨询' },
2253
+ })
2254
+ decision = { ...decision, messages: [...decision.messages, note] }
2255
+ consultation.acknowledge?.()
2256
+ } catch (error) {
2257
+ warn(`无法注入平级只读咨询:${messageOf(error)}`)
2258
+ }
2193
2259
  }
2194
2260
  }
2195
2261
  }
@@ -2202,6 +2268,7 @@ export function apply(ctx, config) {
2202
2268
  await domainReservation.previous
2203
2269
  if (disposing) return
2204
2270
  await stateStore.open()
2271
+ await sessionTools.ready
2205
2272
  if (disposing) return
2206
2273
  if (stateStore.hasUnsafeState()) startupError ??= new Error('存储域无法完整读取;原始数据已保留')
2207
2274
  const snapshot = stateStore.getSnapshot()
@@ -2209,7 +2276,7 @@ export function apply(ctx, config) {
2209
2276
  const tree = row.worktreeId && worktrees.get(row.worktreeId)
2210
2277
  const leaseState = row.leaseState ?? (!row.leaseId ? 'none'
2211
2278
  : writeLeases.get(row.leaseId) ? 'held' : startupError ? 'unknown' : 'released')
2212
- return { ...row, leaseState, ...(tree && { worktree: { ...tree, ...tree.auditSummary, locked: tree.locked } }) }
2279
+ return { ...row, leaseState, ...(tree && { worktree: { ...tree, locked: tree.locked } }) }
2213
2280
  }
2214
2281
  await reconcileOnStartup({
2215
2282
  snapshot, store: stateStore, worktrees, leases: writeLeases, timeline, retry, actionLedger,
@@ -2229,8 +2296,9 @@ export function apply(ctx, config) {
2229
2296
  async onDelegateReconciled(row) {
2230
2297
  const tree = row.worktreeId && worktrees.get(row.worktreeId)
2231
2298
  if (tree?.state !== 'active' || stateStore.listDelegates().some((other) =>
2232
- other.worktreeId === tree.id && other.childId !== row.childId && other.dispatchState === 'running')) return
2233
- const review = worktrees.markReadyForReview(tree.id, { incomplete: row.incomplete === true })
2299
+ other.worktreeId === tree.id && other.childId !== row.childId &&
2300
+ (other.dispatchState === 'running' || (other.wakeActionKey && actionLedger.get(other.wakeActionKey)?.phase !== 'done')))) return
2301
+ const review = worktrees.markReadyForReview(tree.id)
2234
2302
  await putTree(tree.id)
2235
2303
  for (const childId of tree.childIds) timeline.recordWorktreeState(childId, {
2236
2304
  id: tree.id, parentId: tree.parentId, state: review?.state,