@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.
@@ -4,25 +4,27 @@
4
4
  * testable without the DSH runtime.
5
5
  *
6
6
  * One worker call per item and stage; stages of one item are strictly sequential,
7
- * different items are independent (no global stage barrier). Every worker uses the
8
- * same route — the configured one, unless this call carries an explicit
9
- * provider/model override the user asked for — `delivery: 'caller'` and, when the
10
- * stage declares one, `outputSchema`.
7
+ * different items are independent (no global stage barrier). Each worker uses its
8
+ * stage's explicit route, the batch override, or the configured worker route, in
9
+ * that order. Every worker uses `delivery: 'caller'` and, when the stage declares
10
+ * one, `outputSchema`.
11
11
  *
12
12
  * A writable batch declares one top-level `writeScope`. In Git isolation each item
13
- * owns a checkout, lease and audit across all its stages. Shared mode preserves the
14
- * atomic batch lease and workspace snapshot; a conflict starts no workers.
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, auditNotice, discardEmptyWorktree, dispatchWorkspaceRoot, dispatchWriteParameters,
21
- prepareDispatchWrite, settleDispatchWrite, validateDispatchIsolation, validateDispatchWrite,
22
- worktreeAuditSummary, worktreeDetails, worktreeFailure, worktreePromptNote,
20
+ READ_ONLY_NOTICE, TEAM_TASK_ID_PARAMETER, discardEmptyWorktree, dispatchWorkspaceRoot,
21
+ dispatchWriteParameters, parseTeamTaskId, prepareDispatchWrite,
22
+ validateDispatchIsolation, validateDispatchWrite, worktreeDetails,
23
+ worktreeFailure, worktreePromptNote,
23
24
  } from './delegate.js'
25
+ import { teamTaskPromptNote } from './rules.js'
24
26
  import { assertObjectSchema, isJsonValue, validateJsonSchemaValue } from './schema.js'
25
- import { buildSpawnActivation, isDispatchEnabled, readRoute, readRouteOverride } from './worker.js'
27
+ import { buildSpawnActivation, configValue, isDispatchEnabled, readRoute, readRouteOverride } from './worker.js'
26
28
  import { probeGitRepo } from './worktree.js'
27
29
  import { dispatchCwd, formatWorktreeError, releaseWriteScope, writeScopeNotice } from './write-scope-tool.js'
28
30
 
@@ -48,18 +50,16 @@ const ARGUMENT_KEYS = Object.freeze([
48
50
  'provider',
49
51
  'model',
50
52
  'reasoning_effort',
53
+ 'team_task_id',
51
54
  'writeScope',
52
55
  'readOnly',
53
56
  'isolation',
54
- 'expectedFingerprints',
55
- 'expectedTargets',
56
57
  ])
57
- const STAGE_KEYS = Object.freeze(['name', 'prompt', 'schema'])
58
+ const STAGE_KEYS = Object.freeze(['name', 'prompt', 'schema', 'provider', 'model', 'reasoning_effort'])
58
59
 
59
60
  /**
60
- * Reject fields the tool does not implement. Silently ignoring a typo (or a
61
- * route override placed on a stage instead of the call) would run workers with a
62
- * different configuration than the caller believes, so unknown keys fail up front.
61
+ * Reject fields the tool does not implement. Silently ignoring a typo would run
62
+ * workers with a different configuration than the caller believes.
63
63
  */
64
64
  function rejectUnknownKeys(value, allowed, at) {
65
65
  for (const key of Object.keys(value)) {
@@ -70,11 +70,12 @@ function rejectUnknownKeys(value, allowed, at) {
70
70
 
71
71
  /**
72
72
  * Validate and normalise `execute` arguments. Everything that can fail globally
73
- * (shape, unknown fields, limits, stage schema) fails here, before any worker starts.
73
+ * (shape, unknown fields, limits, stage schema and route) fails here, before any worker starts.
74
74
  */
75
75
  export function parseOrchestrateArgs(args) {
76
76
  if (!isPlainObject(args)) fail('arguments must be an object')
77
77
  rejectUnknownKeys(args, ARGUMENT_KEYS, 'arguments')
78
+ const teamTaskId = parseTeamTaskId(args.team_task_id, ORCHESTRATE_TOOL)
78
79
 
79
80
  if (!Array.isArray(args.items)) fail('"items" must be a JSON array')
80
81
  if (!within(args.items.length, LIMITS.items)) {
@@ -101,10 +102,12 @@ export function parseOrchestrateArgs(args) {
101
102
  fail(error instanceof Error ? error.message : String(error))
102
103
  }
103
104
  }
105
+ const route = readRouteOverride(stage, `${ORCHESTRATE_TOOL}.stages[${index}]`)
104
106
  return {
105
107
  name: stage.name,
106
108
  prompt: stage.prompt,
107
109
  ...(stage.schema === undefined ? {} : { schema: stage.schema }),
110
+ ...(route === undefined ? {} : { route }),
108
111
  }
109
112
  })
110
113
 
@@ -133,6 +136,7 @@ export function parseOrchestrateArgs(args) {
133
136
  maxConcurrency: args.maxConcurrency ?? LIMITS.maxConcurrency.default,
134
137
  writeScope,
135
138
  readOnly: readOnly === true,
139
+ ...(teamTaskId === undefined ? {} : { teamTaskId }),
136
140
  }
137
141
  }
138
142
 
@@ -151,8 +155,8 @@ export function buildStagePrompt({
151
155
  previous,
152
156
  writeScope,
153
157
  readOnly,
154
- baselineId,
155
158
  worktree,
159
+ teamTaskId,
156
160
  }) {
157
161
  const lines = [
158
162
  stage.prompt.trim(),
@@ -186,8 +190,8 @@ export function buildStagePrompt({
186
190
  // declaration, so the constraint always travels with the prompt.
187
191
  lines.push('')
188
192
  lines.push(readOnly ? READ_ONLY_NOTICE : writeScopeNotice(writeScope))
189
- if (baselineId !== undefined) lines.push(`写后审计基线:${baselineId}。`)
190
193
  if (worktree) lines.push('', worktreePromptNote(worktree))
194
+ if (teamTaskId !== undefined) lines.push('', teamTaskPromptNote(teamTaskId))
191
195
  return lines.join('\n')
192
196
  }
193
197
 
@@ -316,17 +320,18 @@ function createLimiter(limit) {
316
320
  export async function runOrchestration({
317
321
  plan,
318
322
  parent,
319
- route,
323
+ batchRoute,
324
+ defaultRoute,
320
325
  maxDepth,
321
326
  subagents,
322
327
  signal,
323
328
  writeScope,
324
- baselineId,
325
329
  itemIsolation,
326
330
  stageTracking,
327
331
  sharedBatch,
332
+ sharedStarts,
328
333
  }) {
329
- const { cwd, items, stages, maxConcurrency, readOnly } = plan
334
+ const { cwd, items, stages, maxConcurrency, readOnly, teamTaskId } = plan
330
335
  const limiter = createLimiter(maxConcurrency)
331
336
  const results = new Array(items.length).fill(null)
332
337
  const errors = []
@@ -361,6 +366,13 @@ export async function runOrchestration({
361
366
  return pending
362
367
  }
363
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
+
364
376
  const onAbort = () => {
365
377
  for (const handle of active) void dispose(handle)
366
378
  }
@@ -383,7 +395,7 @@ export async function runOrchestration({
383
395
  prompt,
384
396
  label: `orchestrate ${stage.name} (item ${itemIndex + 1}/${items.length}, stage ${stageIndex + 1}/${stages.length})`,
385
397
  parent,
386
- route,
398
+ route: stage.route ?? batchRoute ?? defaultRoute,
387
399
  maxDepth,
388
400
  signal,
389
401
  outputSchema: stage.schema,
@@ -415,38 +427,38 @@ export async function runOrchestration({
415
427
  (handle) => ({ handle }),
416
428
  (error) => ({ error }),
417
429
  )
418
- // A start still in flight can launch a writer even after cancellation. Do not remove
419
- // or audit the checkout until a late receipt has been observed and disposed.
420
- if (workspace) {
421
- const pending = settledStart.then(async ({ handle }) => {
422
- if (!handle || typeof handle !== 'object') return
423
- // A receipt without a child or result is not evidence that a stage ran.
424
- workspace.started ||= (typeof handle.childId === 'string' && handle.childId.length > 0) ||
425
- typeof handle.result?.then === 'function'
426
- if (workspace.started) itemIsolation.bind(workspace, handle)
427
- if (signal.aborted) await dispose(handle)
428
- })
429
- workspace.pending = pending
430
- void pending.finally(() => {
431
- if (workspace.pending === pending) workspace.pending = undefined
432
- }).catch(() => {})
433
- }
434
- started = await new Promise((resolve, reject) => {
435
- const onAbort = () => reject(abortReason(signal))
436
- if (signal.aborted) onAbort()
437
- else signal.addEventListener('abort', onAbort, { once: true })
438
- settledStart.then((outcome) => {
439
- signal.removeEventListener('abort', onAbort)
440
- if (signal.aborted) {
441
- // Late handle: clean it up without dispatching its worker.
442
- if (outcome.handle !== undefined) void dispose(outcome.handle)
443
- reject(abortReason(signal))
444
- 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)
445
448
  }
446
- if (Object.hasOwn(outcome, 'error')) reject(outcome.error)
447
- else resolve(outcome.handle)
448
- })
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
+ }
449
457
  })
458
+ const pendingStarts = workspace?.pendingStarts ?? sharedStarts
459
+ pendingStarts?.add(pending)
460
+ void pending.finally(() => pendingStarts?.delete(pending)).catch(() => {})
461
+ started = await receipt
450
462
  if (
451
463
  started === null ||
452
464
  typeof started !== 'object' ||
@@ -482,8 +494,7 @@ export async function runOrchestration({
482
494
  try {
483
495
  if (started !== undefined) {
484
496
  active.delete(started)
485
- await dispose(started)
486
- if (batch && result) await stageTracking.stageEnded(batch, started, result)
497
+ await settleStage(batch, started, result)
487
498
  }
488
499
  } finally {
489
500
  if (acquired) limiter.release()
@@ -518,8 +529,8 @@ export async function runOrchestration({
518
529
  previous,
519
530
  writeScope: workspace?.write.writeScope ?? writeScope,
520
531
  readOnly,
521
- baselineId: workspace?.write.baseline?.baselineId ?? baselineId,
522
532
  worktree: workspace?.worktree,
533
+ teamTaskId,
523
534
  })
524
535
  output = await runStage({ stage, stageIndex, prompt, itemIndex: index, workspace })
525
536
  previous = { stageName: stage.name, output }
@@ -533,9 +544,10 @@ export async function runOrchestration({
533
544
  try {
534
545
  if (workspace) {
535
546
  const finish = () => itemIsolation.finish(workspace, index)
536
- if (workspace.pending && signal.aborted) itemIsolation.defer(workspace.pending, finish)
547
+ const pending = [...workspace.pendingStarts]
548
+ if (pending.length && signal.aborted) itemIsolation.defer(Promise.all(pending), finish)
537
549
  else {
538
- await workspace.pending
550
+ await Promise.all(pending)
539
551
  await finish()
540
552
  }
541
553
  }
@@ -592,7 +604,7 @@ const newBatch = (batchId, parent, write) => ({
592
604
 
593
605
  function prepareItemIsolation({
594
606
  isolation, worktrees, args, exec, parent, checked, leases, batchId, probeRepo, getWorkspaceRoot,
595
- captureGit, auditGit, onAudited, onWorktreeChild, onCleanupFailed, stageTracking,
607
+ onWorktreeChild, onCleanupFailed, stageTracking,
596
608
  }) {
597
609
  const sourceCwd = dispatchCwd(args, exec)
598
610
  const workspaceRoot = dispatchWorkspaceRoot(exec, getWorkspaceRoot)
@@ -634,10 +646,10 @@ function prepareItemIsolation({
634
646
  try {
635
647
  const write = prepareDispatchWrite({
636
648
  args, exec, parent, leases, childId: `${batchId}:item:${index}`, tool: ORCHESTRATE_TOOL,
637
- checked, worktree, captureGit,
649
+ checked, worktree,
638
650
  })
639
651
  const batch = stageTracking ? newBatch(batchId, parent, write) : undefined
640
- return { worktree, write, batch, started: false }
652
+ return { worktree, write, batch, started: false, pendingStarts: new Set() }
641
653
  } catch (error) {
642
654
  discardEmptyWorktree(worktrees, worktree, onCleanupFailed)
643
655
  throw error
@@ -652,64 +664,49 @@ function prepareItemIsolation({
652
664
  },
653
665
  async finish({ worktree, write, started, batch }, itemIndex) {
654
666
  if (stageTracking?.isDisposing() || (batch && !stageTracking.canFinishBatch(batch))) return
655
- let audit
656
667
  try {
657
668
  if (!started) {
658
669
  discardEmptyWorktree(worktrees, worktree, onCleanupFailed)
659
670
  return
660
671
  }
661
- audit = settleDispatchWrite(write.baseline, auditGit)
662
- worktrees.markReadyForReview(worktree.id, worktreeAuditSummary(audit))
672
+ worktrees.markReadyForReview(worktree.id)
663
673
  const { id: worktreeId, branch, path } = worktreeDetails(worktree)
664
- rows.push({ itemIndex, worktreeId, branch, path, audit })
665
- onAudited?.({ childId: `${batchId}:item:${itemIndex}`, parentId: parent.id, audit, itemIndex, worktree })
674
+ rows.push({ itemIndex, worktreeId, branch, path, state: "ready_for_review" })
666
675
  } finally {
667
- if (batch) await stageTracking.finishBatch(batch, audit)
676
+ if (batch) await stageTracking.finishBatch(batch)
668
677
  else releaseWriteScope(leases, write.lease)
669
678
  }
670
679
  },
671
680
  defer(pending, finish) {
672
- void pending.finally(finish).catch((error) => onCleanupFailed?.(error))
681
+ void pending.then(finish).catch((error) => onCleanupFailed?.(error))
673
682
  },
674
683
  },
675
684
  }
676
685
  }
677
686
 
678
- function aggregateItemAudits(rows) {
679
- const summary = { added: 0, modified: 0, deleted: 0, violations: 0, truncated: false }
680
- const changedFiles = []
681
- const violations = []
682
- for (const { itemIndex, audit } of rows) {
683
- for (const key of ['added', 'modified', 'deleted', 'violations']) summary[key] += audit.summary[key]
684
- summary.truncated ||= audit.summary.truncated === true
685
- changedFiles.push(...audit.changedFiles.map((entry) => ({ ...entry, itemIndex })))
686
- violations.push(...audit.violations.map((entry) => ({ ...entry, path: `item ${itemIndex + 1}: ${entry.path}`, itemIndex })))
687
- }
688
- return {
689
- passed: rows.every(({ audit }) => audit.passed), readOnly: false, isolationLevel: 'git-worktree',
690
- isolationNote: '每个条目独立完成 Git 审计;具体证据见 details.itemAudits。',
691
- changedFiles, violations, summary,
692
- }
693
- }
694
687
 
695
688
  export function createOrchestrateTool({
696
- defineTool, subagents, config, leases, onAudited, worktrees, onWorktreeChild, onCleanupFailed,
697
- isWorktreeEnabled = () => true, getWorkspaceRoot,
698
- captureGitBaseline: captureGit, auditGitBaseline: auditGit, probeGitRepo: probeRepo = probeGitRepo,
689
+ defineTool, subagents, config, leases, worktrees, onWorktreeChild, onCleanupFailed,
690
+ isWorktreeEnabled = () => true, resolveSessionConfig, getWorkspaceRoot,
691
+ probeGitRepo: probeRepo = probeGitRepo,
699
692
  stageTracking,
700
693
  }) {
701
694
  // This description does not repeat `mainAgentRule`: only `delegate` opens with it.
702
695
  // The plumbing still accepts the whitelist fields a shared factory passes down so a
703
696
  // caller does not have to branch, but they are unused here.
704
- const enabled = () => isDispatchEnabled(config)
697
+ const globalReadOnly = () => configValue(config, 'readOnlyEnabled', false) === true
705
698
  const ruleLead = '主代理规则同 delegate。'
706
- const body =
699
+ const body = (readOnlyEnabled) =>
707
700
  '按 item 派发子代理:单 stage 即批量扇出;多 stage 时各 item 独立走完阶段,无全局屏障,每阶段自动附带指令、原始 item 与上阶段输出。' +
708
701
  '声明 schema 的阶段输出校验过的 JSON,否则为文本;单 item 失败置为 null 并记入 errors。' +
709
- 'maxConcurrency 限制并发数;非只读调用必填 writeScope。Git 写任务默认按 item 分配独立 Worktree,同 item 多 stage 复用一树,结算后保留,由 worktree_manage 评审、合回或丢弃。' +
710
- '非 Git 自动降级:共享模式整批共享一个写租约,冲突时整批失败不排队;readOnly: true 不占租约,仅做逻辑写后审计,不是物理隔离。' +
702
+ 'maxConcurrency 限制并发数;' + (readOnlyEnabled ? '非只读调用' : '调用') +
703
+ '必填 writeScope。Git 写任务默认按 item 分配独立 Worktree,同 item 多 stage 复用一树,结算后保留,由 worktree_manage 评审、合回或丢弃。' +
704
+ '非 Git 自动降级:共享模式整批共享一个写租约,冲突时整批失败不排队。' +
705
+ (readOnlyEnabled ? 'readOnly: true 不占租约,宿主不提供逐子代理物理只读隔离。' : '') +
711
706
  '无关批次可并发调用;单任务请用 delegate。'
712
- const descriptionOf = () => (enabled() ? ruleLead + body : body)
707
+ const describeFor = (_allowed, { enabled = isDispatchEnabled(config), readOnlyEnabled = globalReadOnly() } = {}) =>
708
+ (enabled ? ruleLead : '') + body(readOnlyEnabled)
709
+ const descriptionOf = () => describeFor()
713
710
 
714
711
  const tool = defineTool({
715
712
  name: ORCHESTRATE_TOOL,
@@ -720,6 +717,7 @@ export function createOrchestrateTool({
720
717
  description: '初始工作目录(相对路径基于当前目录);省略则继承。',
721
718
  },
722
719
  ...dispatchWriteParameters({ batch: true }),
720
+ team_task_id: TEAM_TASK_ID_PARAMETER,
723
721
  items: {
724
722
  type: 'array',
725
723
  required: true,
@@ -729,7 +727,9 @@ export function createOrchestrateTool({
729
727
  stages: {
730
728
  type: 'array',
731
729
  required: true,
732
- description: `顺序执行的阶段(${LIMITS.stages.min}..${LIMITS.stages.max}),单阶段即扇出。`,
730
+ description:
731
+ `顺序执行的阶段(${LIMITS.stages.min}..${LIMITS.stages.max}),单阶段即扇出。` +
732
+ '路由优先级:阶段覆盖 > 顶层批次覆盖 > 面板默认 worker 路由。',
733
733
  items: {
734
734
  type: 'object',
735
735
  additionalProperties: false,
@@ -750,6 +750,21 @@ export function createOrchestrateTool({
750
750
  description:
751
751
  '可选对象根 JSON Schema(支持 type/properties/required/additionalProperties/items/enum/const/oneOf)。',
752
752
  },
753
+ provider: {
754
+ type: 'string',
755
+ description:
756
+ '可选阶段路由覆盖:仅当用户显式点名(当前消息或 AGENTS.md 等工作区指令)时与 model 同传;优先于顶层批次覆盖。',
757
+ },
758
+ model: {
759
+ type: 'string',
760
+ description:
761
+ '可选阶段路由覆盖:仅当用户显式点名(当前消息或 AGENTS.md 等工作区指令)时与 provider 同传;优先于顶层批次覆盖。',
762
+ },
763
+ reasoning_effort: {
764
+ type: 'string',
765
+ description:
766
+ '可选阶段推理强度:仅当用户点名时才设置,须与阶段 provider/model 同传;作为整组覆盖优先于顶层批次,不继承后备路由的推理强度。',
767
+ },
753
768
  },
754
769
  },
755
770
  },
@@ -760,12 +775,12 @@ export function createOrchestrateTool({
760
775
  provider: {
761
776
  type: 'string',
762
777
  description:
763
- '可选路由覆盖:仅当用户显式点名(当前消息或 AGENTS.md 等工作区指令)时与 model 同传;省略走 worker 路由。',
778
+ '可选批次路由覆盖:仅当用户显式点名(当前消息或 AGENTS.md 等工作区指令)时与 model 同传;适用于无阶段覆盖的阶段,省略走 worker 路由。',
764
779
  },
765
780
  model: {
766
781
  type: 'string',
767
782
  description:
768
- '可选路由覆盖:仅当用户显式点名(当前消息或 AGENTS.md 等工作区指令)时与 provider 同传;省略走 worker 路由。',
783
+ '可选批次路由覆盖:仅当用户显式点名(当前消息或 AGENTS.md 等工作区指令)时与 provider 同传;适用于无阶段覆盖的阶段,省略走 worker 路由。',
769
784
  },
770
785
  reasoning_effort: {
771
786
  type: 'string',
@@ -779,7 +794,6 @@ export function createOrchestrateTool({
779
794
  properties: {
780
795
  kind: { type: 'string', const: ORCHESTRATION_KIND },
781
796
  agentsStarted: { type: 'integer' },
782
- audit: { type: 'object', additionalProperties: true },
783
797
  details: { type: 'object', additionalProperties: true },
784
798
  results: {
785
799
  type: 'array',
@@ -818,10 +832,9 @@ export function createOrchestrateTool({
818
832
  text:
819
833
  `orchestration finished: ${value.results.filter((entry) => entry !== null).length}/${value.results.length} items, ` +
820
834
  `${value.errors.length} errors, ${value.agentsStarted} workers started` +
821
- (value.audit?.passed === false ? `\n不得验收为通过。\n${auditNotice(value.audit)}` : '') +
822
835
  (value.details?.worktrees?.length
823
836
  ? '\n请用 worktree_manage 逐项 inspect / merge / discard:\n' + value.details.worktrees.map((worktree) =>
824
- `item ${worktree.itemIndex + 1}:${worktree.worktreeId}(${worktree.branch})${worktree.audit.passed ? '审计通过' : '审计失败'}`).join('\n')
837
+ `item ${worktree.itemIndex + 1}:${worktree.worktreeId}(${worktree.branch})`).join('\n')
825
838
  : '') +
826
839
  (value.details?.isolationFallback ? `\n已降级为共享工作区:${value.details.isolationFallback.message}` : ''),
827
840
  },
@@ -829,45 +842,45 @@ export function createOrchestrateTool({
829
842
  },
830
843
  isConcurrencySafe: () => true,
831
844
  async execute(args, exec) {
832
- if (!enabled()) throw new Error(disabledToolMessage(ORCHESTRATE_TOOL))
833
845
  const parent = exec?.agent
846
+ const effective = resolveSessionConfig?.(parent)
847
+ if (!(effective?.enabled ?? isDispatchEnabled(config))) throw new Error(disabledToolMessage(ORCHESTRATE_TOOL))
834
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())
835
850
  const isolation = validateDispatchIsolation(args)
836
- const checked = validateDispatchWrite(args, ORCHESTRATE_TOOL)
837
- // Parse first: bad input or schema must fail before any worker starts.
851
+ // Even if every stage overrides it, reject an invalid batch override.
852
+ const batchRoute = readRouteOverride(args, ORCHESTRATE_TOOL)
838
853
  const plan = parseOrchestrateArgs(args)
839
854
  const signal = exec.signal
840
855
  if (signal === undefined || typeof signal.throwIfAborted !== 'function') {
841
856
  throw new Error('orchestrate requires a cancellation signal')
842
857
  }
843
858
  signal.throwIfAborted()
844
- // An explicit per-call override wins and is never read from config; otherwise the
845
- // route is read at call time, so a changed route applies from this orchestration on.
846
- const route = readRouteOverride(args, ORCHESTRATE_TOOL) ?? readRoute(config)
859
+ // Read the panel route only when needed, before acquiring any lease or Worktree.
860
+ const defaultRoute = batchRoute === undefined && plan.stages.some((stage) => stage.route === undefined)
861
+ ? effective?.workerRoute ?? readRoute(config)
862
+ : undefined
847
863
  const maxDepth = subagents.resolveMaxDepth(undefined)
848
864
  signal.throwIfAborted()
849
865
  const childId = nextBatchId(parent)
850
866
  let isolationFallback
851
867
  if (!checked.readOnly && (isolation.mode === 'worktree' ||
852
- (isolation.mode === 'auto' && worktrees && isWorktreeEnabled()))) {
868
+ (isolation.mode === 'auto' && worktrees && (effective?.worktreeIsolationEnabled ?? isWorktreeEnabled(parent))))) {
853
869
  const isolated = prepareItemIsolation({
854
870
  isolation, worktrees, args, exec, parent, checked, leases, batchId: childId, probeRepo, getWorkspaceRoot,
855
- captureGit, auditGit, onAudited, onWorktreeChild, onCleanupFailed, stageTracking,
871
+ onWorktreeChild, onCleanupFailed, stageTracking,
856
872
  })
857
873
  if (isolated.itemIsolation) {
858
874
  try {
859
875
  const result = await runOrchestration({
860
- plan, parent, route, maxDepth, subagents, signal, itemIsolation: isolated.itemIsolation, stageTracking,
876
+ plan, parent, batchRoute, defaultRoute, maxDepth, subagents, signal,
877
+ itemIsolation: isolated.itemIsolation, stageTracking,
861
878
  })
862
879
  const rows = isolated.rows.sort((left, right) => left.itemIndex - right.itemIndex)
863
- const audit = rows.length === 0 ? undefined : aggregateItemAudits(rows)
864
880
  return {
865
881
  ...result,
866
- ...(audit && { audit }),
867
882
  details: {
868
883
  worktrees: rows,
869
- itemAudits: rows.map(({ itemIndex, worktreeId, audit }) => ({ itemIndex, worktreeId, audit })),
870
- ...(audit && { writeAudit: audit }),
871
884
  },
872
885
  }
873
886
  } finally {
@@ -876,50 +889,51 @@ export function createOrchestrateTool({
876
889
  }
877
890
  isolationFallback = isolated.isolationFallback
878
891
  }
879
- // Shared mode keeps the atomic batch lease and one snapshot audit.
892
+ // Shared mode keeps the atomic batch lease and one owner across all stages.
880
893
  const write = prepareDispatchWrite({ args, exec, parent, leases, childId, tool: ORCHESTRATE_TOOL, checked })
881
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
+ }
882
901
  let result
883
- let audit
884
902
  try {
885
903
  if (sharedBatch) await stageTracking.beforeLaunch(write)
886
904
  result = await runOrchestration({
887
905
  plan,
888
906
  parent,
889
- route,
907
+ batchRoute,
908
+ defaultRoute,
890
909
  maxDepth,
891
910
  subagents,
892
911
  signal,
893
912
  writeScope: write.lease?.scope,
894
- baselineId: write.baseline?.baselineId,
895
913
  stageTracking,
896
914
  sharedBatch,
915
+ sharedStarts,
897
916
  })
898
917
  } finally {
899
- if (!stageTracking?.isDisposing() && (!sharedBatch || stageTracking.canFinishBatch(sharedBatch))) {
900
- try {
901
- audit = settleDispatchWrite(write.baseline)
902
- // On abort or another thrown error there is no result to attach evidence to.
903
- if (audit !== undefined) onAudited?.({ childId, parentId: parent.id, audit, hasResult: result !== undefined })
904
- } finally {
905
- if (sharedBatch) await stageTracking.finishBatch(sharedBatch, audit)
906
- else releaseWriteScope(leases, write.lease)
907
- }
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()
908
924
  }
909
925
  }
910
926
  return {
911
927
  ...result,
912
- ...(audit && { audit }),
913
928
  ...(isolationFallback && { details: { isolationFallback } }),
914
929
  }
915
930
  },
916
931
  })
917
932
  // The host reads `description` while it builds a request; keep it a live getter for the
918
933
  // same reason as `delegate`, even though this text no longer depends on the whitelist.
919
- Object.defineProperty(tool, 'description', {
920
- enumerable: true,
921
- configurable: true,
922
- get: descriptionOf,
934
+ Object.defineProperties(tool, {
935
+ description: { enumerable: true, configurable: true, get: descriptionOf },
936
+ describeFor: { value: describeFor },
923
937
  })
924
938
  return tool
925
939
  }