@fish-under-sea/dsh-agent-teams-fish 2.0.1 → 2.1.0

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.
@@ -43,6 +43,85 @@ interface RuntimeBoundary {
43
43
  [hostPromptDeliver]?: Deliver
44
44
  }
45
45
 
46
+ /**
47
+ * Audited 0.2.2-rc.2 tree manager seam. Upstream removed the symbol adapter
48
+ * without a public host-authored FIFO replacement. All native model/browser
49
+ * delivery converges on deliverToMember; keep that receiver, authorization,
50
+ * cancellation, provenance and wake/restore transaction intact.
51
+ * Source: dsh-v0.2.2-rc.2 subagent/src/{index,manager}.ts.
52
+ */
53
+ interface TreeActivation {
54
+ childId: SessionId
55
+ root: Agent
56
+ ancestors: readonly SessionId[]
57
+ }
58
+ interface TreeDeliveryOptions {
59
+ source: MessageSource
60
+ signal: AbortSignal
61
+ delivery: 'queue' | 'steer'
62
+ authorize?: () => void
63
+ }
64
+ type TreeDeliver = (root: Agent, childId: SessionId, content: ContentBlock[], options: TreeDeliveryOptions) => Promise<MessageId>
65
+ interface TreeManager {
66
+ deliverToMember: TreeDeliver
67
+ resident: ReadonlyMap<SessionId, TreeActivation>
68
+ dispose: (activation: TreeActivation) => Promise<void>
69
+ }
70
+ interface TreeBoundary {
71
+ rootOf: (caller: Agent) => Agent
72
+ manager: TreeManager
73
+ }
74
+ interface TreeWork {
75
+ root: Agent
76
+ branch: readonly SessionId[]
77
+ controller: AbortController
78
+ settled: Promise<void>
79
+ }
80
+ const treeWork = new WeakMap<TreeManager, Set<TreeWork>>()
81
+
82
+ function treeBoundary(runtime: Context['subagents']): TreeBoundary | undefined {
83
+ const tree = runtime as unknown as TreeBoundary & { prompt?: unknown }
84
+ if (typeof tree.rootOf !== 'function' || typeof tree.prompt !== 'function') return undefined
85
+ if (typeof tree.manager?.deliverToMember !== 'function' || typeof tree.manager.dispose !== 'function'
86
+ || !(tree.manager.resident instanceof Map)) return unsupported('missing audited tree delivery manager')
87
+ return tree
88
+ }
89
+
90
+ /** Track exact branch work before its first await so a targeted stop can join it. */
91
+ function trackTreeWork<T>(
92
+ manager: TreeManager, root: Agent, branch: readonly SessionId[], signal: AbortSignal,
93
+ operation: (signal: AbortSignal) => Promise<T>,
94
+ ): Promise<T> {
95
+ const pending = treeWork.get(manager) ?? new Set<TreeWork>()
96
+ treeWork.set(manager, pending)
97
+ const controller = new AbortController()
98
+ let finish!: () => void
99
+ const settled = new Promise<void>(resolve => { finish = resolve })
100
+ const work = { root, branch, controller, settled }
101
+ pending.add(work)
102
+ try {
103
+ return operation(AbortSignal.any([signal, controller.signal])).finally(() => { pending.delete(work); finish() })
104
+ } catch (error) {
105
+ pending.delete(work)
106
+ finish()
107
+ throw error
108
+ }
109
+ }
110
+
111
+ function deliverTreePrompt(
112
+ runtime: Context['subagents'], tree: TreeBoundary, parent: Agent, childId: SessionId,
113
+ content: ContentBlock[], source: MessageSource, signal: AbortSignal, delivery: 'queue' | 'steer',
114
+ ): Promise<MessageId> {
115
+ const root = tree.rootOf.call(runtime, parent)
116
+ return tree.manager.deliverToMember.call(tree.manager, root, childId, content, {
117
+ source, signal, delivery,
118
+ // Recheck the exact live caller immediately before native inbox acceptance.
119
+ authorize: () => {
120
+ if (tree.rootOf.call(runtime, parent) !== root) throw new SubagentError('AgentTeams caller left its subagent tree', 'UNAUTHORIZED')
121
+ },
122
+ })
123
+ }
124
+
46
125
  /** Version-independent creation contract; legacy-only options stay at this seam. */
47
126
  export interface MemberStartSpec {
48
127
  provider: string
@@ -72,7 +151,9 @@ export async function startMember(runtime: Context['subagents'], spec: MemberSta
72
151
  const host = runtime as unknown as CreationBoundary
73
152
  if (typeof host.startActivation === 'function') {
74
153
  const { persona: _persona, toolFilter: _filter, ...request } = spec.request
75
- const activation = await host.startActivation.call(runtime, { ...spec, request, delivery: 'parent' })
154
+ const activation = await Reflect.apply(host.startActivation, runtime, [treeBoundary(runtime) === undefined
155
+ ? { ...spec, request, delivery: 'parent' }
156
+ : { provider: spec.provider, label: spec.label, ...request, signal: spec.signal, delivery: 'parent' }]) as { childId: SessionId; result: Promise<unknown> }
76
157
  // Preserve native settlement as the missing-report/error fallback on both
77
158
  // fresh and resumed activations. mailbox.ts deduplicates successful reports.
78
159
  void activation.result.catch(() => undefined)
@@ -85,6 +166,7 @@ export async function startMember(runtime: Context['subagents'], spec: MemberSta
85
166
  /** Wrap every available creation API, restoring only this plugin's own methods. */
86
167
  export function guardSubagentCreation(ctx: Context, check: (parent: Agent) => void): void {
87
168
  const runtime = ctx.subagents as unknown as CreationBoundary
169
+ const tree = treeBoundary(ctx.subagents)
88
170
  ctx.effect(() => {
89
171
  const disposers: (() => void)[] = []
90
172
  for (const key of ['start', 'startContinuable', 'startActivation'] as const) {
@@ -92,8 +174,17 @@ export function guardSubagentCreation(ctx: Context, check: (parent: Agent) => vo
92
174
  if (typeof original !== 'function') continue
93
175
  const descriptor = Object.getOwnPropertyDescriptor(runtime, key)
94
176
  const guarded = async (...args: unknown[]): Promise<unknown> => {
95
- const request = key === 'start' ? args[1] : (args[0] as MemberStartSpec).request
96
- check((request as MemberStartSpec['request']).parent)
177
+ const request = key === 'start' ? args[1] : key === 'startActivation' && tree !== undefined
178
+ ? args[0] : (args[0] as MemberStartSpec).request
179
+ const parent = (request as MemberStartSpec['request']).parent
180
+ check(parent)
181
+ if (key === 'startActivation' && tree !== undefined) {
182
+ const spec = args[0] as { signal: AbortSignal }
183
+ const root = tree.rootOf.call(ctx.subagents, parent)
184
+ const branch = [parent.id, ...tree.manager.resident.get(parent.id)?.ancestors ?? []]
185
+ return trackTreeWork(tree.manager, root, branch, spec.signal, signal =>
186
+ Reflect.apply(original, ctx.subagents, [{ ...spec, signal }]) as Promise<unknown>)
187
+ }
97
188
  return Reflect.apply(original, ctx.subagents, args)
98
189
  }
99
190
  Object.defineProperty(runtime, key, { value: guarded, writable: true, configurable: true })
@@ -124,7 +215,9 @@ export function installMemberModelSelection(
124
215
  ref: { current: ModelSelection; assembled?: ModelSelection },
125
216
  ): () => void {
126
217
  const install = installModelSelection as unknown as (ctx: Context, ref?: unknown) => () => void
127
- return install.length >= 2 ? install(childCtx, ref) : install(childCtx)
218
+ // 0.2.2-rc.3 keeps the caller-owned selection ref; older hosts ignore the
219
+ // extra argument, so always forward it instead of guessing by arity.
220
+ return install(childCtx, ref)
128
221
  }
129
222
 
130
223
  function boundary(runtime: Context['subagents']): RuntimeBoundary {
@@ -292,6 +385,15 @@ export function assertMemberModelSelection(ctx: Context, captain: Agent, route:
292
385
  }
293
386
  }
294
387
 
388
+ /** rc.2 summaries use tree names; the new structured reason owns the outcome. */
389
+ export function successfulSubagentSettlement(source: MessageSource | undefined): source is Extract<MessageSource, { kind: 'subagent-settled' }> {
390
+ if (source?.kind !== 'subagent-settled') return false
391
+ const current = source as typeof source & { stopReason?: string }
392
+ return current.stopReason === undefined
393
+ ? source.summary === `Background subagent ${source.senderSessionId} finished and will do no further work unless you send it more.`
394
+ : current.stopReason === 'completed'
395
+ }
396
+
295
397
  /** Install before the first request, including cold resume, with HMR cleanup. */
296
398
  export function installContinuableMemberSetup(ctx: Context, setup: Setup): void {
297
399
  const runtime = boundary(ctx.subagents)
@@ -305,7 +407,7 @@ export function installContinuableMemberSetup(ctx: Context, setup: Setup): void
305
407
  })
306
408
  return
307
409
  }
308
- if ((typeof runtime[hostPromptQueue] !== 'function' && typeof runtime[hostPromptDeliver] !== 'function') || typeof runtime.sendMessage !== 'function') {
410
+ if (treeBoundary(ctx.subagents) === undefined && ((typeof runtime[hostPromptQueue] !== 'function' && typeof runtime[hostPromptDeliver] !== 'function') || typeof runtime.sendMessage !== 'function')) {
309
411
  return unsupported('missing continuable setup and modern host queue')
310
412
  }
311
413
  const installed = new WeakSet<Agent>()
@@ -369,6 +471,8 @@ export async function queueMemberPrompt(
369
471
  ): Promise<MessageId> {
370
472
  const host = boundary(runtime)
371
473
  const source = agentTeamsSource({ kind: 'agent-teams' }, observedSessionFormatVersion(parent))
474
+ const tree = treeBoundary(runtime)
475
+ if (tree !== undefined) return deliverTreePrompt(runtime, tree, parent, childId, content, source, signal, 'queue')
372
476
  if (typeof host.followup === 'function') {
373
477
  return host.followup.call(runtime, parent, childId, content, { source, signal })
374
478
  }
@@ -386,6 +490,8 @@ export async function steerMemberPrompt(
386
490
  ): Promise<MessageId> {
387
491
  const host = boundary(runtime)
388
492
  const source = agentTeamsSource({ kind: 'agent-teams' }, observedSessionFormatVersion(live ?? parent))
493
+ const tree = treeBoundary(runtime)
494
+ if (tree !== undefined) return deliverTreePrompt(runtime, tree, parent, childId, content, source, signal, 'steer')
389
495
  const deliver = host[hostPromptDeliver]
390
496
  if (typeof deliver === 'function') return deliver.call(runtime, parent, childId, content, source, signal, 'steer')
391
497
  if (typeof host.sendMessage === 'function') return host.sendMessage.call(runtime, parent, childId, content, { signal })
@@ -405,6 +511,35 @@ export function guardSubagentDelivery(
405
511
  ctx: Context, isRetired: (sender: Agent, targetId: SessionId) => Promise<boolean>,
406
512
  ): void {
407
513
  const runtime = ctx.subagents
514
+ const tree = treeBoundary(runtime)
515
+ if (tree !== undefined) {
516
+ const manager = tree.manager
517
+ ctx.effect(() => {
518
+ const original = manager.deliverToMember
519
+ const descriptor = Object.getOwnPropertyDescriptor(manager, 'deliverToMember')
520
+ let active = true
521
+ const guarded: TreeDeliver = async (root, childId, content, options) => {
522
+ if (!active) return original.call(manager, root, childId, content, options)
523
+ const branch = [childId, ...manager.resident.get(childId)?.ancestors ?? []]
524
+ return trackTreeWork(manager, root, branch, options.signal, async signal => {
525
+ signal.throwIfAborted()
526
+ if (await isRetired(root, childId)) {
527
+ throw new SubagentError(`AgentTeams member "${childId}" was retired and cannot be resumed`, 'NOT_RESUMABLE')
528
+ }
529
+ signal.throwIfAborted()
530
+ return original.call(manager, root, childId, content, { ...options, signal })
531
+ })
532
+ }
533
+ manager.deliverToMember = guarded
534
+ return () => {
535
+ active = false
536
+ if (Object.getOwnPropertyDescriptor(manager, 'deliverToMember')?.value !== guarded) return
537
+ if (descriptor === undefined) Reflect.deleteProperty(manager, 'deliverToMember')
538
+ else Object.defineProperty(manager, 'deliverToMember', descriptor)
539
+ }
540
+ }, 'agent-teams: tree retired member guard')
541
+ return
542
+ }
408
543
  const host = boundary(runtime)
409
544
  const legacy = host.followup
410
545
  const queue = host[hostPromptQueue]
@@ -567,6 +702,22 @@ export async function startMemberWithLenientFilter<T>(
567
702
 
568
703
  /** Targeted recursive cancellation renamed with the unified activation manager. */
569
704
  export async function drainMemberChildren(runtime: Context['subagents'], parent: Agent, ids: readonly SessionId[]): Promise<void> {
705
+ const tree = treeBoundary(runtime)
706
+ if (tree !== undefined) {
707
+ const root = tree.rootOf.call(runtime, parent)
708
+ const selected = new Set(ids)
709
+ // The native tree-wide drain also stops unrelated siblings and permanently
710
+ // closes the captain. Join only work in the selected creation branches.
711
+ const pending = [...treeWork.get(tree.manager) ?? []].filter(work => work.root === root && work.branch.some(id => selected.has(id)))
712
+ for (const work of pending) work.controller.abort()
713
+ await Promise.all(pending.map(work => work.settled))
714
+ const targets = [...tree.manager.resident.values()].filter(item => item.root === root
715
+ && item.ancestors.includes(parent.id) && (selected.has(item.childId) || item.ancestors.some(id => selected.has(id))))
716
+ const results = await Promise.allSettled(targets.map(item => tree.manager.dispose.call(tree.manager, item)))
717
+ const failures = results.flatMap(result => result.status === 'rejected' ? [result.reason as unknown] : [])
718
+ if (failures.length) throw new AggregateError(failures, 'AgentTeams member teardown failed')
719
+ return
720
+ }
570
721
  const host = runtime as unknown as {
571
722
  drainChildren?: (parent: Agent, ids: readonly SessionId[]) => Promise<void>
572
723
  drainContinuableChildren?: (parent: Agent, ids: readonly SessionId[]) => Promise<void>
package/src/index.ts CHANGED
@@ -22,6 +22,7 @@
22
22
  import type { Context } from '@deepseek-ai/cordis'
23
23
  import z from '@deepseek-ai/schemastery'
24
24
  import { createUserMessage } from '@deepseek-ai/dsh-llm'
25
+ import type { Agent } from '@deepseek-ai/dsh-agent'
25
26
  // Declaration merges make ctx.subagents and ctx.systemPrompt visible.
26
27
  import type {} from '@deepseek-ai/dsh-subagent'
27
28
  import type {} from '@deepseek-ai/dsh-system-prompt'
@@ -53,6 +54,21 @@ const WEB_SERVER_KEYS = ['webServer', 'httpServer'] as const
53
54
  /** Workspace registry service key candidates, newest first. */
54
55
  const WORKSPACE_KEYS = ['workspaceRegistry', 'workspace'] as const
55
56
 
57
+ /**
58
+ * Native 0.2.1-rc.3+ team-mode service (row id `agent-team`). It owns the
59
+ * durable per-Session `agentTeam` projection the model menu reads. Fish does
60
+ * not use its task tools or UI (those rows are disabled; Fish owns both), only
61
+ * the saved on/off switch, so the model-menu toggle can drive Fish AgentTeams.
62
+ */
63
+ interface NativeTeamModeService {
64
+ isEnabled(agent: Agent): boolean
65
+ setEnabled(agent: Agent, enabled: boolean, signal?: AbortSignal): Promise<void>
66
+ }
67
+
68
+ function nativeTeamMode(ctx: Context): NativeTeamModeService | undefined {
69
+ return (ctx as unknown as { agentTeams?: NativeTeamModeService }).agentTeams
70
+ }
71
+
56
72
  export const name = 'agent-teams'
57
73
  export const inject = ['tools', 'llm', 'subagents', 'systemPrompt', 'agents']
58
74
 
@@ -141,8 +157,10 @@ const toolPolicyConfig = z.union([
141
157
  export const Config: z<Config> = z.object({
142
158
  stateDir: z.string().default('.agent-teams'),
143
159
  memberProvider: z.string().default('spawn'),
144
- memberModel: z.string(),
145
- memberLlmProvider: z.string(),
160
+ // Optional: when absent, the member route comes from the official subagent
161
+ // policy (or the captain's current route when no policy was captured).
162
+ memberModel: z.union([z.string(), z.const(undefined)]),
163
+ memberLlmProvider: z.union([z.string(), z.const(undefined)]),
146
164
  executionPrompt: z.string(),
147
165
  fallback: fallbackRouteConfig,
148
166
  profiles: z.dict(z.object({
@@ -264,6 +282,8 @@ export async function resolveArtwork(
264
282
  }
265
283
 
266
284
  export function apply(ctx: Context, config: Config): void {
285
+ /** True when a native team-mode service is present and the switch is on. */
286
+ const teamEnabled = (agent: Agent): boolean => nativeTeamMode(ctx)?.isEnabled(agent) ?? true
267
287
  const resolved: ToolsConfig = {
268
288
  stateDir: config.stateDir ?? '.agent-teams',
269
289
  memberProvider: config.memberProvider ?? 'spawn',
@@ -274,6 +294,7 @@ export function apply(ctx: Context, config: Config): void {
274
294
  memberMaxDepth: config.memberMaxDepth ?? 0,
275
295
  maxMembers: config.maxMembers ?? 8,
276
296
  profiles: config.profiles ?? {},
297
+ isTeamEnabled: teamEnabled,
277
298
  // Owner configuration is validated once, at mount: an empty or malformed
278
299
  // policy must never reach a member creation path.
279
300
  toolPolicies: parseToolPolicies(config.toolPolicies),
@@ -295,6 +316,7 @@ export function apply(ctx: Context, config: Config): void {
295
316
  stateDir: resolved.stateDir,
296
317
  isPendingMember: agentTeamsRuntime.isPendingMember,
297
318
  order: config.promptSectionOrder,
319
+ isTeamEnabled: teamEnabled,
298
320
  // Keep the bounded profile directory available without extra tool calls.
299
321
  // installTeamCapabilities snapshots this once; no business state rewrites it.
300
322
  captainPrompt: () => usageSectionText(TEAM_TOOL_NAMES.join(', '), formatProfilesForPrompt(config.profiles)),
@@ -443,6 +465,63 @@ export function apply(ctx: Context, config: Config): void {
443
465
  },
444
466
  }), 'agent-teams: model policy route')
445
467
 
468
+ // 模型菜单「启用AgentTeam」开关。官方任务工具与官方团队 UI 行已在 bundle
469
+ // 层停用;原生服务只负责保存每个 Session 的持久开关,这里让开关直接控制
470
+ // Fish AgentTeams(关闭时工具与提示词都不参与本会话)。
471
+ ctx.effect(() => webServer.register({
472
+ kind: 'exact',
473
+ path: '/plugins/dsh-agent-teams/mode',
474
+ handler: async (req, res) => {
475
+ const url = new URL(req.url ?? '/', 'http://x')
476
+ const service = nativeTeamMode(ctx)
477
+ const respond = (status: number, body: unknown): void => {
478
+ res.writeHead(status, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' })
479
+ res.end(JSON.stringify(body))
480
+ }
481
+ if (service === undefined) {
482
+ respond(503, { error: 'native team-mode service is not mounted' })
483
+ return
484
+ }
485
+ const lookup = (sessionId: string): Agent | undefined =>
486
+ ctx.agents.get(sessionId as import('@deepseek-ai/dsh-session').SessionId)
487
+ if (req.method === 'GET') {
488
+ const sessionId = url.searchParams.get('session')?.trim() ?? ''
489
+ if (sessionId === '') { respond(400, { error: 'session is required' }); return }
490
+ const agent = lookup(sessionId)
491
+ if (agent === undefined) { respond(409, { error: 'session is not attached' }); return }
492
+ respond(200, { enabled: service.isEnabled(agent) })
493
+ return
494
+ }
495
+ if (req.method !== 'POST') {
496
+ res.writeHead(405, { allow: 'GET, POST', 'cache-control': 'no-store' })
497
+ res.end()
498
+ return
499
+ }
500
+ let payload: Record<string, unknown>
501
+ try {
502
+ payload = await readJsonRequest(req)
503
+ } catch (error: unknown) {
504
+ respond(error instanceof RequestBodyError ? error.status : 400, { error: error instanceof Error ? error.message : 'invalid request body' })
505
+ return
506
+ }
507
+ const sessionId = typeof payload['sessionId'] === 'string' ? payload['sessionId'].trim() : ''
508
+ const enabled = payload['enabled']
509
+ if (sessionId === '' || typeof enabled !== 'boolean') {
510
+ respond(400, { error: 'sessionId and enabled are required' })
511
+ return
512
+ }
513
+ const agent = lookup(sessionId)
514
+ if (agent === undefined) { respond(409, { error: 'session is not attached' }); return }
515
+ try {
516
+ await service.setEnabled(agent, enabled)
517
+ respond(200, { ok: true, enabled })
518
+ } catch (error: unknown) {
519
+ ctx.logger.warn(`agent-teams: mode switch failed: ${String(error)}`)
520
+ respond(409, { error: error instanceof Error ? error.message : 'failed to switch AgentTeam mode' })
521
+ }
522
+ },
523
+ }), 'agent-teams: mode route')
524
+
446
525
  ctx.effect(() => webServer.register({
447
526
  kind: 'exact',
448
527
  path: '/plugins/dsh-agent-teams/plan',
package/src/mailbox.ts CHANGED
@@ -3,7 +3,7 @@ import type { Context } from '@deepseek-ai/cordis'
3
3
  import { join } from 'node:path'
4
4
  import { acknowledgeMailbox, CAPTAIN_KEY, discardMailboxMessages, findTeamByCaptain, readMailbox, readUnreadMailbox, readTeam, sanitizeKey, withTeamLock } from './state.ts'
5
5
  import type { TeamMessage, TeamState } from './types.ts'
6
- import { sessionOwnEvents } from './harness-compat.ts'
6
+ import { sessionOwnEvents, successfulSubagentSettlement } from './harness-compat.ts'
7
7
  import { leadIdentityOfAsync, sessionLeadsTeamAsync } from './lineage.ts'
8
8
 
9
9
  const PREFIX = 'AgentTeams inbox receipt: '
@@ -80,8 +80,7 @@ export function installMailboxAdmission(ctx: Context, stateDir: string): void {
80
80
  // result. Keep abnormal endings and missing reports as fallback signals.
81
81
  const successfulSettlements = new Set(decision.messages.flatMap(input => {
82
82
  const source = input.source
83
- return source?.kind === 'subagent-settled'
84
- && source.summary === `Background subagent ${source.senderSessionId} finished and will do no further work unless you send it more.`
83
+ return successfulSubagentSettlement(source)
85
84
  ? [source.senderSessionId as string] : []
86
85
  }))
87
86
  const redundantSettlements = new Set<string>()
@@ -155,8 +154,7 @@ export function installMailboxAdmission(ctx: Context, stateDir: string): void {
155
154
  }
156
155
  const admitted = []
157
156
  for (const { input, receipt, batch } of inputs) {
158
- if (input.source?.kind === 'subagent-settled' && redundantSettlements.has(input.source.senderSessionId)
159
- && input.source.summary === `Background subagent ${input.source.senderSessionId} finished and will do no further work unless you send it more.`) continue
157
+ if (successfulSubagentSettlement(input.source) && redundantSettlements.has(input.source.senderSessionId)) continue
160
158
  if (receipt === undefined || batch === undefined || batch.failed === true) { admitted.push(input); continue }
161
159
  const messages = []
162
160
  for (const id of receipt.ids) {
package/src/members.ts CHANGED
@@ -20,7 +20,7 @@ import { createUserMessage, LlmError, ReasoningEffortId } from '@deepseek-ai/dsh
20
20
  import type { Session, SessionId } from '@deepseek-ai/dsh-session'
21
21
  import { randomUUID } from 'node:crypto'
22
22
  import { join } from 'node:path'
23
- import { agentTeamsSource, assertMemberModelSelection, observedSessionFormatVersion, outputLimitTurn, type SessionFormatBearer, guardSubagentCreation, installMemberModelSelection, startMember, usesManagedActivations, guardSubagentDelivery, installContinuableMemberSetup, memberToolFilter, queueMemberPrompt, restrictableToolNames, startMemberWithLenientFilter, steerMemberPrompt, sessionOwnEvents } from './harness-compat.ts'
23
+ import { agentTeamsSource, assertMemberModelSelection, memberModelSelectionPolicy, observedSessionFormatVersion, outputLimitTurn, type SessionFormatBearer, guardSubagentCreation, installMemberModelSelection, startMember, usesManagedActivations, guardSubagentDelivery, installContinuableMemberSetup, memberToolFilter, queueMemberPrompt, restrictableToolNames, startMemberWithLenientFilter, steerMemberPrompt, sessionOwnEvents } from './harness-compat.ts'
24
24
  import { markMailboxDelivered, appendMailbox, CAPTAIN_KEY, createMessage, readRetiredMemberIds, readTeamSync, readTeam, releaseMailboxDelivery, withTeamLock, writeTeam } from './state.ts'
25
25
  import { mailboxPrompt } from './mailbox.ts'
26
26
  import { nearestLiveLead } from './lineage.ts'
@@ -569,7 +569,7 @@ export async function resolveMemberLlmSelection(
569
569
  // catalogs. A named provider (explicit or configured) is authoritative — a
570
570
  // model it does not advertise is a hard error, never a silent switch — and a
571
571
  // model the caller named keeps that caller's route.
572
- const provider = composed.derivedProvider
572
+ const preferredProvider = composed.derivedProvider
573
573
  ? await resolveMemberModelOwner(ctx, currentProvider, composed.model.value, signal)
574
574
  : composed.provider.value
575
575
 
@@ -577,9 +577,34 @@ export async function resolveMemberLlmSelection(
577
577
  // captain's effort only on the same route; a changed route must resolve its
578
578
  // own default. Explicit effort still wins, while "default" forces that
579
579
  // target-default behavior even when the route did not change.
580
- const model = composed.model.value
580
+ let provider = preferredProvider
581
+ let model = composed.model.value
582
+ // The official subagent policy is the single source of truth for member
583
+ // routes. A configured/member-inherited route that falls outside the list is
584
+ // replaced by the first allowed route; an explicitly requested route is
585
+ // never silently re-routed and still fails the assertion below.
586
+ const policyRoutes = memberModelSelectionPolicy(ctx, captain.session)
587
+ const allowed = (candidate: { provider: string; model: string }): boolean => (
588
+ policyRoutes === undefined
589
+ || policyRoutes.some((route) => route.provider === candidate.provider && route.model === candidate.model)
590
+ )
591
+ const explicitRoute = composed.provider.source === 'request' || composed.model.source === 'request'
592
+ if (policyRoutes !== undefined && !allowed({ provider, model }) && !explicitRoute) {
593
+ const first = policyRoutes[0]
594
+ if (first !== undefined) {
595
+ provider = first.provider
596
+ model = first.model
597
+ }
598
+ }
581
599
  assertMemberModelSelection(ctx, captain, { provider, model })
582
- if (fallback !== undefined) assertMemberModelSelection(ctx, captain, fallback)
600
+ // Fallback is derived from the same allowlist: keep the configured route when
601
+ // it is allowed, otherwise pick another allowed route, and drop it when none
602
+ // exists. This removes the need to synchronise a static fallback in the
603
+ // profile by hand.
604
+ let effectiveFallback = fallback
605
+ if (policyRoutes !== undefined && fallback !== undefined && !allowed(fallback)) {
606
+ effectiveFallback = policyRoutes.find((candidate) => candidate.provider !== provider || candidate.model !== model)
607
+ }
583
608
  const sameRoute = provider === currentProvider && model === currentModel
584
609
  const reasoningEffort = explicitEffort === undefined
585
610
  ? sameRoute
@@ -607,7 +632,7 @@ export async function resolveMemberLlmSelection(
607
632
  ...resolved.reasoningEffort === undefined
608
633
  ? {}
609
634
  : { reasoningEffort: String(resolved.reasoningEffort) },
610
- ...fallback === undefined ? {} : { fallback },
635
+ ...effectiveFallback === undefined ? {} : { fallback: effectiveFallback },
611
636
  }
612
637
  }
613
638
 
@@ -1033,8 +1058,17 @@ export async function spawnMember(
1033
1058
  // mirror what startContinuable would reject, with an actionable error.
1034
1059
  const provider = ctx.subagents.getProvider(config.provider)
1035
1060
  if (provider === undefined) {
1061
+ // 0.2.2-rc.3 removed the public `list()`; the private registry still holds
1062
+ // the names, so read those when present and fall back to the old API.
1063
+ const boundary = ctx.subagents as unknown as {
1064
+ list?: () => readonly string[]
1065
+ providers?: Map<string, unknown>
1066
+ }
1067
+ const available = typeof boundary.list === 'function'
1068
+ ? boundary.list()
1069
+ : [...(boundary.providers?.keys?.() ?? [])]
1036
1070
  throw new Error(
1037
- `agent-teams: no subagent provider "${config.provider}" is registered (available: ${ctx.subagents.list().join(', ') || 'none'}) — `
1071
+ `agent-teams: no subagent provider "${config.provider}" is registered (available: ${available.join(', ') || 'none'}) — `
1038
1072
  + 'check that the subagent provider row (e.g. subagent-spawn) is mounted in the composition',
1039
1073
  )
1040
1074
  }
package/src/tools.ts CHANGED
@@ -16,7 +16,7 @@ import { createUserMessage } from '@deepseek-ai/dsh-llm'
16
16
  import type { SessionId } from '@deepseek-ai/dsh-session'
17
17
  import type { JsonValue } from '@deepseek-ai/dsh-util-values'
18
18
  import { defineTool } from '@deepseek-ai/dsh-tools'
19
- import type { ToolRunContext } from '@deepseek-ai/dsh-tools'
19
+ import type { ToolDefinition, ToolRunContext } from '@deepseek-ai/dsh-tools'
20
20
  import { join } from 'node:path'
21
21
  import { appendTeamEvent, captainSessionOf } from './events.ts'
22
22
  import {
@@ -116,6 +116,12 @@ export interface ToolsConfig {
116
116
  profiles: Record<string, import('./profiles.ts').TeamProfileConfig>
117
117
  /** Owner-declared reusable member tool policies, keyed by policy id (#59). */
118
118
  toolPolicies: Record<string, MemberToolPolicy>
119
+ /**
120
+ * Per-agent gate: the session's model-menu 「启用AgentTeam」 switch must be on
121
+ * for AgentTeams tools and prompt to participate. Omitted keeps the legacy
122
+ * always-on behavior for hosts without the native team-mode service.
123
+ */
124
+ isTeamEnabled?: (agent: Agent) => boolean
119
125
  }
120
126
 
121
127
  /** Browser/UI mutations allowed while a plan is waiting for approval. */
@@ -671,6 +677,12 @@ export function registerAgentTeamsTools(ctx: Context, config: ToolsConfig): Agen
671
677
  installMailboxAdmission(ctx, config.stateDir)
672
678
  const scheduler = installTeamScheduler(ctx, { stateDir: config.stateDir, executionPrompt: config.executionPrompt, dispatch: dispatchMember })
673
679
 
680
+ /** Step-time admission shared by every `agent_teams_*` tool. */
681
+ const teamEnabled = (agent: Agent | undefined): boolean =>
682
+ agent === undefined ? false : (config.isTeamEnabled?.(agent) ?? true)
683
+ const registerTool = (definition: ToolDefinition): (() => void) =>
684
+ ctx.tools.register(definition, { when: ({ agent }) => teamEnabled(agent) })
685
+
674
686
  async function dispatchMember(captain: Agent, teamId: string, memberName: string, text: string, signal: AbortSignal, mode: 'queue' | 'steer', attemptId?: string): Promise<boolean> {
675
687
  const root = stateRootOf(workspaceOf(captain), config)
676
688
  // Record why a member never started. The scheduler treats a failed dispatch as
@@ -941,7 +953,7 @@ export function registerAgentTeamsTools(ctx: Context, config: ToolsConfig): Agen
941
953
 
942
954
 
943
955
 
944
- ctx.tools.register(defineTool({
956
+ registerTool(defineTool({
945
957
  name: 'agent_teams_create',
946
958
  description: 'Create a team. Use approval=required for a two-phase plan: members and tasks remain unspawned/unclaimed until the user reviews the Web plan and explicitly approves it. Optional profiles expand their configured roster; seed profiles also expand template tasks, while captain profiles leave the graph for the Captain to design. approval=automatic preserves the legacy immediate-execution path.',
947
959
  parameters: {
@@ -1153,7 +1165,7 @@ export function registerAgentTeamsTools(ctx: Context, config: ToolsConfig): Agen
1153
1165
  },
1154
1166
  }))
1155
1167
 
1156
- ctx.tools.register(defineTool({
1168
+ registerTool(defineTool({
1157
1169
  name: 'agent_teams_edit_plan',
1158
1170
  description: 'Atomically revise an AgentTeams plan. While staged, edit tasks and roster without starting work. While running, only update_task is allowed, and only for pending tasks with no prior attempt: correct dependencies, assignees or descriptions before they start; newly ready work is scheduled after commit. Never edit active/finished attempts. Submit dependent edits in order. Never modify .agent-teams files directly.',
1159
1171
  parameters: {
@@ -1277,7 +1289,7 @@ export function registerAgentTeamsTools(ctx: Context, config: ToolsConfig): Agen
1277
1289
  },
1278
1290
  }))
1279
1291
 
1280
- ctx.tools.register(defineTool({
1292
+ registerTool(defineTool({
1281
1293
  name: 'agent_teams_approve',
1282
1294
  description: 'Approve and start a staged team plan. Call this only in response to an explicit user approval in a new user turn; never call it during the turn that created or edited the plan. The Web Approve & Run button uses the same runtime directly.',
1283
1295
  parameters: {
@@ -1309,7 +1321,7 @@ export function registerAgentTeamsTools(ctx: Context, config: ToolsConfig): Agen
1309
1321
  },
1310
1322
  }))
1311
1323
 
1312
- ctx.tools.register(defineTool({
1324
+ registerTool(defineTool({
1313
1325
  name: 'agent_teams_add_member',
1314
1326
  description: 'Add a member to the team roster. Planning and idle roster rows do not call a model. After approval, the member session starts with its first ready task or explicit message and remains durable for later work.',
1315
1327
  parameters: {
@@ -1413,7 +1425,7 @@ export function registerAgentTeamsTools(ctx: Context, config: ToolsConfig): Agen
1413
1425
  },
1414
1426
  }))
1415
1427
 
1416
- ctx.tools.register(defineTool({
1428
+ registerTool(defineTool({
1417
1429
  name: 'agent_teams_remove_member',
1418
1430
  description: 'Remove a member safely: revoke its current attempts, return all unfinished owned tasks to the shared pending pool, interrupt its live turn, and mark it removed.',
1419
1431
  parameters: {
@@ -1472,7 +1484,7 @@ export function registerAgentTeamsTools(ctx: Context, config: ToolsConfig): Agen
1472
1484
  },
1473
1485
  }))
1474
1486
 
1475
- ctx.tools.register(defineTool({
1487
+ registerTool(defineTool({
1476
1488
  name: 'agent_teams_create_task',
1477
1489
  description: 'Create a task in your team\'s task list. Use kind=work (default) for research, repository audits and general tasks. kind=review is only a quality gate for an existing implementation/repair task via reviewedTaskId. Every call must include a non-empty subject, including verification and review tasks. Tasks can depend on other tasks (dependencies): a task is only claimable once every dependency is completed. Optionally assign it to a member, who still claims it before working.',
1478
1490
  parameters: {
@@ -1630,7 +1642,7 @@ export function registerAgentTeamsTools(ctx: Context, config: ToolsConfig): Agen
1630
1642
  },
1631
1643
  }))
1632
1644
 
1633
- ctx.tools.register(defineTool({
1645
+ registerTool(defineTool({
1634
1646
  name: 'agent_teams_reassign_task',
1635
1647
  description: 'Atomically retry, reassign, or let the captain take over one ready unfinished/failed task. The old attempt is revoked before its member is interrupted, so late updates cannot overwrite the new owner. Use assignee="captain" only when you will finish that task in this turn; a captain can own only one unfinished takeover at a time, and an unfinished takeover returns to the member pool when the captain becomes idle.',
1636
1648
  parameters: {
@@ -1761,7 +1773,7 @@ export function registerAgentTeamsTools(ctx: Context, config: ToolsConfig): Agen
1761
1773
  },
1762
1774
  }))
1763
1775
 
1764
- ctx.tools.register(defineTool({
1776
+ registerTool(defineTool({
1765
1777
  name: 'agent_teams_claim_task',
1766
1778
  description: 'Members claim their own ready task or read their existing attempt_id. Captains must use reassign_task to assign and wake a member; claim_task does not dispatch work. A member cannot own a second unfinished task. The returned attempt_id is required for updates and becomes stale after retry/reassignment.',
1767
1779
  parameters: {
@@ -1868,7 +1880,7 @@ export function registerAgentTeamsTools(ctx: Context, config: ToolsConfig): Agen
1868
1880
  },
1869
1881
  }))
1870
1882
 
1871
- ctx.tools.register(defineTool({
1883
+ registerTool(defineTool({
1872
1884
  name: 'agent_teams_update_task',
1873
1885
  description: 'Update a task status/output. Members must supply the current attempt_id returned by claim_task; stale attempts are rejected after takeover/reassignment. Terminal results are immutable, but owners and the captain can append acceptanceResults/commandsRun/evidence_note as attributed supplemental evidence, without reclaiming or changing the verdict. A captain must use reassign_task(assignee="captain") before updating active member-owned work.',
1874
1886
  parameters: {
@@ -2094,7 +2106,7 @@ export function registerAgentTeamsTools(ctx: Context, config: ToolsConfig): Agen
2094
2106
  },
2095
2107
  }))
2096
2108
 
2097
- ctx.tools.register(defineTool({
2109
+ registerTool(defineTool({
2098
2110
  name: 'agent_teams_amend_task',
2099
2111
  description: 'Captain-only controlled contract amendment for one non-terminal quality task: replace a wrong objective/acceptance/verify/inScope/outOfScope when the original contract makes honest completion impossible (for example a verify command that cannot pass, or an inScope that forbids the file the objective names). The amendment is appended to the task\'s revisions ledger with previous values and the reason, and is rejected once a review/requirements task has passed judgment on this task. Members cannot amend contracts; the implementer re-reads the amended contract before its next quality gate. Lists are full replacements, not deltas.',
2100
2112
  parameters: {
@@ -2175,7 +2187,7 @@ export function registerAgentTeamsTools(ctx: Context, config: ToolsConfig): Agen
2175
2187
  },
2176
2188
  }))
2177
2189
 
2178
- ctx.tools.register(defineTool({
2190
+ registerTool(defineTool({
2179
2191
  name: 'agent_teams_send_message',
2180
2192
  description: 'Send coordination or current-task guidance directly to the captain or a teammate. A running recipient receives it at the next model step; an idle recipient wakes. Messages are durably retained until read. Use task creation/reassignment for a new unit of work, not repeated status nudges.',
2181
2193
  parameters: {
@@ -2310,7 +2322,7 @@ export function registerAgentTeamsTools(ctx: Context, config: ToolsConfig): Agen
2310
2322
  },
2311
2323
  }))
2312
2324
 
2313
- ctx.tools.register(defineTool({
2325
+ registerTool(defineTool({
2314
2326
  name: 'agent_teams_status',
2315
2327
  description: 'Team snapshot: members with live activity and tasks with status/assignee/dependencies/output. Captains also see every team mailbox; members see only their own inbox. Use after mailbox progress deliveries or for an explicit status request. After dispatch, end your turn while members work; do not repeatedly poll.',
2316
2328
  parameters: {},
@@ -2457,7 +2469,7 @@ export function registerAgentTeamsTools(ctx: Context, config: ToolsConfig): Agen
2457
2469
  },
2458
2470
  }))
2459
2471
 
2460
- ctx.tools.register(defineTool({
2472
+ registerTool(defineTool({
2461
2473
  name: 'agent_teams_resume',
2462
2474
  description: 'Explicitly resume a halted team. Requires a non-empty reason. Does not recreate cancelled tasks; only still-pending work is scheduled.',
2463
2475
  parameters: {
@@ -2509,7 +2521,7 @@ export function registerAgentTeamsTools(ctx: Context, config: ToolsConfig): Agen
2509
2521
  },
2510
2522
  }))
2511
2523
 
2512
- ctx.tools.register(defineTool({
2524
+ registerTool(defineTool({
2513
2525
  name: 'agent_teams_delete',
2514
2526
  description: 'End and archive your team: interrupts members and moves the current tasks and mailboxes out of active state for later inspection. Use when the work is done or explicitly abandoned. A same-name archive replaces its previous generation.',
2515
2527
  parameters: {},