@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/README.md +44 -23
- package/README.zh.md +42 -22
- package/lib/client.js +657 -384
- package/lib/delegate-status.js +42 -67
- package/lib/delegate.js +69 -127
- package/lib/gate.js +9 -3
- package/lib/index.js +500 -432
- package/lib/orchestrate.js +91 -109
- package/lib/read-index.js +186 -0
- package/lib/reconcile.js +2 -3
- package/lib/rules.js +11 -10
- package/lib/session-tools.js +194 -22
- 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 +33 -7
- 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/orchestrate.js
CHANGED
|
@@ -10,21 +10,21 @@
|
|
|
10
10
|
* one, `outputSchema`.
|
|
11
11
|
*
|
|
12
12
|
* A writable batch declares one top-level `writeScope`. In Git isolation each item
|
|
13
|
-
* owns a checkout
|
|
14
|
-
* atomic batch lease
|
|
13
|
+
* owns a checkout and lease across all its stages. Shared mode preserves the
|
|
14
|
+
* atomic batch lease; a conflict starts no workers.
|
|
15
15
|
*/
|
|
16
16
|
|
|
17
17
|
import { randomUUID } from 'node:crypto'
|
|
18
18
|
import { DELIVERY, LIMITS, ORCHESTRATE_TOOL, ORCHESTRATION_KIND, disabledToolMessage } from './api.js'
|
|
19
19
|
import {
|
|
20
|
-
READ_ONLY_NOTICE, TEAM_TASK_ID_PARAMETER,
|
|
21
|
-
dispatchWriteParameters, parseTeamTaskId, prepareDispatchWrite,
|
|
22
|
-
validateDispatchIsolation, validateDispatchWrite,
|
|
20
|
+
READ_ONLY_NOTICE, TEAM_TASK_ID_PARAMETER, discardEmptyWorktree, dispatchWorkspaceRoot,
|
|
21
|
+
dispatchWriteParameters, parseTeamTaskId, prepareDispatchWrite,
|
|
22
|
+
validateDispatchIsolation, validateDispatchWrite, worktreeDetails,
|
|
23
23
|
worktreeFailure, worktreePromptNote,
|
|
24
24
|
} from './delegate.js'
|
|
25
25
|
import { teamTaskPromptNote } from './rules.js'
|
|
26
26
|
import { assertObjectSchema, isJsonValue, validateJsonSchemaValue } from './schema.js'
|
|
27
|
-
import { buildSpawnActivation, isDispatchEnabled, readRoute, readRouteOverride } from './worker.js'
|
|
27
|
+
import { buildSpawnActivation, configValue, isDispatchEnabled, readRoute, readRouteOverride } from './worker.js'
|
|
28
28
|
import { probeGitRepo } from './worktree.js'
|
|
29
29
|
import { dispatchCwd, formatWorktreeError, releaseWriteScope, writeScopeNotice } from './write-scope-tool.js'
|
|
30
30
|
|
|
@@ -54,8 +54,6 @@ const ARGUMENT_KEYS = Object.freeze([
|
|
|
54
54
|
'writeScope',
|
|
55
55
|
'readOnly',
|
|
56
56
|
'isolation',
|
|
57
|
-
'expectedFingerprints',
|
|
58
|
-
'expectedTargets',
|
|
59
57
|
])
|
|
60
58
|
const STAGE_KEYS = Object.freeze(['name', 'prompt', 'schema', 'provider', 'model', 'reasoning_effort'])
|
|
61
59
|
|
|
@@ -157,7 +155,6 @@ export function buildStagePrompt({
|
|
|
157
155
|
previous,
|
|
158
156
|
writeScope,
|
|
159
157
|
readOnly,
|
|
160
|
-
baselineId,
|
|
161
158
|
worktree,
|
|
162
159
|
teamTaskId,
|
|
163
160
|
}) {
|
|
@@ -193,7 +190,6 @@ export function buildStagePrompt({
|
|
|
193
190
|
// declaration, so the constraint always travels with the prompt.
|
|
194
191
|
lines.push('')
|
|
195
192
|
lines.push(readOnly ? READ_ONLY_NOTICE : writeScopeNotice(writeScope))
|
|
196
|
-
if (baselineId !== undefined) lines.push(`写后审计基线:${baselineId}。`)
|
|
197
193
|
if (worktree) lines.push('', worktreePromptNote(worktree))
|
|
198
194
|
if (teamTaskId !== undefined) lines.push('', teamTaskPromptNote(teamTaskId))
|
|
199
195
|
return lines.join('\n')
|
|
@@ -330,10 +326,10 @@ export async function runOrchestration({
|
|
|
330
326
|
subagents,
|
|
331
327
|
signal,
|
|
332
328
|
writeScope,
|
|
333
|
-
baselineId,
|
|
334
329
|
itemIsolation,
|
|
335
330
|
stageTracking,
|
|
336
331
|
sharedBatch,
|
|
332
|
+
sharedStarts,
|
|
337
333
|
}) {
|
|
338
334
|
const { cwd, items, stages, maxConcurrency, readOnly, teamTaskId } = plan
|
|
339
335
|
const limiter = createLimiter(maxConcurrency)
|
|
@@ -370,6 +366,13 @@ export async function runOrchestration({
|
|
|
370
366
|
return pending
|
|
371
367
|
}
|
|
372
368
|
|
|
369
|
+
const settleStage = async (batch, handle, result) => {
|
|
370
|
+
await dispose(handle)
|
|
371
|
+
if (batch && handle?.childId) {
|
|
372
|
+
await stageTracking.stageEnded(batch, handle, result ?? { stopReason: signal.aborted ? 'aborted' : 'error' })
|
|
373
|
+
}
|
|
374
|
+
}
|
|
375
|
+
|
|
373
376
|
const onAbort = () => {
|
|
374
377
|
for (const handle of active) void dispose(handle)
|
|
375
378
|
}
|
|
@@ -424,38 +427,38 @@ export async function runOrchestration({
|
|
|
424
427
|
(handle) => ({ handle }),
|
|
425
428
|
(error) => ({ error }),
|
|
426
429
|
)
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
if (signal.aborted) onAbort()
|
|
446
|
-
else signal.addEventListener('abort', onAbort, { once: true })
|
|
447
|
-
settledStart.then((outcome) => {
|
|
448
|
-
signal.removeEventListener('abort', onAbort)
|
|
449
|
-
if (signal.aborted) {
|
|
450
|
-
// Late handle: clean it up without dispatching its worker.
|
|
451
|
-
if (outcome.handle !== undefined) void dispose(outcome.handle)
|
|
452
|
-
reject(abortReason(signal))
|
|
453
|
-
return
|
|
430
|
+
let acceptStart
|
|
431
|
+
let rejectStart
|
|
432
|
+
const receipt = new Promise((resolve, reject) => {
|
|
433
|
+
acceptStart = resolve
|
|
434
|
+
rejectStart = reject
|
|
435
|
+
})
|
|
436
|
+
const cancelStart = () => rejectStart(abortReason(signal))
|
|
437
|
+
signal.addEventListener('abort', cancelStart, { once: true })
|
|
438
|
+
if (signal.aborted) cancelStart()
|
|
439
|
+
// Keep both item and shared leases until late receipts are disposed and recorded.
|
|
440
|
+
const pending = settledStart.then(async (outcome) => {
|
|
441
|
+
const { handle } = outcome
|
|
442
|
+
signal.removeEventListener('abort', cancelStart)
|
|
443
|
+
try {
|
|
444
|
+
if (workspace && handle && typeof handle === 'object') {
|
|
445
|
+
workspace.started ||= (typeof handle.childId === 'string' && handle.childId.length > 0) ||
|
|
446
|
+
typeof handle.result?.then === 'function'
|
|
447
|
+
if (workspace.started) itemIsolation.bind(workspace, handle)
|
|
454
448
|
}
|
|
455
|
-
if (
|
|
456
|
-
else
|
|
457
|
-
|
|
449
|
+
if (signal.aborted) await settleStage(batch, handle)
|
|
450
|
+
else if (Object.hasOwn(outcome, 'error')) rejectStart(outcome.error)
|
|
451
|
+
else acceptStart(handle)
|
|
452
|
+
} catch (error) {
|
|
453
|
+
rejectStart(error)
|
|
454
|
+
if (!signal.aborted) await settleStage(batch, handle)
|
|
455
|
+
else throw error
|
|
456
|
+
}
|
|
458
457
|
})
|
|
458
|
+
const pendingStarts = workspace?.pendingStarts ?? sharedStarts
|
|
459
|
+
pendingStarts?.add(pending)
|
|
460
|
+
void pending.finally(() => pendingStarts?.delete(pending)).catch(() => {})
|
|
461
|
+
started = await receipt
|
|
459
462
|
if (
|
|
460
463
|
started === null ||
|
|
461
464
|
typeof started !== 'object' ||
|
|
@@ -491,8 +494,7 @@ export async function runOrchestration({
|
|
|
491
494
|
try {
|
|
492
495
|
if (started !== undefined) {
|
|
493
496
|
active.delete(started)
|
|
494
|
-
await
|
|
495
|
-
if (batch && result) await stageTracking.stageEnded(batch, started, result)
|
|
497
|
+
await settleStage(batch, started, result)
|
|
496
498
|
}
|
|
497
499
|
} finally {
|
|
498
500
|
if (acquired) limiter.release()
|
|
@@ -527,7 +529,6 @@ export async function runOrchestration({
|
|
|
527
529
|
previous,
|
|
528
530
|
writeScope: workspace?.write.writeScope ?? writeScope,
|
|
529
531
|
readOnly,
|
|
530
|
-
baselineId: workspace?.write.baseline?.baselineId ?? baselineId,
|
|
531
532
|
worktree: workspace?.worktree,
|
|
532
533
|
teamTaskId,
|
|
533
534
|
})
|
|
@@ -543,9 +544,10 @@ export async function runOrchestration({
|
|
|
543
544
|
try {
|
|
544
545
|
if (workspace) {
|
|
545
546
|
const finish = () => itemIsolation.finish(workspace, index)
|
|
546
|
-
|
|
547
|
+
const pending = [...workspace.pendingStarts]
|
|
548
|
+
if (pending.length && signal.aborted) itemIsolation.defer(Promise.all(pending), finish)
|
|
547
549
|
else {
|
|
548
|
-
await
|
|
550
|
+
await Promise.all(pending)
|
|
549
551
|
await finish()
|
|
550
552
|
}
|
|
551
553
|
}
|
|
@@ -602,7 +604,7 @@ const newBatch = (batchId, parent, write) => ({
|
|
|
602
604
|
|
|
603
605
|
function prepareItemIsolation({
|
|
604
606
|
isolation, worktrees, args, exec, parent, checked, leases, batchId, probeRepo, getWorkspaceRoot,
|
|
605
|
-
|
|
607
|
+
onWorktreeChild, onCleanupFailed, stageTracking,
|
|
606
608
|
}) {
|
|
607
609
|
const sourceCwd = dispatchCwd(args, exec)
|
|
608
610
|
const workspaceRoot = dispatchWorkspaceRoot(exec, getWorkspaceRoot)
|
|
@@ -644,10 +646,10 @@ function prepareItemIsolation({
|
|
|
644
646
|
try {
|
|
645
647
|
const write = prepareDispatchWrite({
|
|
646
648
|
args, exec, parent, leases, childId: `${batchId}:item:${index}`, tool: ORCHESTRATE_TOOL,
|
|
647
|
-
checked, worktree,
|
|
649
|
+
checked, worktree,
|
|
648
650
|
})
|
|
649
651
|
const batch = stageTracking ? newBatch(batchId, parent, write) : undefined
|
|
650
|
-
return { worktree, write, batch, started: false }
|
|
652
|
+
return { worktree, write, batch, started: false, pendingStarts: new Set() }
|
|
651
653
|
} catch (error) {
|
|
652
654
|
discardEmptyWorktree(worktrees, worktree, onCleanupFailed)
|
|
653
655
|
throw error
|
|
@@ -662,64 +664,49 @@ function prepareItemIsolation({
|
|
|
662
664
|
},
|
|
663
665
|
async finish({ worktree, write, started, batch }, itemIndex) {
|
|
664
666
|
if (stageTracking?.isDisposing() || (batch && !stageTracking.canFinishBatch(batch))) return
|
|
665
|
-
let audit
|
|
666
667
|
try {
|
|
667
668
|
if (!started) {
|
|
668
669
|
discardEmptyWorktree(worktrees, worktree, onCleanupFailed)
|
|
669
670
|
return
|
|
670
671
|
}
|
|
671
|
-
|
|
672
|
-
worktrees.markReadyForReview(worktree.id, worktreeAuditSummary(audit))
|
|
672
|
+
worktrees.markReadyForReview(worktree.id)
|
|
673
673
|
const { id: worktreeId, branch, path } = worktreeDetails(worktree)
|
|
674
|
-
rows.push({ itemIndex, worktreeId, branch, path,
|
|
675
|
-
onAudited?.({ childId: `${batchId}:item:${itemIndex}`, parentId: parent.id, audit, itemIndex, worktree })
|
|
674
|
+
rows.push({ itemIndex, worktreeId, branch, path, state: "ready_for_review" })
|
|
676
675
|
} finally {
|
|
677
|
-
if (batch) await stageTracking.finishBatch(batch
|
|
676
|
+
if (batch) await stageTracking.finishBatch(batch)
|
|
678
677
|
else releaseWriteScope(leases, write.lease)
|
|
679
678
|
}
|
|
680
679
|
},
|
|
681
680
|
defer(pending, finish) {
|
|
682
|
-
void pending.
|
|
681
|
+
void pending.then(finish).catch((error) => onCleanupFailed?.(error))
|
|
683
682
|
},
|
|
684
683
|
},
|
|
685
684
|
}
|
|
686
685
|
}
|
|
687
686
|
|
|
688
|
-
function aggregateItemAudits(rows) {
|
|
689
|
-
const summary = { added: 0, modified: 0, deleted: 0, violations: 0, truncated: false }
|
|
690
|
-
const changedFiles = []
|
|
691
|
-
const violations = []
|
|
692
|
-
for (const { itemIndex, audit } of rows) {
|
|
693
|
-
for (const key of ['added', 'modified', 'deleted', 'violations']) summary[key] += audit.summary[key]
|
|
694
|
-
summary.truncated ||= audit.summary.truncated === true
|
|
695
|
-
changedFiles.push(...audit.changedFiles.map((entry) => ({ ...entry, itemIndex })))
|
|
696
|
-
violations.push(...audit.violations.map((entry) => ({ ...entry, path: `item ${itemIndex + 1}: ${entry.path}`, itemIndex })))
|
|
697
|
-
}
|
|
698
|
-
return {
|
|
699
|
-
passed: rows.every(({ audit }) => audit.passed), readOnly: false, isolationLevel: 'git-worktree',
|
|
700
|
-
isolationNote: '每个条目独立完成 Git 审计;具体证据见 details.itemAudits。',
|
|
701
|
-
changedFiles, violations, summary,
|
|
702
|
-
}
|
|
703
|
-
}
|
|
704
687
|
|
|
705
688
|
export function createOrchestrateTool({
|
|
706
|
-
defineTool, subagents, config, leases,
|
|
707
|
-
isWorktreeEnabled = () => true, getWorkspaceRoot,
|
|
708
|
-
|
|
689
|
+
defineTool, subagents, config, leases, worktrees, onWorktreeChild, onCleanupFailed,
|
|
690
|
+
isWorktreeEnabled = () => true, resolveSessionConfig, getWorkspaceRoot,
|
|
691
|
+
probeGitRepo: probeRepo = probeGitRepo,
|
|
709
692
|
stageTracking,
|
|
710
693
|
}) {
|
|
711
694
|
// This description does not repeat `mainAgentRule`: only `delegate` opens with it.
|
|
712
695
|
// The plumbing still accepts the whitelist fields a shared factory passes down so a
|
|
713
696
|
// caller does not have to branch, but they are unused here.
|
|
714
|
-
const
|
|
697
|
+
const globalReadOnly = () => configValue(config, 'readOnlyEnabled', false) === true
|
|
715
698
|
const ruleLead = '主代理规则同 delegate。'
|
|
716
|
-
const body =
|
|
699
|
+
const body = (readOnlyEnabled) =>
|
|
717
700
|
'按 item 派发子代理:单 stage 即批量扇出;多 stage 时各 item 独立走完阶段,无全局屏障,每阶段自动附带指令、原始 item 与上阶段输出。' +
|
|
718
701
|
'声明 schema 的阶段输出校验过的 JSON,否则为文本;单 item 失败置为 null 并记入 errors。' +
|
|
719
|
-
'maxConcurrency
|
|
720
|
-
'
|
|
702
|
+
'maxConcurrency 限制并发数;' + (readOnlyEnabled ? '非只读调用' : '调用') +
|
|
703
|
+
'必填 writeScope。Git 写任务默认按 item 分配独立 Worktree,同 item 多 stage 复用一树,结算后保留,由 worktree_manage 评审、合回或丢弃。' +
|
|
704
|
+
'非 Git 自动降级:共享模式整批共享一个写租约,冲突时整批失败不排队。' +
|
|
705
|
+
(readOnlyEnabled ? 'readOnly: true 不占租约,宿主不提供逐子代理物理只读隔离。' : '') +
|
|
721
706
|
'无关批次可并发调用;单任务请用 delegate。'
|
|
722
|
-
const
|
|
707
|
+
const describeFor = (_allowed, { enabled = isDispatchEnabled(config), readOnlyEnabled = globalReadOnly() } = {}) =>
|
|
708
|
+
(enabled ? ruleLead : '') + body(readOnlyEnabled)
|
|
709
|
+
const descriptionOf = () => describeFor()
|
|
723
710
|
|
|
724
711
|
const tool = defineTool({
|
|
725
712
|
name: ORCHESTRATE_TOOL,
|
|
@@ -807,7 +794,6 @@ export function createOrchestrateTool({
|
|
|
807
794
|
properties: {
|
|
808
795
|
kind: { type: 'string', const: ORCHESTRATION_KIND },
|
|
809
796
|
agentsStarted: { type: 'integer' },
|
|
810
|
-
audit: { type: 'object', additionalProperties: true },
|
|
811
797
|
details: { type: 'object', additionalProperties: true },
|
|
812
798
|
results: {
|
|
813
799
|
type: 'array',
|
|
@@ -846,10 +832,9 @@ export function createOrchestrateTool({
|
|
|
846
832
|
text:
|
|
847
833
|
`orchestration finished: ${value.results.filter((entry) => entry !== null).length}/${value.results.length} items, ` +
|
|
848
834
|
`${value.errors.length} errors, ${value.agentsStarted} workers started` +
|
|
849
|
-
(value.audit?.passed === false ? `\n不得验收为通过。\n${auditNotice(value.audit)}` : '') +
|
|
850
835
|
(value.details?.worktrees?.length
|
|
851
836
|
? '\n请用 worktree_manage 逐项 inspect / merge / discard:\n' + value.details.worktrees.map((worktree) =>
|
|
852
|
-
`item ${worktree.itemIndex + 1}:${worktree.worktreeId}(${worktree.branch}
|
|
837
|
+
`item ${worktree.itemIndex + 1}:${worktree.worktreeId}(${worktree.branch})`).join('\n')
|
|
853
838
|
: '') +
|
|
854
839
|
(value.details?.isolationFallback ? `\n已降级为共享工作区:${value.details.isolationFallback.message}` : ''),
|
|
855
840
|
},
|
|
@@ -857,11 +842,12 @@ export function createOrchestrateTool({
|
|
|
857
842
|
},
|
|
858
843
|
isConcurrencySafe: () => true,
|
|
859
844
|
async execute(args, exec) {
|
|
860
|
-
if (!enabled()) throw new Error(disabledToolMessage(ORCHESTRATE_TOOL))
|
|
861
845
|
const parent = exec?.agent
|
|
846
|
+
const effective = resolveSessionConfig?.(parent)
|
|
847
|
+
if (!(effective?.enabled ?? isDispatchEnabled(config))) throw new Error(disabledToolMessage(ORCHESTRATE_TOOL))
|
|
862
848
|
if (!parent) throw new Error('orchestrate requires a calling agent (exec.agent was undefined)')
|
|
849
|
+
const checked = validateDispatchWrite(args, ORCHESTRATE_TOOL, effective?.readOnlyEnabled ?? globalReadOnly())
|
|
863
850
|
const isolation = validateDispatchIsolation(args)
|
|
864
|
-
const checked = validateDispatchWrite(args, ORCHESTRATE_TOOL)
|
|
865
851
|
// Even if every stage overrides it, reject an invalid batch override.
|
|
866
852
|
const batchRoute = readRouteOverride(args, ORCHESTRATE_TOOL)
|
|
867
853
|
const plan = parseOrchestrateArgs(args)
|
|
@@ -872,17 +858,17 @@ export function createOrchestrateTool({
|
|
|
872
858
|
signal.throwIfAborted()
|
|
873
859
|
// Read the panel route only when needed, before acquiring any lease or Worktree.
|
|
874
860
|
const defaultRoute = batchRoute === undefined && plan.stages.some((stage) => stage.route === undefined)
|
|
875
|
-
? readRoute(config)
|
|
861
|
+
? effective?.workerRoute ?? readRoute(config)
|
|
876
862
|
: undefined
|
|
877
863
|
const maxDepth = subagents.resolveMaxDepth(undefined)
|
|
878
864
|
signal.throwIfAborted()
|
|
879
865
|
const childId = nextBatchId(parent)
|
|
880
866
|
let isolationFallback
|
|
881
867
|
if (!checked.readOnly && (isolation.mode === 'worktree' ||
|
|
882
|
-
(isolation.mode === 'auto' && worktrees && isWorktreeEnabled()))) {
|
|
868
|
+
(isolation.mode === 'auto' && worktrees && (effective?.worktreeIsolationEnabled ?? isWorktreeEnabled(parent))))) {
|
|
883
869
|
const isolated = prepareItemIsolation({
|
|
884
870
|
isolation, worktrees, args, exec, parent, checked, leases, batchId: childId, probeRepo, getWorkspaceRoot,
|
|
885
|
-
|
|
871
|
+
onWorktreeChild, onCleanupFailed, stageTracking,
|
|
886
872
|
})
|
|
887
873
|
if (isolated.itemIsolation) {
|
|
888
874
|
try {
|
|
@@ -891,14 +877,10 @@ export function createOrchestrateTool({
|
|
|
891
877
|
itemIsolation: isolated.itemIsolation, stageTracking,
|
|
892
878
|
})
|
|
893
879
|
const rows = isolated.rows.sort((left, right) => left.itemIndex - right.itemIndex)
|
|
894
|
-
const audit = rows.length === 0 ? undefined : aggregateItemAudits(rows)
|
|
895
880
|
return {
|
|
896
881
|
...result,
|
|
897
|
-
...(audit && { audit }),
|
|
898
882
|
details: {
|
|
899
883
|
worktrees: rows,
|
|
900
|
-
itemAudits: rows.map(({ itemIndex, worktreeId, audit }) => ({ itemIndex, worktreeId, audit })),
|
|
901
|
-
...(audit && { writeAudit: audit }),
|
|
902
884
|
},
|
|
903
885
|
}
|
|
904
886
|
} finally {
|
|
@@ -907,11 +889,16 @@ export function createOrchestrateTool({
|
|
|
907
889
|
}
|
|
908
890
|
isolationFallback = isolated.isolationFallback
|
|
909
891
|
}
|
|
910
|
-
// Shared mode keeps the atomic batch lease and one
|
|
892
|
+
// Shared mode keeps the atomic batch lease and one owner across all stages.
|
|
911
893
|
const write = prepareDispatchWrite({ args, exec, parent, leases, childId, tool: ORCHESTRATE_TOOL, checked })
|
|
912
894
|
const sharedBatch = stageTracking ? newBatch(childId, parent, write) : undefined
|
|
895
|
+
const sharedStarts = new Set()
|
|
896
|
+
const finish = async () => {
|
|
897
|
+
if (stageTracking?.isDisposing()) return
|
|
898
|
+
if (!sharedBatch) releaseWriteScope(leases, write.lease)
|
|
899
|
+
else if (stageTracking.canFinishBatch(sharedBatch)) await stageTracking.finishBatch(sharedBatch)
|
|
900
|
+
}
|
|
913
901
|
let result
|
|
914
|
-
let audit
|
|
915
902
|
try {
|
|
916
903
|
if (sharedBatch) await stageTracking.beforeLaunch(write)
|
|
917
904
|
result = await runOrchestration({
|
|
@@ -923,35 +910,30 @@ export function createOrchestrateTool({
|
|
|
923
910
|
subagents,
|
|
924
911
|
signal,
|
|
925
912
|
writeScope: write.lease?.scope,
|
|
926
|
-
baselineId: write.baseline?.baselineId,
|
|
927
913
|
stageTracking,
|
|
928
914
|
sharedBatch,
|
|
915
|
+
sharedStarts,
|
|
929
916
|
})
|
|
930
917
|
} finally {
|
|
931
|
-
|
|
932
|
-
|
|
933
|
-
|
|
934
|
-
|
|
935
|
-
|
|
936
|
-
|
|
937
|
-
if (sharedBatch) await stageTracking.finishBatch(sharedBatch, audit)
|
|
938
|
-
else releaseWriteScope(leases, write.lease)
|
|
939
|
-
}
|
|
918
|
+
const pending = [...sharedStarts]
|
|
919
|
+
if (pending.length && signal.aborted) {
|
|
920
|
+
void Promise.all(pending).then(finish).catch((error) => onCleanupFailed?.(error))
|
|
921
|
+
} else {
|
|
922
|
+
await Promise.all(pending)
|
|
923
|
+
await finish()
|
|
940
924
|
}
|
|
941
925
|
}
|
|
942
926
|
return {
|
|
943
927
|
...result,
|
|
944
|
-
...(audit && { audit }),
|
|
945
928
|
...(isolationFallback && { details: { isolationFallback } }),
|
|
946
929
|
}
|
|
947
930
|
},
|
|
948
931
|
})
|
|
949
932
|
// The host reads `description` while it builds a request; keep it a live getter for the
|
|
950
933
|
// same reason as `delegate`, even though this text no longer depends on the whitelist.
|
|
951
|
-
Object.
|
|
952
|
-
enumerable: true,
|
|
953
|
-
|
|
954
|
-
get: descriptionOf,
|
|
934
|
+
Object.defineProperties(tool, {
|
|
935
|
+
description: { enumerable: true, configurable: true, get: descriptionOf },
|
|
936
|
+
describeFor: { value: describeFor },
|
|
955
937
|
})
|
|
956
938
|
return tool
|
|
957
939
|
}
|
|
@@ -0,0 +1,186 @@
|
|
|
1
|
+
import { isDelegatedChild } from './gate.js'
|
|
2
|
+
|
|
3
|
+
const READ_TOOLS = new Map([
|
|
4
|
+
['read', 'read'], ['ops_inspect_local_file', 'read'],
|
|
5
|
+
['glob', 'glob'], ['ops_glob', 'glob'],
|
|
6
|
+
['grep', 'grep'], ['ops_grep', 'grep'],
|
|
7
|
+
])
|
|
8
|
+
const MAX_CHILDREN = 128
|
|
9
|
+
const MAX_CALLS = 1024
|
|
10
|
+
const MAX_ENTRIES = 20
|
|
11
|
+
const MAX_PEERS_SHOWN = 5
|
|
12
|
+
const MAX_ROWS_SHOWN = 5
|
|
13
|
+
const ANSWER_PREFIX = '【平级只读咨询答复】'
|
|
14
|
+
export const PEER_CONSULT_SOURCE_KIND = 'orchestrator-peer-read-only-consult'
|
|
15
|
+
|
|
16
|
+
function remember(map, key, value, limit) {
|
|
17
|
+
map.delete(key)
|
|
18
|
+
map.set(key, value)
|
|
19
|
+
if (map.size > limit) map.delete(map.keys().next().value)
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
function compact(value, limit = 220) {
|
|
23
|
+
return typeof value === 'string' ? value.replace(/[\x00-\x1f\x7f\u2028\u2029]/g, ' ').trim().slice(0, limit) : ''
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
function pathOf(value) {
|
|
27
|
+
return compact(typeof value === 'string' ? value : value?.path ?? value?.filePath ?? value?.file_path)
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
function positiveInteger(value) {
|
|
31
|
+
return Number.isSafeInteger(value) && value > 0 ? value : undefined
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
function readRows(kind, args, value) {
|
|
35
|
+
if (kind === 'read') {
|
|
36
|
+
const path = pathOf(value) || pathOf(args)
|
|
37
|
+
const lines = Array.isArray(value?.lines) ? value.lines : undefined
|
|
38
|
+
const from = positiveInteger(lines?.[0]?.number ?? value?.offset ?? value?.startLine ?? args.offset ?? args.start_line) ?? 1
|
|
39
|
+
const to = positiveInteger(lines?.at(-1)?.number ?? value?.endLine) ?? (lines?.length ? from + lines.length - 1 : undefined)
|
|
40
|
+
if (!path || lines?.length === 0) return []
|
|
41
|
+
return [{ path, detail: to === undefined ? `读取自第 ${from} 行` : `已读第 ${from}–${to} 行` }]
|
|
42
|
+
}
|
|
43
|
+
const matches = kind === 'glob' ? value?.paths ?? value?.items : value?.matches ?? value?.files ?? value?.items
|
|
44
|
+
if (!Array.isArray(matches)) return []
|
|
45
|
+
const rows = []
|
|
46
|
+
for (const match of matches.slice(0, MAX_ENTRIES)) {
|
|
47
|
+
const path = pathOf(match)
|
|
48
|
+
if (!path) continue
|
|
49
|
+
const line = positiveInteger(match?.lineNumber ?? match?.line_number ?? match?.line)
|
|
50
|
+
const detail = kind === 'glob' ? '路径匹配' : line === undefined ? '检索命中' : `第 ${line} 行命中`
|
|
51
|
+
rows.push({ path, detail })
|
|
52
|
+
}
|
|
53
|
+
return rows
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
function peerOf(left, right) {
|
|
57
|
+
return Boolean(left && right && left.id !== right.id &&
|
|
58
|
+
left.parentId === right.parentId && left.rootId === right.rootId)
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
function relaySender(message) {
|
|
62
|
+
const source = message?.source
|
|
63
|
+
return source?.kind === 'agent-message' && source.form === 'relay' ? source.senderSessionId : undefined
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
function isAnswer(message) {
|
|
67
|
+
// The host prepends its own sender banner as the first block.
|
|
68
|
+
const block = message.content?.[1]
|
|
69
|
+
return block?.type === 'text' && typeof block.text === 'string' && block.text.startsWith(ANSWER_PREFIX)
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/** Keep metadata only; file contents, search excerpts and agent messages are never indexed. */
|
|
73
|
+
export function createReadIndex({
|
|
74
|
+
enabledFor, getAgent, listAgents, rootIdOf, readOnlyOf, nameOf, resolvePeerTarget,
|
|
75
|
+
} = {}) {
|
|
76
|
+
const children = new Map()
|
|
77
|
+
const calls = new Map()
|
|
78
|
+
const receipts = new Map()
|
|
79
|
+
const shown = new WeakMap()
|
|
80
|
+
|
|
81
|
+
function identity(agent) {
|
|
82
|
+
if (!isDelegatedChild(agent) || typeof agent?.id !== 'string') return undefined
|
|
83
|
+
const parentId = agent.session?.header?.parentSession
|
|
84
|
+
const rootId = rootIdOf(agent)
|
|
85
|
+
if (typeof parentId !== 'string' || typeof rootId !== 'string') return undefined
|
|
86
|
+
const previous = children.get(agent.id)
|
|
87
|
+
const rows = previous?.rootId === rootId && previous.parentId === parentId ? previous.rows : new Map()
|
|
88
|
+
return {
|
|
89
|
+
id: agent.id, parentId, rootId,
|
|
90
|
+
name: compact(nameOf?.(agent), 120) || agent.id,
|
|
91
|
+
readOnly: readOnlyOf?.(agent) === true,
|
|
92
|
+
rows,
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
function enabled(agent) {
|
|
97
|
+
return enabledFor(rootIdOf(agent)) === true
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
function addReceipt(id, sender, target) {
|
|
101
|
+
if (typeof id === 'string' && id && peerOf(sender, target)) {
|
|
102
|
+
remember(receipts, id, { senderId: sender.id, rootId: sender.rootId }, MAX_CALLS)
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
async function observe(exec, result) {
|
|
107
|
+
const agent = exec?.agent
|
|
108
|
+
const kind = READ_TOOLS.get(exec?.name)
|
|
109
|
+
if ((!kind && exec?.name !== 'send_message') || !isDelegatedChild(agent) ||
|
|
110
|
+
!result || result.isError === true || !enabled(agent)) return
|
|
111
|
+
const child = identity(agent)
|
|
112
|
+
if (!child) return
|
|
113
|
+
const { callId } = exec
|
|
114
|
+
if (typeof callId !== 'string' || !callId) return
|
|
115
|
+
const callKey = JSON.stringify([child.id, callId])
|
|
116
|
+
if (calls.has(callKey)) return
|
|
117
|
+
remember(calls, callKey, true, MAX_CALLS)
|
|
118
|
+
remember(children, child.id, child, MAX_CHILDREN)
|
|
119
|
+
if (exec.name === 'send_message') {
|
|
120
|
+
const targetId = await resolvePeerTarget?.(exec)
|
|
121
|
+
addReceipt(result.value?.messageId, child, identity(getAgent?.(targetId)) ?? children.get(targetId))
|
|
122
|
+
return
|
|
123
|
+
}
|
|
124
|
+
for (const row of readRows(kind, exec.arguments ?? {}, result.value)) {
|
|
125
|
+
remember(child.rows, JSON.stringify([row.path, row.detail]), row, MAX_ENTRIES)
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
function peerSummary(agent, child) {
|
|
130
|
+
const peers = []
|
|
131
|
+
for (const live of listAgents?.() ?? []) {
|
|
132
|
+
const peer = children.get(live?.id)
|
|
133
|
+
if (peer?.rows.size && peerOf(child, peer) && peerOf(child, identity(live))) peers.push(peer)
|
|
134
|
+
}
|
|
135
|
+
const text = peers.slice(0, MAX_PEERS_SHOWN).map((peer) => {
|
|
136
|
+
const rows = [...peer.rows.values()].slice(-MAX_ROWS_SHOWN)
|
|
137
|
+
.map(({ path, detail }) => `${JSON.stringify(path)}(${detail})`).join('、')
|
|
138
|
+
return `- ${JSON.stringify(peer.name)}(ID ${JSON.stringify(peer.id)},${peer.readOnly ? '只读任务' : '含写任务'}):${rows}`
|
|
139
|
+
}).join('\n')
|
|
140
|
+
if (shown.get(agent) === text) return ''
|
|
141
|
+
if (!text) shown.delete(agent)
|
|
142
|
+
return text
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
function prepare(agent, messages) {
|
|
146
|
+
if (!agent || !enabled(agent)) {
|
|
147
|
+
if (agent) shown.delete(agent)
|
|
148
|
+
return { messages }
|
|
149
|
+
}
|
|
150
|
+
if (!isDelegatedChild(agent)) {
|
|
151
|
+
const rootId = rootIdOf(agent)
|
|
152
|
+
const filtered = messages.filter((message) => {
|
|
153
|
+
const sender = relaySender(message)
|
|
154
|
+
const receipt = sender && receipts.get(message.id)
|
|
155
|
+
return !(receipt?.rootId === rootId && receipt?.senderId === sender && !message.source.error && !message.error)
|
|
156
|
+
})
|
|
157
|
+
return { messages: filtered.length === messages.length ? messages : filtered }
|
|
158
|
+
}
|
|
159
|
+
const child = identity(agent)
|
|
160
|
+
if (!child || messages.length === 0) return { messages }
|
|
161
|
+
const askers = new Map()
|
|
162
|
+
for (const message of messages) {
|
|
163
|
+
const senderId = relaySender(message)
|
|
164
|
+
if (!senderId) continue
|
|
165
|
+
const sender = identity(getAgent?.(senderId)) ?? children.get(senderId)
|
|
166
|
+
if (!peerOf(child, sender)) continue
|
|
167
|
+
addReceipt(message.id, sender, child)
|
|
168
|
+
if (!isAnswer(message)) askers.set(sender.id, sender.name)
|
|
169
|
+
}
|
|
170
|
+
const summary = peerSummary(agent, child)
|
|
171
|
+
const parts = []
|
|
172
|
+
if (summary) {
|
|
173
|
+
parts.push('【平级已读索引】下列条目是路径和命中位置。可用 send_message 请对方概括其已读上下文,减少重复读取。\n' + summary)
|
|
174
|
+
}
|
|
175
|
+
for (const [id, name] of [...askers].slice(0, MAX_PEERS_SHOWN)) {
|
|
176
|
+
parts.push(`这是来自平级子代理 ${JSON.stringify(name)} 的只读上下文咨询。请仅基于已读事实简明回答,保持文件和主任务边界。用 send_message 向 ${JSON.stringify(id)} 回复,正文以 ${ANSWER_PREFIX} 开头,然后继续原任务。`)
|
|
177
|
+
}
|
|
178
|
+
return {
|
|
179
|
+
messages,
|
|
180
|
+
text: parts.join('\n'),
|
|
181
|
+
acknowledge: summary ? () => shown.set(agent, summary) : undefined,
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
return { observe, prepare }
|
|
186
|
+
}
|
package/lib/reconcile.js
CHANGED
|
@@ -485,7 +485,8 @@ export async function reconcileOnStartup({
|
|
|
485
485
|
if (isId(leaseId) && !expired.has(leaseId) && (knownLeaseIds.has(leaseId) || await leases?.get?.(leaseId))) {
|
|
486
486
|
childLeases.add(leaseId)
|
|
487
487
|
}
|
|
488
|
-
|
|
488
|
+
const activeCheckout = record.worktreeId && worktrees?.get?.(record.worktreeId)?.state === 'active'
|
|
489
|
+
if (TERMINAL_STATES.has(record.dispatchState) && childLeases.size === 0 && !activeCheckout) continue
|
|
489
490
|
|
|
490
491
|
const host = await inspect(childId, parentId, rootSessionId)
|
|
491
492
|
signal?.throwIfAborted?.()
|
|
@@ -531,8 +532,6 @@ export async function reconcileOnStartup({
|
|
|
531
532
|
const terminal = lost ? { dispatchState: 'lost', stopReason: 'lost' } : terminalState(host.lastTurnEndKind)
|
|
532
533
|
const outcome = lost ? 'lost' : terminal.dispatchState === 'interrupted' ? 'interrupted' : 'settled-offline'
|
|
533
534
|
const updated = { ...record, ...terminal, endedAt: record.endedAt ?? at, updatedAt: at }
|
|
534
|
-
if (record.auditState === 'pending') updated.auditState = 'incomplete'
|
|
535
|
-
if (lost || record.auditState === 'pending') updated.incomplete = true
|
|
536
535
|
const batchStages = pendingBatchStages.get(leaseId)
|
|
537
536
|
if (!batchStages && (isId(leaseId) || childLeases.size > 0 || lost)) updated.leaseState = 'released'
|
|
538
537
|
if (!lost && sessionQuery && isId(parentId)) {
|
package/lib/rules.js
CHANGED
|
@@ -27,21 +27,22 @@ export function teamTaskPromptNote(teamTaskId) {
|
|
|
27
27
|
* Build the rule text. `allowedTools` is the live whitelist the gate enforces,
|
|
28
28
|
* so the closing sentence names exactly what stays available.
|
|
29
29
|
*/
|
|
30
|
-
export function mainAgentRule(allowedTools) {
|
|
30
|
+
export function mainAgentRule(allowedTools, { readOnlyEnabled = false } = {}) {
|
|
31
31
|
const allowed = [...new Set(allowedTools ?? [])]
|
|
32
32
|
const allowedNames = allowed.join(', ')
|
|
33
33
|
return (
|
|
34
34
|
'主代理规则:主代理只负责规划,读/写/编辑/搜索/命令/抓取均通过 delegate 或 orchestrate 交子代理执行,勿试探调用被禁工具。' +
|
|
35
|
-
'
|
|
36
|
-
'已结束的写任务续跑前重抢原写租约并拍新基线,租约冲突或工作树已锁定时拒绝投递;本轮结束后写审计并再次释放租约。' +
|
|
37
|
-
'新会话或压缩后直接推进,无需重新确认。' +
|
|
38
|
-
'独立任务在同一消息内并发派发,delegate 完成后直接结束回合等待子代理完成,勿空转轮询状态。' +
|
|
39
|
-
'子代理完成通知只代表执行结束,不等于写作用域审计通过。' +
|
|
35
|
+
'优先用 send_message 复用当前会话中已有且闲置(inactive)的子代理,例如重试、纠偏、返工或追问。' +
|
|
40
36
|
(allowed.includes(DELEGATE_STATUS_TOOL_NAME)
|
|
41
|
-
?
|
|
42
|
-
: '') +
|
|
43
|
-
'
|
|
44
|
-
'
|
|
37
|
+
? `需调整该子代理下一轮的 writeScope 或 readOnly 时,先调用 ${DELEGATE_STATUS_TOOL_NAME}({ action: 'edit', childId, writeScope, readOnly }) 更新待应用声明,再用 send_message 唤醒。`
|
|
38
|
+
: '复用时沿用当前写作用域和只读声明。') +
|
|
39
|
+
'仅在 Worktree 已锁定或合回、原上下文跑偏,或确需并行处理互不干扰的独立任务时,才通过 delegate 的 allowNewReason 说明原因后新建。' +
|
|
40
|
+
'恢复写任务前按下一轮声明重新获取写租约,租约冲突或工作树已锁定时拒绝投递;本轮结束后释放租约。' +
|
|
41
|
+
'新会话或压缩后直接推进,无需重新确认。' +
|
|
42
|
+
'确需并行的独立任务在同一消息内派发,delegate 返回后直接结束回合等待子代理完成,勿空转轮询状态。' +
|
|
43
|
+
'Git 仓库中的写任务默认在独立 Git Worktree 中执行,非 Git 目录使用写租约协调声明范围内的写入。可用 isolation: "auto" | "worktree" | "shared" 覆盖隔离模式。' +
|
|
44
|
+
(readOnlyEnabled ? '' : '只读调研或检索无需代码隔离时,显式传 isolation: "shared",并在任务描述和边界中要求不得修改文件,避免创建无用 Worktree。') +
|
|
45
|
+
'Worktree 不自动合回;子代理交付后由主代理评审并决定是否合回。' +
|
|
45
46
|
(allowed.includes('worktree_manage')
|
|
46
47
|
? '用 worktree_manage(list / inspect / merge / discard / prune)显式评审、合回或清理。'
|
|
47
48
|
: '') +
|