@sshirkit/dsh-orchestrator 1.0.1 → 1.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/delegate.js CHANGED
@@ -16,7 +16,7 @@
16
16
  import { statSync } from 'node:fs'
17
17
  import path from 'node:path'
18
18
  import { DELEGATE_TOOL, DELIVERY, disabledToolMessage } from './api.js'
19
- import { mainAgentRule } from './rules.js'
19
+ import { mainAgentRule, teamTaskPromptNote } from './rules.js'
20
20
  import { buildSpawnActivation, isDispatchEnabled, languageNote, readRoute, readRouteOverride } from './worker.js'
21
21
  import { auditBaseline, captureBaseline, formatAuditReport } from './write-audit.js'
22
22
  import { auditGitBaseline, captureGitBaseline, formatGitAuditReport } from './git-audit.js'
@@ -39,6 +39,19 @@ export { WriteScopeError, WRITE_SCOPE_TOOL_CODES } from './write-scope-tool.js'
39
39
 
40
40
  export const READ_ONLY_NOTICE = '本任务仅限只读,不得写入文件。不占写租约;宿主未提供逐子代理物理只读隔离,由插件做逻辑写后审计并告警。'
41
41
 
42
+ export const TEAM_TASK_ID_PARAMETER = Object.freeze({
43
+ type: 'string',
44
+ description: '可选原生 Team 任务 ID;传给子代理作为共享目标的只读对齐参考,不能替代完整任务说明。',
45
+ })
46
+
47
+ export function parseTeamTaskId(value, tool) {
48
+ if (value === undefined) return undefined
49
+ if (typeof value !== 'string' || value.trim() === '') {
50
+ throw new Error(`${tool}: "team_task_id" must be a non-empty string when provided`)
51
+ }
52
+ return value.trim()
53
+ }
54
+
42
55
  export function dispatchWriteParameters({ batch = false } = {}) {
43
56
  return {
44
57
  writeScope: {
@@ -225,13 +238,14 @@ export function auditNotice(audit) {
225
238
  }
226
239
 
227
240
  /** The delegate spec: the prompt carries the language note and delivery answers the parent. */
228
- export function buildActivation({ args, parent, route, maxDepth, signal, baselineId, worktree }) {
241
+ export function buildActivation({ args, parent, route, maxDepth, signal, baselineId, worktree, teamTaskId }) {
229
242
  return buildSpawnActivation({
230
243
  cwd: worktree?.execCwd ?? args.cwd,
231
244
  prompt: languageNote(args.prompt) + args.prompt +
232
245
  (args.readOnly === true ? `\n\n${READ_ONLY_NOTICE}` : '') +
233
246
  (baselineId === undefined ? '' : `\n写后审计基线:${baselineId}。`) +
234
- (worktree ? `\n\n${worktreePromptNote(worktree)}` : ''),
247
+ (worktree ? `\n\n${worktreePromptNote(worktree)}` : '') +
248
+ (teamTaskId === undefined ? '' : `\n\n${teamTaskPromptNote(teamTaskId)}`),
235
249
  label: args.description,
236
250
  parent,
237
251
  route,
@@ -257,21 +271,20 @@ export function createDelegateTool({
257
271
  onCleanupFailed,
258
272
  persistence,
259
273
  }) {
260
- // `allowedTools` is the Allowed Tools whitelist the gate enforces: a function when the
261
- // host owns the list, read again whenever the description is rendered, so a settings
262
- // change reaches the prompt without re-registering the tool. A fixed array is still
263
- // accepted, for tests and callers that have no live config. `deniedTools` is accepted
264
- // only as a legacy alias, so an older caller cannot silently describe the wrong rule.
265
- const list = allowedTools ?? deniedTools
266
- const liveAllowed = typeof list === 'function' ? list : () => list
274
+ // Direct callers may provide an unscoped display list. Model-facing descriptions
275
+ // are rendered explicitly on scoped copies by tool-surface, never through this list.
276
+ const legacyList = allowedTools ?? deniedTools
277
+ const legacyAllowed = typeof legacyList === 'function' ? legacyList : () => legacyList
267
278
  const enabled = () => isDispatchEnabled(config)
268
- const rule = () => mainAgentRule(liveAllowed())
269
279
  const body =
270
280
  '把一个自包含任务交给子代理执行。子代理看不到本会话,prompt 须写清目标、允许修改的文件、验收命令与兜底方案。非只读任务必填 writeScope;只读任务设 readOnly: true,不占租约,只做逻辑写后审计而非物理隔离。' +
271
281
  '立即返回子代理 ID 及宿主提供的 agentName,二者均可填 send_message.agent。结束时自动通知,严禁要求子代理用 send_message 汇报。' +
272
282
  '独立 Worktree 交付物须经 worktree_manage 评审、合回或丢弃。' +
273
283
  '多个独立任务在同一轮并发发起;同构批量请用 orchestrate。'
274
- const descriptionOf = () => (enabled() ? rule() + (nativeToolNote?.() ?? '') + body : body)
284
+ const describeFor = (allowed) => (enabled()
285
+ ? mainAgentRule(allowed) + (nativeToolNote?.(allowed) ?? '') + body
286
+ : body)
287
+ const descriptionOf = () => legacyList === undefined ? body : describeFor(legacyAllowed())
275
288
 
276
289
  // A provisional id lets the lease be registered before the host names the child: the
277
290
  // conflict has to be refused before `startActivation` (AC1). `rebind` moves the same
@@ -301,6 +314,7 @@ export function createDelegateTool({
301
314
  required: true,
302
315
  description: '交给子代理的完整任务说明;它看不到本会话。',
303
316
  },
317
+ team_task_id: TEAM_TASK_ID_PARAMETER,
304
318
  provider: {
305
319
  type: 'string',
306
320
  description:
@@ -362,6 +376,7 @@ export function createDelegateTool({
362
376
  const checked = validateDispatchWrite(args, DELEGATE_TOOL)
363
377
  if (typeof args?.prompt !== 'string' || args.prompt.trim() === '') throw new Error('delegate requires a non-empty prompt')
364
378
  if (typeof args?.description !== 'string' || args.description.trim() === '') throw new Error('delegate requires a non-empty description')
379
+ const teamTaskId = parseTeamTaskId(args.team_task_id, DELEGATE_TOOL)
365
380
  // An explicit per-call override wins and is never read from config; otherwise the
366
381
  // route is read at call time, so a changed route applies from this delegation on.
367
382
  const route = readRouteOverride(args, DELEGATE_TOOL) ?? readRoute(config)
@@ -395,7 +410,9 @@ export function createDelegateTool({
395
410
  })
396
411
  const held = write.lease
397
412
  const baselineId = write.baseline?.baselineId
398
- const spec = buildActivation({ args, parent, route, maxDepth, signal: exec.signal, baselineId, worktree })
413
+ const spec = buildActivation({
414
+ args, parent, route, maxDepth, signal: exec.signal, baselineId, worktree, teamTaskId,
415
+ })
399
416
  if (persistence) {
400
417
  await persistence.beforeLaunch(write)
401
418
  persistence.assertActive()
@@ -458,12 +475,11 @@ export function createDelegateTool({
458
475
  }
459
476
  },
460
477
  })
461
- // The host reads `description` while it builds a request (its own run_code tool uses a
462
- // getter for the same reason), so this keeps the rule text in step with the gate.
463
- Object.defineProperty(tool, 'description', {
464
- enumerable: true,
465
- configurable: true,
466
- get: descriptionOf,
478
+ // Direct consumers keep a readable default. Request-scoped definitions supply their
479
+ // resolved list explicitly rather than changing the registered tool's description.
480
+ Object.defineProperties(tool, {
481
+ description: { enumerable: true, configurable: true, get: descriptionOf },
482
+ describeFor: { value: describeFor },
467
483
  })
468
484
  return tool
469
485
  }
package/lib/gate.js CHANGED
@@ -258,7 +258,7 @@ export function installGate({ agent, allowed, allowAgentTeam = true, enabled = (
258
258
  }
259
259
  return undefined
260
260
  }
261
- const guard = allowGuard(liveAllowed(), { allowAgentTeam: liveAllowAgentTeam() })
261
+ const guard = allowGuard(liveAllowed(caller), { allowAgentTeam: liveAllowAgentTeam() })
262
262
  const refusal = guard(exec)
263
263
  if (refusal === undefined) return undefined
264
264
  return checkSupervision?.(caller, tool, { whitelistMiss: true }) ?? refusal
@@ -267,7 +267,7 @@ export function installGate({ agent, allowed, allowAgentTeam = true, enabled = (
267
267
  guardError = error instanceof Error ? error.message : String(error)
268
268
  }
269
269
  return {
270
- allowed: resolveEffectiveAllowedTools(liveAllowed(), { allowAgentTeam: liveAllowAgentTeam() }),
270
+ allowed: resolveEffectiveAllowedTools(liveAllowed(agent), { allowAgentTeam: liveAllowAgentTeam() }),
271
271
  guardError,
272
272
  /** Unregister the guard. A second call is a no-op. */
273
273
  dispose: () => {
package/lib/index.js CHANGED
@@ -17,6 +17,7 @@ import {
17
17
  createActionLedger, evaluateWakeupGate, inspectHostChildState, makeResumeActionKey,
18
18
  makeSettleActionKey, reconcileOnStartup,
19
19
  } from './reconcile.js'
20
+ import { createSessionTools, mountSessionToolsRemote } from './session-tools.js'
20
21
  import { createStateStore } from './state-store.js'
21
22
  import { normalizeScope } from './write-scope.js'
22
23
  import {
@@ -31,7 +32,7 @@ import {
31
32
  } from './supervise.js'
32
33
  import { SWITCH_SOURCE_KIND, createSwitchNotices } from './switch-notice.js'
33
34
  import { INLINE_AUDIT_SOURCE_KIND, createDispatchTimeline, formatInlineAuditNotice } from './timeline.js'
34
- import { DEFAULT_ALLOWED_TOOLS, NATIVE_TEAM_TOOLS, installToolSurface, resolveEffectiveAllowedTools } from './tool-surface.js'
35
+ import { DEFAULT_ALLOWED_TOOLS, NATIVE_TEAM_TOOLS, installToolSurface } from './tool-surface.js'
35
36
  import { isDispatchEnabled } from './worker.js'
36
37
  import { createWriteLeases } from './write-lease.js'
37
38
  import { formatWorktreeError, releaseWriteScope } from './write-scope-tool.js'
@@ -1590,14 +1591,27 @@ export function apply(ctx, config) {
1590
1591
  // The same live whitelist feeds the prompt, execution guard and tool definitions.
1591
1592
  const catalog = createCatalogPublisher({ ctx, config })
1592
1593
  const allowAgentTeam = () => configValue(config, 'allowAgentTeam', true) !== false
1593
- const allowedTools = () => resolveEffectiveAllowedTools(configValue(config, 'allowedTools', undefined), {
1594
- defaults: DEFAULT_ALLOWED_TOOLS,
1594
+ const isNativeTeamEnabled = (agent) => {
1595
+ try {
1596
+ // The optional host service resolves the caller's root and reads its Team projection.
1597
+ const teams = typeof ctx.get === 'function' ? ctx.get('agentTeams') : ctx.agentTeams
1598
+ return teams?.isEnabled?.(agent) === true
1599
+ } catch {
1600
+ // An unavailable service or a scope without a live Team root must not break tool rendering.
1601
+ return false
1602
+ }
1603
+ }
1604
+ const sessionTools = createSessionTools({ facility, ctx, logger: ctx.logger, globalAllowedFor: () => allowedToolsFor() })
1605
+ const allowedToolsFor = (subject) => sessionTools.resolveAllowedTools(subject, {
1606
+ globalAllowed: configValue(config, 'allowedTools', undefined),
1607
+ defaultAllowed: DEFAULT_ALLOWED_TOOLS,
1595
1608
  allowAgentTeam: allowAgentTeam(),
1596
- availableTools: catalog.published(),
1609
+ catalog: catalog.published(),
1597
1610
  })
1598
- const nativeToolNote = () => {
1599
- const allowed = allowedTools()
1600
- const team = NATIVE_TEAM_TOOLS.some((name) => allowed.includes(name))
1611
+ const sessionToolsRemote = mountSessionToolsRemote(ctx, sessionTools)
1612
+ if (!sessionToolsRemote.available && typeof ctx.provide === 'function') warn(sessionToolsRemote.error)
1613
+ const nativeToolNote = (allowed) => {
1614
+ const team = NATIVE_TEAM_TOOLS.some((name) => allowed?.includes(name))
1601
1615
  ? '原生 team_task_* 仅用于共享任务板,不替代派发或写租约。'
1602
1616
  : ''
1603
1617
  return `${team}subagent_fork / workflow 默认屏蔽。`
@@ -1621,7 +1635,9 @@ export function apply(ctx, config) {
1621
1635
  config,
1622
1636
  onStarted: onDelegateStarted,
1623
1637
  nativeToolNote,
1624
- allowedTools,
1638
+ // Direct, unscoped consumers retain the global description. Scoped declarations
1639
+ // replace it with describeFor(allowedToolsFor(scope)) without touching the registry.
1640
+ allowedTools: () => allowedToolsFor(undefined),
1625
1641
  leases: writeLeases,
1626
1642
  })
1627
1643
  // Both tools share the one table, so a `delegate` and a batch (or two batches) cannot
@@ -1778,7 +1794,7 @@ export function apply(ctx, config) {
1778
1794
 
1779
1795
  const installFor = (agent) => installGate({
1780
1796
  agent,
1781
- allowed: allowedTools,
1797
+ allowed: allowedToolsFor,
1782
1798
  allowAgentTeam,
1783
1799
  enabled: dispatchEnabled,
1784
1800
  checkSupervision: (current, tool, options) => supervisionTurnState.checkTool(current.id, currentTurnOf(current), tool, options),
@@ -1814,8 +1830,10 @@ export function apply(ctx, config) {
1814
1830
  () =>
1815
1831
  installToolSurface({
1816
1832
  tools: ctx.tools,
1817
- allowed: allowedTools,
1833
+ allowed: allowedToolsFor,
1834
+ describeDelegate: delegateTool.describeFor,
1818
1835
  allowAgentTeam,
1836
+ isNativeTeamEnabled,
1819
1837
  enabled: dispatchEnabled,
1820
1838
  }),
1821
1839
  'orchestrator: tool surface',
@@ -2164,6 +2182,7 @@ export function apply(ctx, config) {
2164
2182
  nextStep: createSwitchPreStep({ switchNotices, logger: ctx.logger, supervisionTurnState }),
2165
2183
  })
2166
2184
  listen('agent/pre-step', async (payload, next) => {
2185
+ if (hasStorage) await sessionTools.ready
2167
2186
  if (restoring) await readyPromise
2168
2187
  if (disposing) return next()
2169
2188
  const decision = await preStep(payload, next)
@@ -2241,8 +2260,12 @@ export function apply(ctx, config) {
2241
2260
  disposing = true
2242
2261
  if (!legacyEffects) stopTimer()
2243
2262
  startupAbort.abort()
2244
- const closing = stateStore.close()
2245
- disposePromise = closing.catch((error) => warn(`关闭存储域失败:${messageOf(error)}`)).finally(() => {
2263
+ const closing = Promise.all([
2264
+ stateStore.close().catch((error) => warn(`关闭存储域失败:${messageOf(error)}`)),
2265
+ sessionToolsRemote.dispose().catch((error) => warn(`卸载会话 Remote 失败:${messageOf(error)}`)),
2266
+ sessionTools.close().catch((error) => warn(`关闭会话存储域失败:${messageOf(error)}`)),
2267
+ ])
2268
+ disposePromise = closing.finally(() => {
2246
2269
  try {
2247
2270
  clean(listenerDisposers)
2248
2271
  for (const cursor of supervision.supervisor.exportCursors()) supervision.supervisor.forget(cursor.childId)
@@ -4,10 +4,10 @@
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
13
  * owns a checkout, lease and audit across all its stages. Shared mode preserves the
@@ -17,10 +17,12 @@
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, auditNotice, discardEmptyWorktree, dispatchWorkspaceRoot,
21
+ dispatchWriteParameters, parseTeamTaskId, prepareDispatchWrite, settleDispatchWrite,
22
+ validateDispatchIsolation, validateDispatchWrite, worktreeAuditSummary, 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
27
  import { buildSpawnActivation, isDispatchEnabled, readRoute, readRouteOverride } from './worker.js'
26
28
  import { probeGitRepo } from './worktree.js'
@@ -48,18 +50,18 @@ 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
57
  'expectedFingerprints',
55
58
  'expectedTargets',
56
59
  ])
57
- const STAGE_KEYS = Object.freeze(['name', 'prompt', 'schema'])
60
+ const STAGE_KEYS = Object.freeze(['name', 'prompt', 'schema', 'provider', 'model', 'reasoning_effort'])
58
61
 
59
62
  /**
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.
63
+ * Reject fields the tool does not implement. Silently ignoring a typo would run
64
+ * workers with a different configuration than the caller believes.
63
65
  */
64
66
  function rejectUnknownKeys(value, allowed, at) {
65
67
  for (const key of Object.keys(value)) {
@@ -70,11 +72,12 @@ function rejectUnknownKeys(value, allowed, at) {
70
72
 
71
73
  /**
72
74
  * Validate and normalise `execute` arguments. Everything that can fail globally
73
- * (shape, unknown fields, limits, stage schema) fails here, before any worker starts.
75
+ * (shape, unknown fields, limits, stage schema and route) fails here, before any worker starts.
74
76
  */
75
77
  export function parseOrchestrateArgs(args) {
76
78
  if (!isPlainObject(args)) fail('arguments must be an object')
77
79
  rejectUnknownKeys(args, ARGUMENT_KEYS, 'arguments')
80
+ const teamTaskId = parseTeamTaskId(args.team_task_id, ORCHESTRATE_TOOL)
78
81
 
79
82
  if (!Array.isArray(args.items)) fail('"items" must be a JSON array')
80
83
  if (!within(args.items.length, LIMITS.items)) {
@@ -101,10 +104,12 @@ export function parseOrchestrateArgs(args) {
101
104
  fail(error instanceof Error ? error.message : String(error))
102
105
  }
103
106
  }
107
+ const route = readRouteOverride(stage, `${ORCHESTRATE_TOOL}.stages[${index}]`)
104
108
  return {
105
109
  name: stage.name,
106
110
  prompt: stage.prompt,
107
111
  ...(stage.schema === undefined ? {} : { schema: stage.schema }),
112
+ ...(route === undefined ? {} : { route }),
108
113
  }
109
114
  })
110
115
 
@@ -133,6 +138,7 @@ export function parseOrchestrateArgs(args) {
133
138
  maxConcurrency: args.maxConcurrency ?? LIMITS.maxConcurrency.default,
134
139
  writeScope,
135
140
  readOnly: readOnly === true,
141
+ ...(teamTaskId === undefined ? {} : { teamTaskId }),
136
142
  }
137
143
  }
138
144
 
@@ -153,6 +159,7 @@ export function buildStagePrompt({
153
159
  readOnly,
154
160
  baselineId,
155
161
  worktree,
162
+ teamTaskId,
156
163
  }) {
157
164
  const lines = [
158
165
  stage.prompt.trim(),
@@ -188,6 +195,7 @@ export function buildStagePrompt({
188
195
  lines.push(readOnly ? READ_ONLY_NOTICE : writeScopeNotice(writeScope))
189
196
  if (baselineId !== undefined) lines.push(`写后审计基线:${baselineId}。`)
190
197
  if (worktree) lines.push('', worktreePromptNote(worktree))
198
+ if (teamTaskId !== undefined) lines.push('', teamTaskPromptNote(teamTaskId))
191
199
  return lines.join('\n')
192
200
  }
193
201
 
@@ -316,7 +324,8 @@ function createLimiter(limit) {
316
324
  export async function runOrchestration({
317
325
  plan,
318
326
  parent,
319
- route,
327
+ batchRoute,
328
+ defaultRoute,
320
329
  maxDepth,
321
330
  subagents,
322
331
  signal,
@@ -326,7 +335,7 @@ export async function runOrchestration({
326
335
  stageTracking,
327
336
  sharedBatch,
328
337
  }) {
329
- const { cwd, items, stages, maxConcurrency, readOnly } = plan
338
+ const { cwd, items, stages, maxConcurrency, readOnly, teamTaskId } = plan
330
339
  const limiter = createLimiter(maxConcurrency)
331
340
  const results = new Array(items.length).fill(null)
332
341
  const errors = []
@@ -383,7 +392,7 @@ export async function runOrchestration({
383
392
  prompt,
384
393
  label: `orchestrate ${stage.name} (item ${itemIndex + 1}/${items.length}, stage ${stageIndex + 1}/${stages.length})`,
385
394
  parent,
386
- route,
395
+ route: stage.route ?? batchRoute ?? defaultRoute,
387
396
  maxDepth,
388
397
  signal,
389
398
  outputSchema: stage.schema,
@@ -520,6 +529,7 @@ export async function runOrchestration({
520
529
  readOnly,
521
530
  baselineId: workspace?.write.baseline?.baselineId ?? baselineId,
522
531
  worktree: workspace?.worktree,
532
+ teamTaskId,
523
533
  })
524
534
  output = await runStage({ stage, stageIndex, prompt, itemIndex: index, workspace })
525
535
  previous = { stageName: stage.name, output }
@@ -720,6 +730,7 @@ export function createOrchestrateTool({
720
730
  description: '初始工作目录(相对路径基于当前目录);省略则继承。',
721
731
  },
722
732
  ...dispatchWriteParameters({ batch: true }),
733
+ team_task_id: TEAM_TASK_ID_PARAMETER,
723
734
  items: {
724
735
  type: 'array',
725
736
  required: true,
@@ -729,7 +740,9 @@ export function createOrchestrateTool({
729
740
  stages: {
730
741
  type: 'array',
731
742
  required: true,
732
- description: `顺序执行的阶段(${LIMITS.stages.min}..${LIMITS.stages.max}),单阶段即扇出。`,
743
+ description:
744
+ `顺序执行的阶段(${LIMITS.stages.min}..${LIMITS.stages.max}),单阶段即扇出。` +
745
+ '路由优先级:阶段覆盖 > 顶层批次覆盖 > 面板默认 worker 路由。',
733
746
  items: {
734
747
  type: 'object',
735
748
  additionalProperties: false,
@@ -750,6 +763,21 @@ export function createOrchestrateTool({
750
763
  description:
751
764
  '可选对象根 JSON Schema(支持 type/properties/required/additionalProperties/items/enum/const/oneOf)。',
752
765
  },
766
+ provider: {
767
+ type: 'string',
768
+ description:
769
+ '可选阶段路由覆盖:仅当用户显式点名(当前消息或 AGENTS.md 等工作区指令)时与 model 同传;优先于顶层批次覆盖。',
770
+ },
771
+ model: {
772
+ type: 'string',
773
+ description:
774
+ '可选阶段路由覆盖:仅当用户显式点名(当前消息或 AGENTS.md 等工作区指令)时与 provider 同传;优先于顶层批次覆盖。',
775
+ },
776
+ reasoning_effort: {
777
+ type: 'string',
778
+ description:
779
+ '可选阶段推理强度:仅当用户点名时才设置,须与阶段 provider/model 同传;作为整组覆盖优先于顶层批次,不继承后备路由的推理强度。',
780
+ },
753
781
  },
754
782
  },
755
783
  },
@@ -760,12 +788,12 @@ export function createOrchestrateTool({
760
788
  provider: {
761
789
  type: 'string',
762
790
  description:
763
- '可选路由覆盖:仅当用户显式点名(当前消息或 AGENTS.md 等工作区指令)时与 model 同传;省略走 worker 路由。',
791
+ '可选批次路由覆盖:仅当用户显式点名(当前消息或 AGENTS.md 等工作区指令)时与 model 同传;适用于无阶段覆盖的阶段,省略走 worker 路由。',
764
792
  },
765
793
  model: {
766
794
  type: 'string',
767
795
  description:
768
- '可选路由覆盖:仅当用户显式点名(当前消息或 AGENTS.md 等工作区指令)时与 provider 同传;省略走 worker 路由。',
796
+ '可选批次路由覆盖:仅当用户显式点名(当前消息或 AGENTS.md 等工作区指令)时与 provider 同传;适用于无阶段覆盖的阶段,省略走 worker 路由。',
769
797
  },
770
798
  reasoning_effort: {
771
799
  type: 'string',
@@ -834,16 +862,18 @@ export function createOrchestrateTool({
834
862
  if (!parent) throw new Error('orchestrate requires a calling agent (exec.agent was undefined)')
835
863
  const isolation = validateDispatchIsolation(args)
836
864
  const checked = validateDispatchWrite(args, ORCHESTRATE_TOOL)
837
- // Parse first: bad input or schema must fail before any worker starts.
865
+ // Even if every stage overrides it, reject an invalid batch override.
866
+ const batchRoute = readRouteOverride(args, ORCHESTRATE_TOOL)
838
867
  const plan = parseOrchestrateArgs(args)
839
868
  const signal = exec.signal
840
869
  if (signal === undefined || typeof signal.throwIfAborted !== 'function') {
841
870
  throw new Error('orchestrate requires a cancellation signal')
842
871
  }
843
872
  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)
873
+ // Read the panel route only when needed, before acquiring any lease or Worktree.
874
+ const defaultRoute = batchRoute === undefined && plan.stages.some((stage) => stage.route === undefined)
875
+ ? readRoute(config)
876
+ : undefined
847
877
  const maxDepth = subagents.resolveMaxDepth(undefined)
848
878
  signal.throwIfAborted()
849
879
  const childId = nextBatchId(parent)
@@ -857,7 +887,8 @@ export function createOrchestrateTool({
857
887
  if (isolated.itemIsolation) {
858
888
  try {
859
889
  const result = await runOrchestration({
860
- plan, parent, route, maxDepth, subagents, signal, itemIsolation: isolated.itemIsolation, stageTracking,
890
+ plan, parent, batchRoute, defaultRoute, maxDepth, subagents, signal,
891
+ itemIsolation: isolated.itemIsolation, stageTracking,
861
892
  })
862
893
  const rows = isolated.rows.sort((left, right) => left.itemIndex - right.itemIndex)
863
894
  const audit = rows.length === 0 ? undefined : aggregateItemAudits(rows)
@@ -886,7 +917,8 @@ export function createOrchestrateTool({
886
917
  result = await runOrchestration({
887
918
  plan,
888
919
  parent,
889
- route,
920
+ batchRoute,
921
+ defaultRoute,
890
922
  maxDepth,
891
923
  subagents,
892
924
  signal,
package/lib/rules.js CHANGED
@@ -12,6 +12,17 @@
12
12
 
13
13
  import { DELEGATE_STATUS_TOOL_NAME } from './api.js'
14
14
 
15
+ export const TEAM_SHARED_GOAL_RULE =
16
+ '复杂多步或需多子代理协同的任务,先用 team_task_create 建立共享目标,将返回的 id(任务 ID)作为 team_task_id 传给 delegate 或 orchestrate。' +
17
+ '共享目标只用于对齐,仍由 delegate / orchestrate 派发并管理写租约;任务说明必须自包含。'
18
+
19
+ export function teamTaskPromptNote(teamTaskId) {
20
+ const id = JSON.stringify(teamTaskId)
21
+ return `关联的共享目标(team_task_id):${id}。` +
22
+ `若 team_task_get 可用,先调用 team_task_get({ task_id: ${id} }),只读查看共享目标作为对齐参考。` +
23
+ '除非任务明确要求更新进度,否则不要改写共享任务状态。若工具不可用或读取失败,按本提示中的完整自包含任务说明继续。'
24
+ }
25
+
15
26
  /**
16
27
  * Build the rule text. `allowedTools` is the live whitelist the gate enforces,
17
28
  * so the closing sentence names exactly what stays available.