@sshirkit/dsh-orchestrator 1.0.1 → 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/README.md +65 -30
- package/README.zh.md +62 -29
- package/lib/client.js +809 -311
- package/lib/delegate-status.js +42 -67
- package/lib/delegate.js +98 -140
- package/lib/gate.js +11 -5
- package/lib/index.js +533 -442
- package/lib/orchestrate.js +143 -129
- package/lib/read-index.js +186 -0
- package/lib/reconcile.js +2 -3
- package/lib/rules.js +22 -10
- package/lib/session-tools.js +516 -0
- package/lib/state-store.js +14 -9
- package/lib/supervise.js +69 -85
- package/lib/switch-notice.js +2 -2
- package/lib/timeline.js +23 -181
- package/lib/tool-surface.js +57 -9
- package/lib/worker.js +18 -7
- package/lib/worktree-manage.js +3 -10
- package/lib/worktree.js +3 -12
- package/lib/write-lease.js +57 -12
- package/package.json +1 -1
- package/lib/git-audit.js +0 -383
- package/lib/write-audit.js +0 -333
package/lib/index.js
CHANGED
|
@@ -2,21 +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,
|
|
10
|
-
|
|
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'
|
|
21
|
+
import { createSessionTools, mountSessionToolsRemote, rootSessionIdOf } from './session-tools.js'
|
|
20
22
|
import { createStateStore } from './state-store.js'
|
|
21
23
|
import { normalizeScope } from './write-scope.js'
|
|
22
24
|
import {
|
|
@@ -30,15 +32,15 @@ import {
|
|
|
30
32
|
summarize,
|
|
31
33
|
} from './supervise.js'
|
|
32
34
|
import { SWITCH_SOURCE_KIND, createSwitchNotices } from './switch-notice.js'
|
|
33
|
-
import {
|
|
34
|
-
import { DEFAULT_ALLOWED_TOOLS, NATIVE_TEAM_TOOLS, installToolSurface
|
|
35
|
-
import { isDispatchEnabled } from './worker.js'
|
|
35
|
+
import { createDispatchTimeline } from './timeline.js'
|
|
36
|
+
import { DEFAULT_ALLOWED_TOOLS, NATIVE_TEAM_TOOLS, installToolSurface } from './tool-surface.js'
|
|
37
|
+
import { configValue, isDispatchEnabled, workerRouteFromConfig } from './worker.js'
|
|
36
38
|
import { createWriteLeases } from './write-lease.js'
|
|
37
|
-
import { formatWorktreeError, releaseWriteScope } from './write-scope-tool.js'
|
|
39
|
+
import { formatWorktreeError, leaseFailure, releaseWriteScope, writeScopeFailure, writeScopeNotice } from './write-scope-tool.js'
|
|
38
40
|
import { createWorktreeManager, probeGitRepo } from './worktree.js'
|
|
39
41
|
import { createPersistentWorktreeTool } from './worktree-tool.js'
|
|
40
42
|
|
|
41
|
-
export { DEFAULT_ALLOWED_TOOLS,
|
|
43
|
+
export { DEFAULT_ALLOWED_TOOLS, SUPERVISE_SOURCE_KIND, SWITCH_SOURCE_KIND }
|
|
42
44
|
|
|
43
45
|
export const name = '@sshirkit/dsh-orchestrator'
|
|
44
46
|
|
|
@@ -55,11 +57,13 @@ export const inject = ['sessionProjections', 'tools', 'subagents', 'agents', 'se
|
|
|
55
57
|
* route is read on every delegation, so it applies from the next `delegate` call.
|
|
56
58
|
*/
|
|
57
59
|
export const Config = z.object({
|
|
58
|
-
/**
|
|
60
|
+
/** Gate dispatch and governance tools by the root session's effective switch. */
|
|
59
61
|
enabled: z.boolean().default(true).volatile(),
|
|
60
62
|
worktreeIsolationEnabled: z.boolean().default(true)
|
|
61
|
-
.description('Git 仓库下对写任务默认启用独立 Worktree
|
|
63
|
+
.description('Git 仓库下对写任务默认启用独立 Worktree 隔离(orchestrate 按 item 隔离),非 Git 目录使用共享工作区')
|
|
62
64
|
.volatile(),
|
|
65
|
+
readOnlyEnabled: z.boolean().default(false).volatile(),
|
|
66
|
+
peerReadOnlyConsultEnabled: z.boolean().default(false).volatile(),
|
|
63
67
|
/**
|
|
64
68
|
* The only tool whitelist there is. Whitelist-driven: only the names listed here stay
|
|
65
69
|
* available to the main agent, and every other host, MCP or plugin tool is automatically
|
|
@@ -107,7 +111,7 @@ export const Config = z.object({
|
|
|
107
111
|
/** How long a child may run before its parent is woken with one summary notice, in seconds. */
|
|
108
112
|
superviseIntervalSeconds: z.number().min(10).max(86400).step(1).default(600).volatile(),
|
|
109
113
|
/** Notices allowed per child; 0 turns supervision off unless superviseUnlimited is on. */
|
|
110
|
-
superviseMaxNoticesPerChild: z.number().min(0).max(20).default(3).volatile(),
|
|
114
|
+
superviseMaxNoticesPerChild: z.number().min(0).max(20).step(1).default(3).volatile(),
|
|
111
115
|
/** Ignore the notice cap and keep supervising until the child stops, delivers, or ends. */
|
|
112
116
|
superviseUnlimited: z.boolean().default(false).volatile(),
|
|
113
117
|
/** Also notify when a child produced no new events; off saves a model turn. */
|
|
@@ -116,17 +120,6 @@ export const Config = z.object({
|
|
|
116
120
|
restoreTodoOnSupervision: z.boolean().default(true).volatile(),
|
|
117
121
|
})
|
|
118
122
|
|
|
119
|
-
/** Read one config field whether it is a schemastery ref or a plain value. */
|
|
120
|
-
function configValue(config, key, fallback) {
|
|
121
|
-
try {
|
|
122
|
-
const field = config?.[key]
|
|
123
|
-
const value = typeof field?.get === 'function' ? field.get() : field
|
|
124
|
-
return value === undefined || value === null ? fallback : value
|
|
125
|
-
} catch {
|
|
126
|
-
return fallback
|
|
127
|
-
}
|
|
128
|
-
}
|
|
129
|
-
|
|
130
123
|
function messageOf(error) {
|
|
131
124
|
return error instanceof Error ? error.message : String(error)
|
|
132
125
|
}
|
|
@@ -377,53 +370,9 @@ function filterSupervisionMessages(messages, { liveNoticeIds, rebuildNotice, age
|
|
|
377
370
|
})
|
|
378
371
|
}
|
|
379
372
|
|
|
380
|
-
function settledAuditEntries(timeline, parentId, messages) {
|
|
381
|
-
const matches = new Map()
|
|
382
|
-
for (const message of messages) {
|
|
383
|
-
const source = message?.source
|
|
384
|
-
if (source?.kind !== 'subagent-settled') continue
|
|
385
|
-
const childId = source.senderSessionId
|
|
386
|
-
if (typeof childId !== 'string' || matches.has(childId)) continue
|
|
387
|
-
const entry = timeline.get(parentId, childId)
|
|
388
|
-
if (entry !== null) matches.set(childId, { childId, entry })
|
|
389
|
-
}
|
|
390
|
-
return [...matches.values()]
|
|
391
|
-
}
|
|
392
|
-
|
|
393
|
-
/** Commit delivery only for the exact messages entering the model step. */
|
|
394
|
-
function attachAuditMessages({ timeline, agent, messages, createMessage, scheduleReconcileInbox, logger }) {
|
|
395
|
-
if (createMessage === undefined) return messages
|
|
396
|
-
const parentId = agent.id
|
|
397
|
-
const attached = settledAuditEntries(timeline, parentId, messages)
|
|
398
|
-
if (attached.length === 0) return messages
|
|
399
|
-
let notice
|
|
400
|
-
try {
|
|
401
|
-
notice = createMessage({
|
|
402
|
-
content: [{ type: 'text', text: formatInlineAuditNotice(attached) }],
|
|
403
|
-
source: { kind: INLINE_AUDIT_SOURCE_KIND, form: 'notice' },
|
|
404
|
-
})
|
|
405
|
-
} catch (error) {
|
|
406
|
-
try {
|
|
407
|
-
logger?.warn?.(`orchestrator: cannot build the inline audit notice: ${messageOf(error)}`)
|
|
408
|
-
} catch {
|
|
409
|
-
// Neither a message constructor nor a logger may break the parent model step.
|
|
410
|
-
}
|
|
411
|
-
return messages
|
|
412
|
-
}
|
|
413
|
-
|
|
414
|
-
let changed = false
|
|
415
|
-
for (const { childId, entry } of attached) {
|
|
416
|
-
if (entry.auditState !== 'passed' && entry.auditState !== 'failed') continue
|
|
417
|
-
changed = timeline.markAuditDelivered({ parentId, childId, via: 'inline-pre-step' }) || changed
|
|
418
|
-
}
|
|
419
|
-
if (changed) scheduleReconcileInbox?.(parentId)
|
|
420
|
-
return [...messages, notice]
|
|
421
|
-
}
|
|
422
|
-
|
|
423
373
|
/** Filter claimed inbox messages before any downstream handler can add model context. */
|
|
424
374
|
export function createSupervisionPreStep({
|
|
425
375
|
ctx, config, supervisor, supervisionTurnState, todoTracker, nextStep, rebuildNotice, retainNotices,
|
|
426
|
-
auditTimeline, loadAuditCreator, scheduleReconcileInbox,
|
|
427
376
|
liveNoticeIds = (_message, ids) => ids.filter((id) => supervisor.has(id) && ctx?.agents?.get?.(id) !== undefined),
|
|
428
377
|
}) {
|
|
429
378
|
const run = async (payload, next) => {
|
|
@@ -481,25 +430,12 @@ export function createSupervisionPreStep({
|
|
|
481
430
|
current = reconcile(decision.messages)
|
|
482
431
|
}
|
|
483
432
|
if (wasSupervision && !current.hasSubstantive) return { kind: 'reject' }
|
|
484
|
-
let createMessage
|
|
485
|
-
if (auditTimeline !== undefined && current.remaining.some((message) =>
|
|
486
|
-
message?.source?.kind === 'subagent-settled' && auditTimeline.get(agent.id, message.source.senderSessionId) !== null)) {
|
|
487
|
-
createMessage = await loadAuditCreator?.()
|
|
488
|
-
current = reconcile(decision.messages)
|
|
489
|
-
if ((wasSupervision && !current.hasSubstantive) || (pure && !current.hasOrdinary)) {
|
|
490
|
-
await restoreOnce()
|
|
491
|
-
current = reconcile(decision.messages)
|
|
492
|
-
}
|
|
493
|
-
}
|
|
494
433
|
if (payload?.signal?.aborted) {
|
|
495
434
|
supervisionTurnState.clearTurn(agent.id, payload.turn)
|
|
496
435
|
return decision
|
|
497
436
|
}
|
|
498
437
|
if (wasSupervision && !current.hasSubstantive) return { kind: 'reject' }
|
|
499
|
-
|
|
500
|
-
timeline: auditTimeline, agent, messages: current.remaining, createMessage, scheduleReconcileInbox, logger: ctx?.logger,
|
|
501
|
-
})
|
|
502
|
-
return enteringMessages === decision.messages ? decision : { ...decision, messages: enteringMessages }
|
|
438
|
+
return current.remaining === decision.messages ? decision : { ...decision, messages: current.remaining }
|
|
503
439
|
}
|
|
504
440
|
return async (payload, next) => {
|
|
505
441
|
const release = retainNotices?.(payload)
|
|
@@ -523,7 +459,7 @@ export function createSupervisionPreStep({
|
|
|
523
459
|
*/
|
|
524
460
|
export function createSupervision({
|
|
525
461
|
ctx, config, logger = ctx?.logger, loadLlm = () => import('@deepseek-ai/dsh-llm'),
|
|
526
|
-
supervisionTurnState, listAttentionItems = () => [], isActive = () => true,
|
|
462
|
+
supervisionTurnState, listAttentionItems = () => [], isActive = () => true, resolveSessionConfig,
|
|
527
463
|
}) {
|
|
528
464
|
let pendingWarned = false
|
|
529
465
|
const warn = (message) => {
|
|
@@ -620,7 +556,7 @@ export function createSupervision({
|
|
|
620
556
|
if (row?.kind !== 'attention') return supervisor.has(id) && isChildAlive(id)
|
|
621
557
|
attentionById ??= new Map(listAttentionItems(parentId).map((entry) => [entry.childId, entry]))
|
|
622
558
|
const current = attentionById.get(id)
|
|
623
|
-
return current !== undefined && current.
|
|
559
|
+
return current !== undefined && current.attemptSeq === row.attemptSeq
|
|
624
560
|
})
|
|
625
561
|
}
|
|
626
562
|
const liveNoticeIds = (message, ids, parentId) =>
|
|
@@ -828,23 +764,15 @@ export function createSupervision({
|
|
|
828
764
|
/** The retry notice: same delivery, its own `source.kind`. */
|
|
829
765
|
const deliverRetry = (parentId, text, childIds) => deliverAs(RETRY_SOURCE_KIND, parentId, text, childIds)
|
|
830
766
|
|
|
831
|
-
|
|
832
|
-
|
|
833
|
-
|
|
834
|
-
|
|
835
|
-
|
|
836
|
-
|
|
837
|
-
|
|
838
|
-
|
|
839
|
-
|
|
840
|
-
return configValue(config, 'superviseMaxNoticesPerChild', 3)
|
|
841
|
-
},
|
|
842
|
-
get unlimited() {
|
|
843
|
-
return configValue(config, 'superviseUnlimited', false) === true
|
|
844
|
-
},
|
|
845
|
-
get notifyOnNoProgress() {
|
|
846
|
-
return configValue(config, 'superviseNotifyOnNoProgress', false) === true
|
|
847
|
-
},
|
|
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
|
+
}
|
|
848
776
|
}
|
|
849
777
|
|
|
850
778
|
const supervisor = createSupervisor({
|
|
@@ -882,7 +810,7 @@ export function createSupervision({
|
|
|
882
810
|
return {
|
|
883
811
|
supervisor, isParentAlive, isChildAlive, readEvents, headSeq, hasPendingNotice,
|
|
884
812
|
deliver, deliverRetry, rebuildNotice, liveNoticeIds, scheduleReconcileInbox, pendingNoticeMeta,
|
|
885
|
-
claimNotice, releaseClaimedNotices, retainNotices,
|
|
813
|
+
claimNotice, releaseClaimedNotices, retainNotices,
|
|
886
814
|
}
|
|
887
815
|
}
|
|
888
816
|
|
|
@@ -1016,32 +944,6 @@ function reserveDomain(facility) {
|
|
|
1016
944
|
return { previous, release }
|
|
1017
945
|
}
|
|
1018
946
|
|
|
1019
|
-
const MAX_GIT_BASELINE_BYTES = 32 * 1024
|
|
1020
|
-
function smallGitBaseline(baseline) {
|
|
1021
|
-
if (baseline?.kind !== 'git-worktree') return undefined
|
|
1022
|
-
return Buffer.byteLength(JSON.stringify(baseline)) <= MAX_GIT_BASELINE_BYTES ? baseline : undefined
|
|
1023
|
-
}
|
|
1024
|
-
|
|
1025
|
-
function restoredGitBaseline(row, worktree) {
|
|
1026
|
-
const baseline = row.gitBaseline
|
|
1027
|
-
if (!worktree || baseline?.kind !== 'git-worktree' || baseline.baselineId !== row.baselineId ||
|
|
1028
|
-
baseline.worktreeId !== worktree.id || baseline.worktreePath !== worktree.worktreePath ||
|
|
1029
|
-
baseline.execCwd !== worktree.execCwd || baseline.repoRoot !== worktree.repoRoot ||
|
|
1030
|
-
baseline.baseCommit !== worktree.baseCommit || baseline.branch !== worktree.branch) return undefined
|
|
1031
|
-
return baseline
|
|
1032
|
-
}
|
|
1033
|
-
|
|
1034
|
-
function missingBaselineAudit(record) {
|
|
1035
|
-
return {
|
|
1036
|
-
baselineId: record.baselineId, passed: false, readOnly: record.readOnly,
|
|
1037
|
-
isolationLevel: record.worktree ? 'git-worktree' : 'logical-post-audit',
|
|
1038
|
-
isolationNote: '历史派发基线无法恢复;不能据此确认写入合规。',
|
|
1039
|
-
changedFiles: [],
|
|
1040
|
-
violations: [{ code: 'audit-incomplete', path: '.', reason: '缺少可核验的历史派发基线' }],
|
|
1041
|
-
summary: { added: 0, modified: 0, deleted: 0, violations: 1, truncated: false },
|
|
1042
|
-
}
|
|
1043
|
-
}
|
|
1044
|
-
|
|
1045
947
|
export function apply(ctx, config) {
|
|
1046
948
|
let facility
|
|
1047
949
|
let startupError
|
|
@@ -1068,8 +970,8 @@ export function apply(ctx, config) {
|
|
|
1068
970
|
const timeline = createDispatchTimeline()
|
|
1069
971
|
const supervisionTurnState = createSupervisionTurnState()
|
|
1070
972
|
const supervision = createSupervision({
|
|
1071
|
-
ctx, config, supervisionTurnState,
|
|
1072
|
-
isActive: () => !disposing,
|
|
973
|
+
ctx, config, supervisionTurnState,
|
|
974
|
+
isActive: () => !disposing, resolveSessionConfig: (parentId) => sessionTools.resolveSessionConfig(parentId),
|
|
1073
975
|
})
|
|
1074
976
|
const writeLeases = createWriteLeases()
|
|
1075
977
|
const worktrees = createWorktreeManager()
|
|
@@ -1078,6 +980,8 @@ export function apply(ctx, config) {
|
|
|
1078
980
|
const batchStages = new Map()
|
|
1079
981
|
const detachedBatchLeases = new Set()
|
|
1080
982
|
const wakeups = new Map()
|
|
983
|
+
const pendingEdits = new Set()
|
|
984
|
+
const settlingChildren = new Set()
|
|
1081
985
|
// Keep recent shared/readonly delegates resumable in memory as well as in persistent hosts.
|
|
1082
986
|
const keepWorktreeWrite = (record) => {
|
|
1083
987
|
const worktree = record.worktree && worktrees.get(record.worktree.id)
|
|
@@ -1118,25 +1022,23 @@ export function apply(ctx, config) {
|
|
|
1118
1022
|
const row = !disposing && id && exportTree(id)
|
|
1119
1023
|
return row ? persist(stateStore.putWorktree(row)) : Promise.resolve()
|
|
1120
1024
|
}
|
|
1121
|
-
const putLease = (lease
|
|
1025
|
+
const putLease = (lease) => {
|
|
1122
1026
|
const row = !disposing && lease && writeLeases.exportLeases().find((entry) => entry.leaseId === lease.leaseId)
|
|
1123
|
-
return row ? persist(stateStore.putLease(
|
|
1027
|
+
return row ? persist(stateStore.putLease(row)) : Promise.resolve()
|
|
1124
1028
|
}
|
|
1125
1029
|
const deleteLease = (lease) => lease && !disposing
|
|
1126
1030
|
? persist(stateStore.deleteLease(lease.leaseId).then(() => true)) : Promise.resolve()
|
|
1127
|
-
const persistDelegate = (childId, record, patch = {}) => {
|
|
1128
|
-
if (disposing
|
|
1129
|
-
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()
|
|
1130
1033
|
if (!entry) return Promise.resolve()
|
|
1131
|
-
const baseline = record.attempt?.baseline
|
|
1132
1034
|
return persist(stateStore.putDelegate({
|
|
1133
|
-
...stateStore.getDelegate(childId), ...entry,
|
|
1035
|
+
...stateStore.getDelegate(childId), ...entry,
|
|
1134
1036
|
childId, parentId: record.parentId, rootSessionId: record.rootSessionId ?? record.parentId,
|
|
1135
|
-
|
|
1037
|
+
worktreeId: record.worktree?.id ?? entry.worktree?.id ?? null,
|
|
1038
|
+
pendingNextTurn: record.pendingNextTurn ?? null, ...patch,
|
|
1136
1039
|
wakeActionKey: record.wakeActionKey ?? null,
|
|
1137
1040
|
retry: retry.exportChildRecord(childId),
|
|
1138
1041
|
watchCursor: supervision.supervisor.exportCursor(childId),
|
|
1139
|
-
gitBaseline: smallGitBaseline(baseline) ?? null,
|
|
1140
1042
|
}))
|
|
1141
1043
|
}
|
|
1142
1044
|
const queueLifecycle = (handler) => (payload) => {
|
|
@@ -1147,18 +1049,29 @@ export function apply(ctx, config) {
|
|
|
1147
1049
|
}
|
|
1148
1050
|
return handler(payload)
|
|
1149
1051
|
}
|
|
1150
|
-
const defineReadyTool = (definition) =>
|
|
1151
|
-
|
|
1152
|
-
|
|
1153
|
-
|
|
1154
|
-
|
|
1155
|
-
|
|
1156
|
-
|
|
1157
|
-
|
|
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
|
+
}
|
|
1158
1070
|
const worktreeResumeRefusal = (childId) => {
|
|
1159
1071
|
const worktree = worktreeOf(childId)
|
|
1160
1072
|
const lock = worktrees.isChildLocked(childId)
|
|
1161
|
-
const missing = worktree && (!
|
|
1073
|
+
const missing = worktree && (!worktree.worktreePath || !worktree.execCwd ||
|
|
1074
|
+
!existsSync(worktree.worktreePath) || !existsSync(worktree.execCwd))
|
|
1162
1075
|
if (!lock.locked && !missing) return undefined
|
|
1163
1076
|
const detail = missing && !['merged', 'discarded'].includes(worktree.state)
|
|
1164
1077
|
? '工作树或执行目录已缺失,已拒绝投递以防写入主工作区。'
|
|
@@ -1166,56 +1079,22 @@ export function apply(ctx, config) {
|
|
|
1166
1079
|
return `[worktree-child-locked] ${formatWorktreeError('worktree-child-locked', detail)}`
|
|
1167
1080
|
}
|
|
1168
1081
|
|
|
1169
|
-
const observeAudit = ({ childId, parentId, audit, itemIndex, worktree }) => {
|
|
1170
|
-
try {
|
|
1171
|
-
ctx.emit?.('orchestrator/write-audit', { childId, parentId, audit, ...(worktree && { itemIndex, worktreeId: worktree.id }) })
|
|
1172
|
-
} catch (error) {
|
|
1173
|
-
warn(`无法发布子代理 ${childId} 的审计证据:${messageOf(error)}`)
|
|
1174
|
-
}
|
|
1175
|
-
// Failed evidence is attached to native settlement or queried, never a new wake-up turn.
|
|
1176
|
-
if (!audit.passed) warn(`【${childId}】不得验收为通过。\n${auditNotice(audit)}`)
|
|
1177
|
-
}
|
|
1178
|
-
|
|
1179
1082
|
const closeWrite = (childId, record) => {
|
|
1180
|
-
const parentId = record
|
|
1181
|
-
|
|
1182
|
-
|
|
1183
|
-
if (record.ended && record.disposalAudit !== undefined) {
|
|
1184
|
-
timeline.recordAudit(record.disposalAudit)
|
|
1185
|
-
record.disposalAudit = undefined
|
|
1186
|
-
}
|
|
1187
|
-
return
|
|
1188
|
-
}
|
|
1083
|
+
const { attempt, parentId } = record
|
|
1084
|
+
if (!attempt) return
|
|
1085
|
+
attempt.replacement?.commit?.()
|
|
1189
1086
|
record.attempt = undefined
|
|
1190
1087
|
record.releasedLease = attempt.lease
|
|
1191
1088
|
try {
|
|
1192
|
-
|
|
1193
|
-
|
|
1194
|
-
|
|
1195
|
-
|
|
1196
|
-
const evidence = {
|
|
1197
|
-
childId, parentId, runId: record.runId, baselineId: audit.baselineId,
|
|
1198
|
-
passed: audit.passed, incomplete: summary.truncated || violations.some(({ code }) => code === 'audit-incomplete'),
|
|
1199
|
-
violations, summary: `新增 ${summary.added};修改 ${summary.modified};删除 ${summary.deleted};违规 ${summary.violations}`,
|
|
1200
|
-
isolation: audit.isolationLevel, at: Date.now(),
|
|
1201
|
-
}
|
|
1202
|
-
if (record.worktree && audit.isolationLevel === 'git-worktree') {
|
|
1203
|
-
const stats = worktreeAuditSummary(audit)
|
|
1204
|
-
const review = worktrees.markReadyForReview(record.worktree.id, stats)
|
|
1205
|
-
background(putTree(record.worktree.id))
|
|
1206
|
-
timeline.recordWorktreeState(childId, { parentId, id: record.worktree.id, state: review?.state, ...stats })
|
|
1207
|
-
// Keep the full Git audit for the same-frame notice, including when disposal precedes end.
|
|
1208
|
-
evidence.audit = audit
|
|
1209
|
-
}
|
|
1210
|
-
// A disposal can provide negative evidence and release the lease, but only end certifies a pass.
|
|
1211
|
-
if (!record.ended && evidence.passed && !evidence.incomplete) record.disposalAudit = evidence
|
|
1212
|
-
else timeline.recordAudit(evidence)
|
|
1213
|
-
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))
|
|
1214
1093
|
}
|
|
1215
1094
|
} finally {
|
|
1216
1095
|
if (!record.batchId) {
|
|
1217
1096
|
releaseWriteScope(writeLeases, attempt.lease)
|
|
1218
|
-
if (attempt.lease) timeline.recordLeaseReleased({ childId, parentId, leaseId: attempt.lease.leaseId
|
|
1097
|
+
if (attempt.lease) timeline.recordLeaseReleased({ childId, parentId, leaseId: attempt.lease.leaseId })
|
|
1219
1098
|
}
|
|
1220
1099
|
supervision.scheduleReconcileInbox(parentId)
|
|
1221
1100
|
}
|
|
@@ -1227,130 +1106,209 @@ export function apply(ctx, config) {
|
|
|
1227
1106
|
if (!record.batchId) background(persistDelegate(childId, record).then(() => deleteLease(record.releasedLease)))
|
|
1228
1107
|
}
|
|
1229
1108
|
|
|
1230
|
-
const
|
|
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 } = {}) => {
|
|
1231
1124
|
const refusal = worktreeResumeRefusal(childId)
|
|
1232
1125
|
if (refusal) throw new Error(refusal)
|
|
1233
1126
|
const { parentId } = record
|
|
1234
|
-
|
|
1235
|
-
if (
|
|
1236
|
-
|
|
1237
|
-
|
|
1238
|
-
|
|
1239
|
-
|
|
1240
|
-
|
|
1241
|
-
|
|
1242
|
-
|
|
1243
|
-
|
|
1244
|
-
|
|
1245
|
-
|
|
1246
|
-
|
|
1247
|
-
|
|
1248
|
-
|
|
1249
|
-
|
|
1250
|
-
releaseWriteScope(writeLeases, lease)
|
|
1251
|
-
throw error
|
|
1252
|
-
}
|
|
1253
|
-
record.attempt = { lease, baseline }
|
|
1254
|
-
record.baselineId = baseline?.baselineId
|
|
1255
|
-
record.ended = false
|
|
1256
|
-
record.runId = undefined
|
|
1257
|
-
record.agent = null // Await the new residency; an old disposal cannot close this lease.
|
|
1258
|
-
timeline.recordRetry({
|
|
1259
|
-
parentId, childId, baselineId: baseline?.baselineId, leaseId: lease?.leaseId,
|
|
1260
|
-
readOnly: record.readOnly, startedAt: Date.now(),
|
|
1261
|
-
})
|
|
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 })
|
|
1262
1143
|
return record.attempt
|
|
1263
1144
|
}
|
|
1264
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
|
+
|
|
1265
1157
|
const wakeIdentity = (childId, record) => ({
|
|
1266
1158
|
childId, parentId: record.parentId, rootSessionId: record.rootSessionId ?? record.parentId,
|
|
1267
|
-
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,
|
|
1268
1160
|
})
|
|
1269
1161
|
const inspectChild = (identity) => inspectHostChildState({
|
|
1270
1162
|
childId: identity.childId, expectedParentId: identity.parentId, expectedRootSessionId: identity.rootSessionId,
|
|
1271
1163
|
agents: ctx.agents, sessions: ctx.sessions, sessionQuery: optionalSessionQuery(), signal: startupAbort.signal,
|
|
1272
1164
|
})
|
|
1273
|
-
const
|
|
1274
|
-
|
|
1275
|
-
|
|
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
|
+
}
|
|
1276
1283
|
|
|
1277
1284
|
// The policy still owns classification and budget; the adapter owns the durable wakeup and lease.
|
|
1278
1285
|
const retry = createRetry({
|
|
1279
1286
|
async deliverPrompt(parentId, childId, text) {
|
|
1280
1287
|
assertActive()
|
|
1281
1288
|
const record = writes.get(childId)
|
|
1282
|
-
if (record
|
|
1283
|
-
throw new Error('
|
|
1284
|
-
}
|
|
1285
|
-
const refusal = worktreeResumeRefusal(childId)
|
|
1286
|
-
if (refusal) throw new Error(refusal)
|
|
1287
|
-
let reservation
|
|
1288
|
-
let sent = false
|
|
1289
|
-
if (hasStorage) {
|
|
1290
|
-
const identity = wakeIdentity(childId, record)
|
|
1291
|
-
const hostState = await inspectChild(identity)
|
|
1292
|
-
assertActive()
|
|
1293
|
-
const retryOrdinal = retry.exportChildRecord(childId).records[0]?.retries ?? 1
|
|
1294
|
-
const gate = evaluateWakeupGate({ ...identity, kind: 'retry', retryOrdinal, worktrees, hostState, actionLedger })
|
|
1295
|
-
if (!gate.allowed || wakeups.has(childId) || record.runId !== identity.runId || record.attempt) {
|
|
1296
|
-
throw new Error(`唤醒门禁拒绝自动续跑:${gate.allowed ? 'in-flight' : gate.reason}`)
|
|
1297
|
-
}
|
|
1298
|
-
reservation = { key: gate.actionKey, kind: 'retry', identity }
|
|
1299
|
-
wakeups.set(childId, reservation)
|
|
1289
|
+
if (!record || record.parentId !== parentId || record.attempt || typeof ctx.subagents?.prompt !== 'function') {
|
|
1290
|
+
throw new Error('没有可安全恢复的委派或宿主续跑能力;已拒绝自动续跑。')
|
|
1300
1291
|
}
|
|
1301
|
-
|
|
1302
|
-
|
|
1303
|
-
|
|
1304
|
-
|
|
1305
|
-
|
|
1306
|
-
|
|
1307
|
-
|
|
1308
|
-
|
|
1309
|
-
|
|
1310
|
-
assertActive()
|
|
1311
|
-
}
|
|
1312
|
-
} catch (error) {
|
|
1313
|
-
if (reservation && wakeups.get(childId) === reservation) wakeups.delete(childId)
|
|
1314
|
-
if (attempt && record.attempt === attempt) {
|
|
1315
|
-
record.attempt = undefined
|
|
1316
|
-
record.ended = true
|
|
1317
|
-
releaseWriteScope(writeLeases, attempt.lease)
|
|
1318
|
-
await deleteLease(attempt.lease)
|
|
1319
|
-
}
|
|
1320
|
-
throw error
|
|
1321
|
-
}
|
|
1322
|
-
const { lease, baseline } = attempt
|
|
1323
|
-
try {
|
|
1324
|
-
const baselineNote = baseline === undefined ? '' : `\n本轮写后审计基线:${baseline.baselineId}。`
|
|
1325
|
-
const modeNote = record.readOnly ? `\n${READ_ONLY_NOTICE}` : ''
|
|
1326
|
-
const worktreeNote = record.worktree ? `\n${worktreePromptNote(record.worktree)}` : ''
|
|
1327
|
-
if (reservation?.observed) return undefined
|
|
1328
|
-
sent = true
|
|
1329
|
-
if (reservation) reservation.submitted = true
|
|
1330
|
-
const messageId = await deliverRetryPrompt(ctx, parentId, childId,
|
|
1331
|
-
text + modeNote + baselineNote + worktreeNote, reservation?.requestId)
|
|
1332
|
-
if (reservation && !disposing) {
|
|
1333
|
-
if (!messageId && !record.runId) throw new Error('宿主未确认投递')
|
|
1334
|
-
await actionLedger.markAccepted(reservation.key, { messageId })
|
|
1335
|
-
if (record.runId) await actionLedger.markDone(reservation.key, { messageId })
|
|
1336
|
-
}
|
|
1337
|
-
return messageId
|
|
1338
|
-
} catch (error) {
|
|
1339
|
-
if (reservation && sent) {
|
|
1340
|
-
// A transport error is not evidence that no activation happened.
|
|
1341
|
-
if (!disposing && !record.runId) await actionLedger.markUnknown(reservation.key, { detail: messageOf(error) })
|
|
1342
|
-
throw error
|
|
1343
|
-
}
|
|
1344
|
-
if (record.attempt === attempt) {
|
|
1345
|
-
record.attempt = undefined
|
|
1346
|
-
record.ended = true
|
|
1347
|
-
timeline.recordDisposed({ childId, parentId, at: Date.now() })
|
|
1348
|
-
releaseWriteScope(writeLeases, lease)
|
|
1349
|
-
if (lease) timeline.recordLeaseReleased({ childId, parentId, leaseId: lease.leaseId, at: Date.now() })
|
|
1350
|
-
}
|
|
1351
|
-
supervision.scheduleReconcileInbox(parentId)
|
|
1352
|
-
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}`)
|
|
1353
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
|
+
} })
|
|
1354
1312
|
},
|
|
1355
1313
|
wakeParent: (...args) => disposing ? undefined : supervision.deliverRetry(...args),
|
|
1356
1314
|
logger: ctx.logger,
|
|
@@ -1371,7 +1329,7 @@ export function apply(ctx, config) {
|
|
|
1371
1329
|
// change. A notice pushed at that moment would splice into a turn the user is still reading,
|
|
1372
1330
|
// so the change is only recorded here and delivered when that agent's next turn begins.
|
|
1373
1331
|
const switchNotices = createSwitchNotices({
|
|
1374
|
-
readEnabled: () =>
|
|
1332
|
+
readEnabled: (id) => dispatchEnabled(rootAgents.get(id) ?? id),
|
|
1375
1333
|
logger: ctx.logger,
|
|
1376
1334
|
})
|
|
1377
1335
|
|
|
@@ -1387,6 +1345,13 @@ export function apply(ctx, config) {
|
|
|
1387
1345
|
if (!lease || !detachedBatchLeases.has(lease.leaseId)) return
|
|
1388
1346
|
const stageRows = stateStore.listDelegates().filter((row) => row.leaseId === lease.leaseId)
|
|
1389
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
|
+
}
|
|
1390
1355
|
await deleteLease(lease)
|
|
1391
1356
|
releaseWriteScope(writeLeases, lease)
|
|
1392
1357
|
detachedBatchLeases.delete(lease.leaseId)
|
|
@@ -1405,6 +1370,8 @@ export function apply(ctx, config) {
|
|
|
1405
1370
|
if (hostRuns.get(childId)?.runId === runId && runId) rememberRecent(earlyEnds, childId, info)
|
|
1406
1371
|
return
|
|
1407
1372
|
}
|
|
1373
|
+
const wakeKey = wakeups.get(childId)?.key ?? record.wakeActionKey
|
|
1374
|
+
if (wakeKey && (!runId || runId === actionLedger.get(wakeKey)?.runId)) return
|
|
1408
1375
|
if (typeof info.parentSessionId === 'string' && record.parentId !== info.parentSessionId) return
|
|
1409
1376
|
if (record.runId && runId && record.runId !== runId) return
|
|
1410
1377
|
if (runId) {
|
|
@@ -1434,22 +1401,29 @@ export function apply(ctx, config) {
|
|
|
1434
1401
|
hooks.forget(childId)
|
|
1435
1402
|
supervision.scheduleReconcileInbox(parentId)
|
|
1436
1403
|
const lease = record.releasedLease
|
|
1437
|
-
|
|
1438
|
-
|
|
1439
|
-
|
|
1440
|
-
|
|
1441
|
-
|
|
1442
|
-
|
|
1443
|
-
|
|
1444
|
-
|
|
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.
|
|
1445
1421
|
try {
|
|
1446
1422
|
await retry.settle(childId, info, runId ?? record.runId)
|
|
1447
1423
|
} finally {
|
|
1448
1424
|
await persistDelegate(childId, record)
|
|
1449
1425
|
}
|
|
1450
|
-
}
|
|
1451
|
-
const pending = settle().catch((error) => warn(`无法结算子代理 ${childId}:${messageOf(error)}`))
|
|
1452
|
-
return pending
|
|
1426
|
+
})().catch((error) => warn(`无法结算子代理 ${childId}:${messageOf(error)}`))
|
|
1453
1427
|
}
|
|
1454
1428
|
|
|
1455
1429
|
const onDelegateStarted = (parent, started, args, write, agentName) => {
|
|
@@ -1457,12 +1431,12 @@ export function apply(ctx, config) {
|
|
|
1457
1431
|
const parentId = parent.id
|
|
1458
1432
|
const cachedRun = hostRuns.get(childId)
|
|
1459
1433
|
const hostRun = cachedRun?.parentId === undefined || cachedRun.parentId === parentId ? cachedRun : undefined
|
|
1460
|
-
const {
|
|
1434
|
+
const { lease, ...metadata } = write
|
|
1461
1435
|
const runId = hostRun?.runId ?? started.runId
|
|
1462
1436
|
if (disposing) return
|
|
1463
1437
|
timeline.recordDispatched({
|
|
1464
1438
|
parentId, childId, agentName, label: args.description, readOnly: write.readOnly, writeScope: write.writeScope,
|
|
1465
|
-
cwd: write.cwd,
|
|
1439
|
+
cwd: write.cwd, allowNewReason: write.allowNewReason, leaseId: lease?.leaseId, startedAt: Date.now(), worktree: write.worktree,
|
|
1466
1440
|
})
|
|
1467
1441
|
timeline.recordRunStarted({ childId, parentId, runId })
|
|
1468
1442
|
const record = {
|
|
@@ -1470,17 +1444,18 @@ export function apply(ctx, config) {
|
|
|
1470
1444
|
parentId,
|
|
1471
1445
|
rootSessionId: parent.session?.header?.rootSessionId ?? parentId,
|
|
1472
1446
|
label: args.description,
|
|
1473
|
-
|
|
1474
|
-
expectedTargets: baseline?.expectedTargets ?? args.expectedTargets,
|
|
1447
|
+
agentName,
|
|
1475
1448
|
runId,
|
|
1476
1449
|
agent: hostRun?.agent ?? ctx.agents?.get?.(childId),
|
|
1477
|
-
attempt: { lease
|
|
1450
|
+
attempt: { lease },
|
|
1478
1451
|
}
|
|
1479
1452
|
writes.set(childId, record)
|
|
1480
1453
|
// Keep resumable worktree metadata through review, but bound other detached records.
|
|
1481
1454
|
for (const [id, record] of writes) {
|
|
1482
1455
|
if (writes.size <= 256) break
|
|
1483
|
-
if (record.attempt === undefined && !retry.has(id) && !wakeups.has(id) && !keepWorktreeWrite(record))
|
|
1456
|
+
if (record.attempt === undefined && !record.pendingNextTurn && !retry.has(id) && !wakeups.has(id) && !keepWorktreeWrite(record)) {
|
|
1457
|
+
writes.delete(id)
|
|
1458
|
+
}
|
|
1484
1459
|
}
|
|
1485
1460
|
hooks.onStarted(parent, { ...started, runId }, args, write)
|
|
1486
1461
|
const durable = Promise.all([putTree(write.worktree?.id), saveAttempt(childId, record)])
|
|
@@ -1522,7 +1497,7 @@ export function apply(ctx, config) {
|
|
|
1522
1497
|
isDisposing: () => disposing,
|
|
1523
1498
|
async beforeLaunch(write) {
|
|
1524
1499
|
assertActive()
|
|
1525
|
-
await Promise.all([putTree(write.worktree?.id), putLease(write.lease
|
|
1500
|
+
await Promise.all([putTree(write.worktree?.id), putLease(write.lease)])
|
|
1526
1501
|
},
|
|
1527
1502
|
async afterFailedLaunch(write) {
|
|
1528
1503
|
await putTree(write.worktree?.id)
|
|
@@ -1544,13 +1519,13 @@ export function apply(ctx, config) {
|
|
|
1544
1519
|
}
|
|
1545
1520
|
const record = {
|
|
1546
1521
|
...stage, batchId, childId, parentId: parent.id, rootSessionId: parent.session?.header?.rootSessionId ?? parent.id,
|
|
1547
|
-
worktree: write.worktree,
|
|
1522
|
+
worktree: write.worktree, runId,
|
|
1548
1523
|
}
|
|
1549
1524
|
batch.children.set(childId, { record, ended: false })
|
|
1550
1525
|
batchStages.set(childId, batch)
|
|
1551
|
-
timeline.recordDispatched({ ...record, ...write,
|
|
1526
|
+
timeline.recordDispatched({ ...record, ...write, leaseId: write.lease?.leaseId })
|
|
1552
1527
|
timeline.recordRunStarted({ childId, parentId: parent.id, runId })
|
|
1553
|
-
await Promise.all([putTree(write.worktree?.id), putLease(write.lease
|
|
1528
|
+
await Promise.all([putTree(write.worktree?.id), putLease(write.lease),
|
|
1554
1529
|
persistDelegate(childId, record, { ...stage, batchId })])
|
|
1555
1530
|
},
|
|
1556
1531
|
async stageEnded(batch, handle, result) {
|
|
@@ -1565,19 +1540,14 @@ export function apply(ctx, config) {
|
|
|
1565
1540
|
canFinishBatch(batch) {
|
|
1566
1541
|
return batch.inFlightStarts === 0 && [...batch.children.values()].every((stage) => stage.ended)
|
|
1567
1542
|
},
|
|
1568
|
-
async finishBatch(batch
|
|
1543
|
+
async finishBatch(batch) {
|
|
1569
1544
|
const { write } = batch
|
|
1570
1545
|
await putTree(write.worktree?.id)
|
|
1571
1546
|
for (const [childId, { record }] of batch.children) {
|
|
1572
1547
|
if (disposing) return
|
|
1573
1548
|
const { parentId } = record
|
|
1574
|
-
if (audit) {
|
|
1575
|
-
const incomplete = audit.summary.truncated || audit.violations.some(({ code }) => code === 'audit-incomplete')
|
|
1576
|
-
timeline.recordAudit({ childId, parentId, baselineId: audit.baselineId, passed: audit.passed,
|
|
1577
|
-
incomplete, violations: audit.violations, isolation: audit.isolationLevel, audit })
|
|
1578
|
-
}
|
|
1579
1549
|
const tree = write.worktree && worktrees.get(write.worktree.id)
|
|
1580
|
-
if (tree) timeline.recordWorktreeState(childId, { parentId, id: tree.id, state: tree.state
|
|
1550
|
+
if (tree) timeline.recordWorktreeState(childId, { parentId, id: tree.id, state: tree.state })
|
|
1581
1551
|
if (write.lease) timeline.recordLeaseReleased({ childId, parentId, leaseId: write.lease.leaseId })
|
|
1582
1552
|
await persistDelegate(childId, record, { batchId: record.batchId, itemIndex: record.itemIndex, stageIndex: record.stageIndex })
|
|
1583
1553
|
batchStages.delete(childId)
|
|
@@ -1590,14 +1560,73 @@ export function apply(ctx, config) {
|
|
|
1590
1560
|
// The same live whitelist feeds the prompt, execution guard and tool definitions.
|
|
1591
1561
|
const catalog = createCatalogPublisher({ ctx, config })
|
|
1592
1562
|
const allowAgentTeam = () => configValue(config, 'allowAgentTeam', true) !== false
|
|
1593
|
-
const
|
|
1594
|
-
|
|
1563
|
+
const isNativeTeamEnabled = (agent) => {
|
|
1564
|
+
try {
|
|
1565
|
+
// The optional host service resolves the caller's root and reads its Team projection.
|
|
1566
|
+
const teams = typeof ctx.get === 'function' ? ctx.get('agentTeams') : ctx.agentTeams
|
|
1567
|
+
return teams?.isEnabled?.(agent) === true
|
|
1568
|
+
} catch {
|
|
1569
|
+
// An unavailable service or a scope without a live Team root must not break tool rendering.
|
|
1570
|
+
return false
|
|
1571
|
+
}
|
|
1572
|
+
}
|
|
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
|
+
})
|
|
1602
|
+
const allowedToolsFor = (subject) => sessionTools.resolveAllowedTools(subject, {
|
|
1603
|
+
globalAllowed: configValue(config, 'allowedTools', undefined),
|
|
1604
|
+
defaultAllowed: DEFAULT_ALLOWED_TOOLS,
|
|
1595
1605
|
allowAgentTeam: allowAgentTeam(),
|
|
1596
|
-
|
|
1606
|
+
catalog: catalog.published(),
|
|
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
|
+
},
|
|
1597
1621
|
})
|
|
1598
|
-
|
|
1599
|
-
|
|
1600
|
-
|
|
1622
|
+
listen('tools/result', (exec, result) => {
|
|
1623
|
+
if (disposing) return
|
|
1624
|
+
background(readIndex.observe(exec, result).catch((error) => warn(`只读索引采集失败:${messageOf(error)}`)))
|
|
1625
|
+
}, { global: true })
|
|
1626
|
+
const sessionToolsRemote = mountSessionToolsRemote(ctx, sessionTools)
|
|
1627
|
+
if (!sessionToolsRemote.available && typeof ctx.provide === 'function') warn(sessionToolsRemote.error)
|
|
1628
|
+
const nativeToolNote = (allowed) => {
|
|
1629
|
+
const team = NATIVE_TEAM_TOOLS.some((name) => allowed?.includes(name))
|
|
1601
1630
|
? '原生 team_task_* 仅用于共享任务板,不替代派发或写租约。'
|
|
1602
1631
|
: ''
|
|
1603
1632
|
return `${team}subagent_fork / workflow 默认屏蔽。`
|
|
@@ -1605,9 +1634,7 @@ export function apply(ctx, config) {
|
|
|
1605
1634
|
|
|
1606
1635
|
const worktreeDispatch = {
|
|
1607
1636
|
worktrees,
|
|
1608
|
-
|
|
1609
|
-
captureGitBaseline,
|
|
1610
|
-
auditGitBaseline,
|
|
1637
|
+
resolveSessionConfig: sessionTools.resolveSessionConfig,
|
|
1611
1638
|
probeGitRepo,
|
|
1612
1639
|
onCleanupFailed: (error) => warn(`无法清理未启动的工作树:${messageOf(error)}`),
|
|
1613
1640
|
}
|
|
@@ -1620,8 +1647,11 @@ export function apply(ctx, config) {
|
|
|
1620
1647
|
subagents: ctx.subagents,
|
|
1621
1648
|
config,
|
|
1622
1649
|
onStarted: onDelegateStarted,
|
|
1650
|
+
listReusableChildren,
|
|
1623
1651
|
nativeToolNote,
|
|
1624
|
-
|
|
1652
|
+
// Direct, unscoped consumers retain the global description. Scoped declarations
|
|
1653
|
+
// replace it with describeFor(allowedToolsFor(scope)) without touching the registry.
|
|
1654
|
+
allowedTools: () => allowedToolsFor(undefined),
|
|
1625
1655
|
leases: writeLeases,
|
|
1626
1656
|
})
|
|
1627
1657
|
// Both tools share the one table, so a `delegate` and a batch (or two batches) cannot
|
|
@@ -1630,11 +1660,10 @@ export function apply(ctx, config) {
|
|
|
1630
1660
|
const orchestrateTool = createOrchestrateTool({
|
|
1631
1661
|
...worktreeDispatch,
|
|
1632
1662
|
defineTool: defineReadyTool,
|
|
1633
|
-
stageTracking
|
|
1663
|
+
stageTracking,
|
|
1634
1664
|
subagents: ctx.subagents,
|
|
1635
1665
|
config,
|
|
1636
1666
|
leases: writeLeases,
|
|
1637
|
-
onAudited: observeAudit,
|
|
1638
1667
|
})
|
|
1639
1668
|
own(() => ctx.tools.register(delegateTool), 'orchestrator: delegate tool')
|
|
1640
1669
|
own(() => ctx.tools.register(orchestrateTool), `orchestrator: ${ORCHESTRATE_TOOL} tool`)
|
|
@@ -1642,11 +1671,16 @@ export function apply(ctx, config) {
|
|
|
1642
1671
|
defineTool: defineReadyTool,
|
|
1643
1672
|
timeline,
|
|
1644
1673
|
toolName: DELEGATE_STATUS_TOOL_NAME,
|
|
1674
|
+
editNextTurn,
|
|
1645
1675
|
isRootAgent: (agent) => !isDelegatedChild(agent),
|
|
1646
1676
|
})
|
|
1647
1677
|
own(() => ctx.tools.register(delegateStatusTool), `orchestrator: ${DELEGATE_STATUS_TOOL_NAME} tool`)
|
|
1648
1678
|
const worktreeManageTool = createPersistentWorktreeTool({
|
|
1649
|
-
|
|
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,
|
|
1650
1684
|
onClosed(record) {
|
|
1651
1685
|
const write = writes.get(record.childId)
|
|
1652
1686
|
if (write?.worktree?.id === record.id && write.attempt === undefined) writes.delete(record.childId)
|
|
@@ -1670,27 +1704,26 @@ export function apply(ctx, config) {
|
|
|
1670
1704
|
refusal = worktreeResumeRefusal(childId)
|
|
1671
1705
|
}
|
|
1672
1706
|
if (refusal) throw new Error(refusal)
|
|
1673
|
-
const row =
|
|
1707
|
+
const row = stateStore.getDelegate(childId)
|
|
1674
1708
|
const record = writes.get(childId) ?? row
|
|
1675
1709
|
if (!record) return { childId }
|
|
1710
|
+
const blocked = wakeupRefusal(childId, record)
|
|
1711
|
+
if (blocked) throw new Error(`唤醒门禁拒绝 send_message:${blocked}`)
|
|
1676
1712
|
const identity = wakeIdentity(childId, record)
|
|
1677
|
-
|
|
1678
|
-
|
|
1679
|
-
|
|
1680
|
-
|
|
1681
|
-
|
|
1682
|
-
|
|
1683
|
-
|
|
1684
|
-
if (!pending.allowed && pending.record?.phase !== 'done') throw new Error(`唤醒门禁拒绝 send_message:${pending.reason}`)
|
|
1685
|
-
}
|
|
1686
|
-
if (record.batchId) throw new Error('编排阶段不能单独恢复;请新建任务。')
|
|
1687
|
-
const gate = evaluateWakeupGate({ ...identity, kind: 'resume', worktrees, hostState, actionLedger })
|
|
1688
|
-
if (!gate.allowed) throw new Error(`唤醒门禁拒绝 send_message:${gate.reason}`)
|
|
1689
|
-
if (wakeups.has(childId) || identity.runId !== record.runId) throw new Error('唤醒门禁拒绝 send_message:in-flight')
|
|
1690
|
-
if (record.attempt) throw new Error('原运行仍在结算,请稍后向同一代理重试。')
|
|
1691
|
-
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')
|
|
1692
1720
|
}
|
|
1693
|
-
|
|
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 }
|
|
1694
1727
|
}
|
|
1695
1728
|
|
|
1696
1729
|
// Early preflight keeps lock refusals visible to direct and Code Mode callers. Reserve
|
|
@@ -1710,75 +1743,36 @@ export function apply(ctx, config) {
|
|
|
1710
1743
|
listen('tools/execute', async (exec, next) => {
|
|
1711
1744
|
if (exec.name !== 'send_message') return next()
|
|
1712
1745
|
if (restoring) await readyPromise
|
|
1713
|
-
const { childId, row, identity, key } = await resolveMessageTarget(exec)
|
|
1746
|
+
const { childId, row, identity, key: actionKey } = await resolveMessageTarget(exec)
|
|
1714
1747
|
if (!identity) return next()
|
|
1715
|
-
const refusal = worktreeResumeRefusal(childId)
|
|
1716
|
-
if (refusal) throw new Error(refusal)
|
|
1717
1748
|
const current = writes.get(childId) ?? hydrateWrite(row)
|
|
1718
|
-
if (
|
|
1719
|
-
|
|
1720
|
-
|
|
1721
|
-
|
|
1722
|
-
|
|
1723
|
-
|
|
1724
|
-
|
|
1725
|
-
|
|
1726
|
-
|
|
1727
|
-
|
|
1728
|
-
|
|
1729
|
-
|
|
1730
|
-
|
|
1731
|
-
|
|
1732
|
-
if (key) {
|
|
1733
|
-
const claim = await actionLedger.prepare(key, { ...identity, kind: 'resume' })
|
|
1734
|
-
if (!claim.ok) throw new Error(`唤醒门禁拒绝 send_message:${claim.reason}`)
|
|
1735
|
-
prepared = true
|
|
1736
|
-
current.wakeActionKey = key
|
|
1737
|
-
await saveAttempt(childId, current)
|
|
1738
|
-
}
|
|
1739
|
-
assertActive()
|
|
1740
|
-
const refusal = worktreeResumeRefusal(childId)
|
|
1741
|
-
if (refusal) throw new Error(refusal)
|
|
1742
|
-
exec.signal?.throwIfAborted?.()
|
|
1743
|
-
delivering = true
|
|
1744
|
-
result = await next()
|
|
1745
|
-
if (key && !result?.isError) await actionLedger.markAccepted(key, { messageId: result?.value?.messageId })
|
|
1746
|
-
return result
|
|
1747
|
-
} finally {
|
|
1748
|
-
// A published start takes ownership, even if a later hook cannot confirm delivery.
|
|
1749
|
-
if (!reservation.observed && (!delivering || result?.isError === true)) {
|
|
1750
|
-
if (attempt && current.attempt === attempt) {
|
|
1751
|
-
Object.assign(current, previous, { wakeActionKey: previous.wakeActionKey })
|
|
1752
|
-
releaseWriteScope(writeLeases, attempt.lease)
|
|
1753
|
-
if (entry) timeline.hydrateEntries([{ ...entry, updatedAt: Date.now() }])
|
|
1754
|
-
}
|
|
1755
|
-
try {
|
|
1756
|
-
if (prepared) await actionLedger.cancelPrepared(key)
|
|
1757
|
-
if (attempt && key) {
|
|
1758
|
-
await deleteLease(attempt.lease)
|
|
1759
|
-
await persistDelegate(childId, current)
|
|
1760
|
-
}
|
|
1761
|
-
} finally {
|
|
1762
|
-
if (wakeups.get(childId) === reservation) wakeups.delete(childId)
|
|
1763
|
-
}
|
|
1764
|
-
} else if (key && delivering && !result && !reservation.observed) {
|
|
1765
|
-
await actionLedger.markUnknown(key)
|
|
1766
|
-
}
|
|
1767
|
-
}
|
|
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
|
+
})
|
|
1768
1763
|
}, { global: true })
|
|
1769
|
-
|
|
1770
1764
|
/**
|
|
1771
1765
|
* The live guard of every gated main agent, keyed by agent id. One predicate covers every
|
|
1772
1766
|
* name — global, scope-local, and calls nested inside `run_code` — so nothing has to be
|
|
1773
1767
|
* rebuilt when the panel or the registry changes; it is dropped with the agent.
|
|
1774
1768
|
*/
|
|
1775
|
-
const dispatchEnabled = () =>
|
|
1769
|
+
const dispatchEnabled = (subject) => sessionTools.resolveSessionConfig(subject).enabled
|
|
1776
1770
|
|
|
1777
1771
|
const gates = new Map()
|
|
1778
1772
|
|
|
1779
1773
|
const installFor = (agent) => installGate({
|
|
1780
1774
|
agent,
|
|
1781
|
-
allowed:
|
|
1775
|
+
allowed: allowedToolsFor,
|
|
1782
1776
|
allowAgentTeam,
|
|
1783
1777
|
enabled: dispatchEnabled,
|
|
1784
1778
|
checkSupervision: (current, tool, options) => supervisionTurnState.checkTool(current.id, currentTurnOf(current), tool, options),
|
|
@@ -1810,13 +1804,41 @@ export function apply(ctx, config) {
|
|
|
1810
1804
|
* (a request built inside that window saw them appear, the next saw them vanish, and the
|
|
1811
1805
|
* cached prompt prefix was lost each time).
|
|
1812
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
|
+
}
|
|
1813
1831
|
own(
|
|
1814
1832
|
() =>
|
|
1815
1833
|
installToolSurface({
|
|
1816
1834
|
tools: ctx.tools,
|
|
1817
|
-
allowed:
|
|
1835
|
+
allowed: allowedToolsFor,
|
|
1836
|
+
describeDelegate: delegateTool.describeFor,
|
|
1818
1837
|
allowAgentTeam,
|
|
1838
|
+
isNativeTeamEnabled,
|
|
1819
1839
|
enabled: dispatchEnabled,
|
|
1840
|
+
readOnlyEnabled: (subject) => sessionTools.resolveSessionConfig(subject).readOnlyEnabled,
|
|
1841
|
+
describeOrchestrate: orchestrateTool.describeFor,
|
|
1820
1842
|
}),
|
|
1821
1843
|
'orchestrator: tool surface',
|
|
1822
1844
|
)
|
|
@@ -1827,7 +1849,7 @@ export function apply(ctx, config) {
|
|
|
1827
1849
|
const scope = row.readOnly ? null : normalizeScope(row.writeScope ?? [], row.cwd)
|
|
1828
1850
|
const record = {
|
|
1829
1851
|
...row, worktree, agent, ended: !active, entries: lease?.entries ?? scope?.entries,
|
|
1830
|
-
attempt: active ? { lease
|
|
1852
|
+
attempt: active ? { lease } : undefined,
|
|
1831
1853
|
}
|
|
1832
1854
|
writes.set(row.childId, record)
|
|
1833
1855
|
if (active && row.batchId && lease) detachedBatchLeases.add(lease.leaseId)
|
|
@@ -1842,6 +1864,10 @@ export function apply(ctx, config) {
|
|
|
1842
1864
|
})
|
|
1843
1865
|
}
|
|
1844
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
|
|
1845
1871
|
if (record.worktree) {
|
|
1846
1872
|
const review = worktrees.reopenForRetry(record.worktree.id)
|
|
1847
1873
|
timeline.recordWorktreeState(childId, {
|
|
@@ -1853,16 +1879,14 @@ export function apply(ctx, config) {
|
|
|
1853
1879
|
record.runId = runId ?? record.runId
|
|
1854
1880
|
record.agent = agent
|
|
1855
1881
|
timeline.recordRunStarted({ childId, parentId: record.parentId, runId })
|
|
1856
|
-
const reservation = wakeups.get(childId)
|
|
1857
1882
|
if (reservation) {
|
|
1858
1883
|
reservation.observed = true
|
|
1859
|
-
|
|
1884
|
+
record.attempt?.replacement?.commit()
|
|
1885
|
+
wakeups.delete(childId)
|
|
1860
1886
|
}
|
|
1887
|
+
if (actionKey && !retry.has(childId)) retry.track(childId, { parentId: record.parentId, label: record.label })
|
|
1861
1888
|
if (changedRun && (hasStorage || reservation)) armRun(childId, record, { resumed: true })
|
|
1862
|
-
|
|
1863
|
-
const previousRun = reservation?.identity.runId ?? actionLedger.get(actionKey)?.runId
|
|
1864
|
-
if (reservation && runId !== previousRun) wakeups.delete(childId)
|
|
1865
|
-
if (actionKey && runId && runId !== previousRun) {
|
|
1889
|
+
if (actionKey) {
|
|
1866
1890
|
record.wakeActionKey = null
|
|
1867
1891
|
return persistDelegate(childId, record).then(() => actionLedger.markDone(actionKey))
|
|
1868
1892
|
}
|
|
@@ -1876,6 +1900,18 @@ export function apply(ctx, config) {
|
|
|
1876
1900
|
const record = writes.get(childId) ?? (row && !row.batchId && hydrateWrite(row))
|
|
1877
1901
|
if (!record || record.batchId || (parentId && record.parentId !== parentId)) return
|
|
1878
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
|
+
}
|
|
1879
1915
|
let reservation = wakeups.get(childId)
|
|
1880
1916
|
if (!reservation) {
|
|
1881
1917
|
const identity = wakeIdentity(childId, record)
|
|
@@ -1896,10 +1932,6 @@ export function apply(ctx, config) {
|
|
|
1896
1932
|
await actionLedger.markAccepted(reservation.key)
|
|
1897
1933
|
}
|
|
1898
1934
|
if (!record.attempt) {
|
|
1899
|
-
if (!record.readOnly && !record.entries?.length) {
|
|
1900
|
-
warn(`子代理 ${childId} 缺少可验证的写作用域;未重建活跃追踪`)
|
|
1901
|
-
return
|
|
1902
|
-
}
|
|
1903
1935
|
prepareWriteRetry(childId, record)
|
|
1904
1936
|
record.wakeActionKey = reservation.key
|
|
1905
1937
|
if (!retry.has(childId)) retry.track(childId, { parentId: record.parentId, label: record.label })
|
|
@@ -1981,7 +2013,7 @@ export function apply(ctx, config) {
|
|
|
1981
2013
|
prepareWriteRetry(childId, record)
|
|
1982
2014
|
if (!retry.has(childId)) retry.track(childId, { parentId: record.parentId })
|
|
1983
2015
|
} catch (error) {
|
|
1984
|
-
warn(`无法为子代理 ${childId}
|
|
2016
|
+
warn(`无法为子代理 ${childId} 的返工登记租约:${messageOf(error)}`)
|
|
1985
2017
|
}
|
|
1986
2018
|
}
|
|
1987
2019
|
if (record?.attempt !== undefined && (!record.runId || !runId || record.runId === runId)) {
|
|
@@ -2007,8 +2039,9 @@ export function apply(ctx, config) {
|
|
|
2007
2039
|
rootAgents.set(agent.id, agent)
|
|
2008
2040
|
sessionToRootAgent.set(agent.session, agent)
|
|
2009
2041
|
todoTracker.bind(agent)
|
|
2042
|
+
sessionTools.restoreMainRoute(agent)
|
|
2010
2043
|
switchNotices.observe(agent.id)
|
|
2011
|
-
if (!dispatchEnabled()) return
|
|
2044
|
+
if (!dispatchEnabled(agent)) return
|
|
2012
2045
|
ctx.logger.info(
|
|
2013
2046
|
`orchestrator: main agent ${agent.id}: armed whitelist gate (${gate.allowed.length} allowed: [${gate.allowed.join(', ')}])`,
|
|
2014
2047
|
)
|
|
@@ -2044,7 +2077,7 @@ export function apply(ctx, config) {
|
|
|
2044
2077
|
return resumeFromHost(agent, agent.id, runId, agent.session?.header?.parentSession)
|
|
2045
2078
|
.catch((error) => warn(`恢复子代理 ${agent.id} 失败:${messageOf(error)}`))
|
|
2046
2079
|
})
|
|
2047
|
-
listen('agent/created', (payload) => {
|
|
2080
|
+
listen('agent/created', async (payload) => {
|
|
2048
2081
|
if (disposing) return
|
|
2049
2082
|
const agent = payload?.agent
|
|
2050
2083
|
// A new root agent is the only place a preset or scope-local tool becomes visible,
|
|
@@ -2061,7 +2094,9 @@ export function apply(ctx, config) {
|
|
|
2061
2094
|
return
|
|
2062
2095
|
}
|
|
2063
2096
|
|
|
2064
|
-
// The
|
|
2097
|
+
// The persisted model must be installed before the first prepared step.
|
|
2098
|
+
if (hasStorage) await sessionTools.ready
|
|
2099
|
+
if (disposing) return
|
|
2065
2100
|
registerRootAgent(agent)
|
|
2066
2101
|
// A resumed agent with a parentSession that still read as a main agent means the
|
|
2067
2102
|
// depth test degraded: the cold-resume regression looked exactly like this.
|
|
@@ -2072,11 +2107,16 @@ export function apply(ctx, config) {
|
|
|
2072
2107
|
}
|
|
2073
2108
|
})
|
|
2074
2109
|
|
|
2075
|
-
|
|
2076
|
-
|
|
2077
|
-
|
|
2078
|
-
|
|
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
|
+
}
|
|
2079
2117
|
}
|
|
2118
|
+
if (hasStorage) background(sessionTools.ready.then(registerExistingRoots))
|
|
2119
|
+
else registerExistingRoots()
|
|
2080
2120
|
|
|
2081
2121
|
// A gated agent that goes away takes its guard with it: the entry is the only owner of
|
|
2082
2122
|
// the disposer, so dropping it here must not leave a predicate behind.
|
|
@@ -2115,12 +2155,27 @@ export function apply(ctx, config) {
|
|
|
2115
2155
|
* the model what changed. Nothing is delivered now: a notice at this moment would splice
|
|
2116
2156
|
* into a turn the user is still reading.
|
|
2117
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
|
+
|
|
2118
2170
|
listen('loader/volatile-update', () => {
|
|
2119
2171
|
// Restore it before the write's own settings read answers, so the panel never falls
|
|
2120
2172
|
// back to its built-in copy after a checkbox click.
|
|
2121
2173
|
catalog.publish()
|
|
2122
2174
|
for (const id of gates.keys()) switchNotices.observe(id)
|
|
2123
|
-
|
|
2175
|
+
refreshSupervision()
|
|
2176
|
+
syncInheritedMainRoutes()
|
|
2177
|
+
}, { global: true })
|
|
2178
|
+
listen('settings/document-updated', syncInheritedMainRoutes, { global: true })
|
|
2124
2179
|
|
|
2125
2180
|
/**
|
|
2126
2181
|
* Deliver a recorded switch change at the start of the agent's next real model step.
|
|
@@ -2155,22 +2210,52 @@ export function apply(ctx, config) {
|
|
|
2155
2210
|
supervisor: supervision.supervisor,
|
|
2156
2211
|
rebuildNotice: supervision.rebuildNotice,
|
|
2157
2212
|
liveNoticeIds: supervision.liveNoticeIds,
|
|
2158
|
-
auditTimeline: timeline,
|
|
2159
|
-
loadAuditCreator: supervision.loadAuditCreator,
|
|
2160
|
-
scheduleReconcileInbox: supervision.scheduleReconcileInbox,
|
|
2161
2213
|
retainNotices: supervision.retainNotices,
|
|
2162
2214
|
supervisionTurnState,
|
|
2163
2215
|
todoTracker,
|
|
2164
2216
|
nextStep: createSwitchPreStep({ switchNotices, logger: ctx.logger, supervisionTurnState }),
|
|
2165
2217
|
})
|
|
2218
|
+
const loadPeerMessage = createUserMessageLoader({
|
|
2219
|
+
logger: ctx.logger,
|
|
2220
|
+
scope: 'peer read-only consult',
|
|
2221
|
+
disabledReason: 'peer context injection is disabled',
|
|
2222
|
+
})
|
|
2166
2223
|
listen('agent/pre-step', async (payload, next) => {
|
|
2224
|
+
if (hasStorage) await sessionTools.ready
|
|
2167
2225
|
if (restoring) await readyPromise
|
|
2168
2226
|
if (disposing) return next()
|
|
2169
|
-
const
|
|
2170
|
-
|
|
2171
|
-
|
|
2172
|
-
|
|
2173
|
-
|
|
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
|
+
}
|
|
2174
2259
|
}
|
|
2175
2260
|
}
|
|
2176
2261
|
}
|
|
@@ -2183,6 +2268,7 @@ export function apply(ctx, config) {
|
|
|
2183
2268
|
await domainReservation.previous
|
|
2184
2269
|
if (disposing) return
|
|
2185
2270
|
await stateStore.open()
|
|
2271
|
+
await sessionTools.ready
|
|
2186
2272
|
if (disposing) return
|
|
2187
2273
|
if (stateStore.hasUnsafeState()) startupError ??= new Error('存储域无法完整读取;原始数据已保留')
|
|
2188
2274
|
const snapshot = stateStore.getSnapshot()
|
|
@@ -2190,7 +2276,7 @@ export function apply(ctx, config) {
|
|
|
2190
2276
|
const tree = row.worktreeId && worktrees.get(row.worktreeId)
|
|
2191
2277
|
const leaseState = row.leaseState ?? (!row.leaseId ? 'none'
|
|
2192
2278
|
: writeLeases.get(row.leaseId) ? 'held' : startupError ? 'unknown' : 'released')
|
|
2193
|
-
return { ...row, leaseState, ...(tree && { worktree: { ...tree,
|
|
2279
|
+
return { ...row, leaseState, ...(tree && { worktree: { ...tree, locked: tree.locked } }) }
|
|
2194
2280
|
}
|
|
2195
2281
|
await reconcileOnStartup({
|
|
2196
2282
|
snapshot, store: stateStore, worktrees, leases: writeLeases, timeline, retry, actionLedger,
|
|
@@ -2210,8 +2296,9 @@ export function apply(ctx, config) {
|
|
|
2210
2296
|
async onDelegateReconciled(row) {
|
|
2211
2297
|
const tree = row.worktreeId && worktrees.get(row.worktreeId)
|
|
2212
2298
|
if (tree?.state !== 'active' || stateStore.listDelegates().some((other) =>
|
|
2213
|
-
other.worktreeId === tree.id && other.childId !== row.childId &&
|
|
2214
|
-
|
|
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)
|
|
2215
2302
|
await putTree(tree.id)
|
|
2216
2303
|
for (const childId of tree.childIds) timeline.recordWorktreeState(childId, {
|
|
2217
2304
|
id: tree.id, parentId: tree.parentId, state: review?.state,
|
|
@@ -2241,8 +2328,12 @@ export function apply(ctx, config) {
|
|
|
2241
2328
|
disposing = true
|
|
2242
2329
|
if (!legacyEffects) stopTimer()
|
|
2243
2330
|
startupAbort.abort()
|
|
2244
|
-
const closing =
|
|
2245
|
-
|
|
2331
|
+
const closing = Promise.all([
|
|
2332
|
+
stateStore.close().catch((error) => warn(`关闭存储域失败:${messageOf(error)}`)),
|
|
2333
|
+
sessionToolsRemote.dispose().catch((error) => warn(`卸载会话 Remote 失败:${messageOf(error)}`)),
|
|
2334
|
+
sessionTools.close().catch((error) => warn(`关闭会话存储域失败:${messageOf(error)}`)),
|
|
2335
|
+
])
|
|
2336
|
+
disposePromise = closing.finally(() => {
|
|
2246
2337
|
try {
|
|
2247
2338
|
clean(listenerDisposers)
|
|
2248
2339
|
for (const cursor of supervision.supervisor.exportCursors()) supervision.supervisor.forget(cursor.childId)
|