@fish-under-sea/dsh-agent-teams-fish 1.0.2 → 2.0.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.
Files changed (179) hide show
  1. package/NOTICE.md +13 -7
  2. package/README.en.md +20 -12
  3. package/README.md +20 -12
  4. package/compatibility.json +82 -46
  5. package/icon.png +0 -0
  6. package/lib/artifacts.js +148 -25
  7. package/lib/client/ActivityPanel.js +26 -5
  8. package/lib/client/WorkspaceActivity.js +6 -4
  9. package/lib/client/activity-monitor.js +113 -41
  10. package/lib/client/locales.js +14 -0
  11. package/lib/client.js +433 -199
  12. package/lib/client.js.map +1 -1
  13. package/lib/command.js +7 -4
  14. package/lib/git-artifact-stamp.json +2 -2
  15. package/lib/harness-compat.js +120 -62
  16. package/lib/index.js +7 -10
  17. package/lib/mailbox.js +15 -5
  18. package/lib/members.js +221 -154
  19. package/lib/snapshot.js +15 -10
  20. package/lib/state.js +41 -8
  21. package/lib/tools.js +123 -64
  22. package/lib/types/artifacts.d.ts +6 -3
  23. package/lib/types/client/activity-monitor.d.ts +13 -4
  24. package/lib/types/client/locales.d.ts +14 -0
  25. package/lib/types/harness-compat.d.ts +63 -16
  26. package/lib/types/mailbox.d.ts +2 -0
  27. package/lib/types/members.d.ts +5 -17
  28. package/lib/types/snapshot.d.ts +12 -7
  29. package/lib/types/state.d.ts +10 -3
  30. package/lib/types/types.d.ts +5 -0
  31. package/lib/types/web-routes.d.ts +2 -0
  32. package/lib/types/workspace-audit-service.d.ts +35 -0
  33. package/lib/types/workspace-audit-worker.d.ts +1 -0
  34. package/lib/web-routes.js +31 -0
  35. package/lib/workspace-audit-service.js +165 -0
  36. package/lib/workspace-audit-worker.js +11 -0
  37. package/lib/workspace-audit.js +6 -5
  38. package/locale/en.json +6 -0
  39. package/locale/zh.json +6 -0
  40. package/package.json +69 -64
  41. package/pnpm-workspace.yaml +306 -273
  42. package/release-notes/v0.1.25.md +16 -0
  43. package/release-notes/v0.1.26.md +19 -0
  44. package/release-notes/v0.1.27.md +42 -0
  45. package/release-notes/v0.1.28.md +45 -0
  46. package/release-notes/v0.1.29.md +23 -0
  47. package/release-notes/v1.1.0.md +42 -0
  48. package/release-notes/v2.0.0.md +17 -0
  49. package/scripts/artwork-role-match.test.mjs +517 -0
  50. package/scripts/capabilities.test.mjs +301 -0
  51. package/scripts/check-install-channel.mjs +55 -0
  52. package/scripts/check-install-channel.test.mjs +39 -0
  53. package/scripts/clean-build.mjs +14 -0
  54. package/scripts/client-harness-migration.test.mjs +46 -0
  55. package/scripts/compatibility.mjs +20 -0
  56. package/scripts/compatibility.test.mjs +187 -0
  57. package/scripts/corrupt-teamjson.test.mjs +180 -0
  58. package/scripts/custom-artwork.test.mjs +273 -0
  59. package/scripts/fallback-tdd.mjs +61 -0
  60. package/scripts/fixtures/harness-benchmark-scope.mjs +16 -0
  61. package/scripts/fixtures/harness-benchmark-scope.test.mjs +18 -0
  62. package/scripts/fixtures/harness-complex-case.mjs +201 -0
  63. package/scripts/fixtures/harness-complex-case.test.mjs +21 -0
  64. package/scripts/fixtures/harness-complex-oracle.mjs +63 -0
  65. package/scripts/fixtures/harness-issue-case.mjs +51 -0
  66. package/scripts/fixtures/harness-issue159-case.mjs +28 -0
  67. package/scripts/fixtures/harness-model-case.mjs +127 -0
  68. package/scripts/fixtures/harness-model-case.test.mjs +37 -0
  69. package/scripts/fixtures/harness-model-driver.mjs +100 -0
  70. package/scripts/fixtures/harness-runtime-credentials.mjs +23 -0
  71. package/scripts/fixtures/harness-runtime-entry.mjs +171 -0
  72. package/scripts/fixtures/harness-runtime-idle.mjs +42 -0
  73. package/scripts/fixtures/harness-runtime-llm.mjs +193 -0
  74. package/scripts/fixtures/harness-runtime-protocol.mjs +187 -0
  75. package/scripts/fixtures/harness-runtime-resume.mjs +24 -0
  76. package/scripts/fixtures/harness-runtime-stability.mjs +282 -0
  77. package/scripts/fixtures/harness-runtime-tools.mjs +13 -0
  78. package/scripts/fixtures/harness-runtime-web-approval.mjs +341 -0
  79. package/scripts/fixtures/issue-336-audit-worker.mjs +18 -0
  80. package/scripts/git-artifacts.mjs +64 -0
  81. package/scripts/git-artifacts.test.mjs +32 -0
  82. package/scripts/harness-compat-tdd.mjs +492 -0
  83. package/scripts/harness-issue-verify.mjs +26 -0
  84. package/scripts/harness-model-benchmark.mjs +163 -0
  85. package/scripts/harness-runtime-platform.test.mjs +31 -0
  86. package/scripts/harness-runtime-scenarios.mjs +297 -0
  87. package/scripts/harness-runtime-verify.mjs +169 -0
  88. package/scripts/harness-source-verify.mjs +211 -0
  89. package/scripts/harness-source-verify.test.mjs +97 -0
  90. package/scripts/harness-validation.mjs +68 -0
  91. package/scripts/harness-validation.test.mjs +95 -0
  92. package/scripts/http-body.test.mjs +72 -0
  93. package/scripts/import-vendor-artwork.mjs +78 -0
  94. package/scripts/inline-plan-blank-optional-tdd.mjs +121 -0
  95. package/scripts/issue-159.test.mjs +78 -0
  96. package/scripts/issue-188.test.mjs +148 -0
  97. package/scripts/issue-189.test.mjs +100 -0
  98. package/scripts/issue-203-card.test.mjs +181 -0
  99. package/scripts/issue-205.test.mjs +163 -0
  100. package/scripts/issue-234.test.mjs +424 -0
  101. package/scripts/issue-236-stale-module.test.mjs +63 -0
  102. package/scripts/issue-236.test.mjs +59 -0
  103. package/scripts/issue-262.test.mjs +98 -0
  104. package/scripts/issue-336.test.mjs +404 -0
  105. package/scripts/legacy-session-source-repair.test.mjs +201 -0
  106. package/scripts/lifecycle-verify.mjs +1573 -0
  107. package/scripts/lineage-identity.test.mjs +77 -0
  108. package/scripts/member-failure-tdd.mjs +451 -0
  109. package/scripts/member-spawn-recovery.test.mjs +92 -0
  110. package/scripts/quality-gates-amend.test.mjs +161 -0
  111. package/scripts/quality-gates-content-bound.test.mjs +572 -0
  112. package/scripts/quality-gates-cross-binding.test.mjs +184 -0
  113. package/scripts/quality-gates-excluded-scope.test.mjs +163 -0
  114. package/scripts/quality-gates-repair-scope.test.mjs +143 -0
  115. package/scripts/quality-gates-repair-wiring.test.mjs +189 -0
  116. package/scripts/quality-gates-tdd.mjs +1238 -0
  117. package/scripts/quality-gates-work-order.test.mjs +494 -0
  118. package/scripts/readme-version.mjs +89 -0
  119. package/scripts/readme-version.test.mjs +77 -0
  120. package/scripts/release-metadata.mjs +45 -0
  121. package/scripts/release-metadata.test.mjs +66 -0
  122. package/scripts/scoped-release.test.mjs +52 -0
  123. package/scripts/stability-tdd.mjs +144 -0
  124. package/scripts/stress-verify.mjs +548 -0
  125. package/scripts/symlink-support.mjs +46 -0
  126. package/scripts/sync-skill.mjs +103 -0
  127. package/scripts/tool-policies.test.mjs +280 -0
  128. package/scripts/update-skills.mjs +105 -0
  129. package/scripts/update-skills.test.mjs +79 -0
  130. package/scripts/upgrade-status.mjs +66 -0
  131. package/scripts/upgrade-status.test.mjs +83 -0
  132. package/scripts/verify-package.mjs +73 -0
  133. package/scripts/verify.mjs +2199 -0
  134. package/scripts/web-routes-verify.mjs +142 -0
  135. package/scripts/workspace-activity.test.mjs +346 -0
  136. package/scripts/workspace-summary.test.mjs +49 -0
  137. package/src/artifacts.ts +487 -0
  138. package/src/artwork-source.ts +262 -0
  139. package/src/capabilities.ts +113 -0
  140. package/src/client/ActivityPanel.module.css +2390 -0
  141. package/src/client/ActivityPanel.tsx +1507 -0
  142. package/src/client/AgentTeamsCard.module.css +148 -0
  143. package/src/client/AgentTeamsCard.tsx +155 -0
  144. package/src/client/StagingPlanEditor.tsx +829 -0
  145. package/src/client/TeamChatEntry.tsx +27 -0
  146. package/src/client/WorkspaceActivity.module.css +41 -0
  147. package/src/client/WorkspaceActivity.tsx +137 -0
  148. package/src/client/activity-model.ts +372 -0
  149. package/src/client/activity-monitor.ts +440 -0
  150. package/src/client/agent-teams-card-definition.ts +250 -0
  151. package/src/client/artwork.ts +374 -0
  152. package/src/client/icons.tsx +17 -0
  153. package/src/client/index.tsx +140 -0
  154. package/src/client/locales.ts +481 -0
  155. package/src/client/panel-geometry.ts +194 -0
  156. package/src/client/session-navigation.ts +73 -0
  157. package/src/client/workspace-state.ts +52 -0
  158. package/src/command.ts +145 -0
  159. package/src/css-modules.d.ts +4 -0
  160. package/src/event-types.ts +177 -0
  161. package/src/events.ts +78 -0
  162. package/src/harness-compat.ts +570 -0
  163. package/src/index.ts +599 -0
  164. package/src/lineage.ts +248 -0
  165. package/src/mailbox.ts +185 -0
  166. package/src/members.ts +1230 -0
  167. package/src/profiles.ts +765 -0
  168. package/src/quality-gates.ts +2124 -0
  169. package/src/scheduler.ts +554 -0
  170. package/src/snapshot.ts +333 -0
  171. package/src/state.ts +1317 -0
  172. package/src/tool-names.ts +14 -0
  173. package/src/tool-policies.ts +219 -0
  174. package/src/tools.ts +2939 -0
  175. package/src/types.ts +414 -0
  176. package/src/web-routes.ts +128 -0
  177. package/src/workspace-audit-service.ts +182 -0
  178. package/src/workspace-audit-worker.ts +12 -0
  179. package/src/workspace-audit.ts +57 -0
package/src/members.ts ADDED
@@ -0,0 +1,1230 @@
1
+ /**
2
+ * Member subagent lifecycle: spawn a continuable child per member, deliver
3
+ * task turns and step-boundary messages, and observe its activity.
4
+ *
5
+ * Members are durable continuable subagents of the captain, so a member keeps
6
+ * its conversation across turns and across harness restarts: the captain
7
+ * queues its next turn through {@link deliverToMember}, it works through its turn
8
+ * (updating team state through the `agent_teams_*` tools), and becomes idle
9
+ * again. Its final assistant message is not readable programmatically, so the
10
+ * member persists its report into the captain's mailbox and the task records,
11
+ * which the captain reads through `agent_teams_status`.
12
+ * @module dsh-agent-teams/members
13
+ */
14
+
15
+ import type { Context } from '@deepseek-ai/cordis'
16
+ import { type Agent, type ModelSelection } from '@deepseek-ai/dsh-agent'
17
+ // Declaration merge only: makes ctx.subagents visible.
18
+ import { foldSubagentDescriptor } from '@deepseek-ai/dsh-subagent'
19
+ import { createUserMessage, LlmError, ReasoningEffortId } from '@deepseek-ai/dsh-llm'
20
+ import type { Session, SessionId } from '@deepseek-ai/dsh-session'
21
+ import { randomUUID } from 'node:crypto'
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'
24
+ import { markMailboxDelivered, appendMailbox, CAPTAIN_KEY, createMessage, readRetiredMemberIds, readTeamSync, readTeam, releaseMailboxDelivery, withTeamLock, writeTeam } from './state.ts'
25
+ import { mailboxPrompt } from './mailbox.ts'
26
+ import { nearestLiveLead } from './lineage.ts'
27
+ import { appendTeamEvent, captainSessionOf } from './events.ts'
28
+ import type { MemberToolFilter } from './tool-policies.ts'
29
+ import { TERMINAL_TASK_STATUSES, type TeamMember, type TeamState, type TeamTask } from './types.ts'
30
+
31
+ /** Persona snapshot of a profile protocol; the full text lives on team.json. */
32
+ export const PERSONA_PROTOCOL_MAX_CHARS = 400
33
+
34
+ /**
35
+ * The captain's own LLM route, for the panel's captain artwork.
36
+ *
37
+ * The captain is the owning session rather than a member, so its route has no
38
+ * other home in the team record. `requestHeader().config` is the route of the
39
+ * request currently being served; `options` covers a session that has not
40
+ * issued a request yet (for example a plan staged before the first model turn
41
+ * completes). Either half may be absent on a legacy host, and an empty half is
42
+ * omitted so the durable record keeps the packaged fallback instead of an
43
+ * unusable empty route.
44
+ * @param captain - the live captain agent.
45
+ * @returns the `captainProvider` / `captainModel` fields, or `{}` when unknown.
46
+ */
47
+ export function captainRouteOf(captain: Agent): { captainProvider?: string; captainModel?: string } {
48
+ const current = captain.session.requestHeader()?.config
49
+ const provider = (current?.provider ?? captain.options.provider)?.trim() ?? ''
50
+ const model = (current?.model ?? captain.options.model)?.trim() ?? ''
51
+ return {
52
+ ...provider === '' ? {} : { captainProvider: provider },
53
+ ...model === '' ? {} : { captainModel: model },
54
+ }
55
+ }
56
+
57
+ /**
58
+ * Restore the SessionId brand on a value that round-tripped through the
59
+ * durable team file. The brand is erased by JSON serialization; the value
60
+ * originated from `startContinuable`/`agent.id`, so this cast is the boundary
61
+ * restoration, not a new assertion.
62
+ */
63
+ function brandedSessionId(value: string): SessionId {
64
+ return value as SessionId
65
+ }
66
+
67
+ /** Runtime knobs for member spawning, resolved from plugin config. */
68
+ export interface MemberRuntimeConfig {
69
+ /** Registered `ctx.subagents` provider name (must support continuable + persona). */
70
+ provider: string
71
+ /** Child delegation depth cap (0 forbids delegation entirely). */
72
+ maxDepth?: number
73
+ /** Plugin-wide execution prompt. */
74
+ executionPrompt?: string
75
+ /** Plugin-wide fallback route. */
76
+ fallback?: { provider: string; model: string }
77
+ }
78
+
79
+ /** Durable provider/model/reasoning snapshot for one member. */
80
+ export interface MemberLlmSelection {
81
+ /** Registered LLM provider route. */
82
+ provider: string
83
+ /** Provider-owned model id. */
84
+ model: string
85
+ /** Adapter-owned reasoning effort, absent when the target has no explicit/default effort. */
86
+ reasoningEffort?: string
87
+ /** Configured second-choice route. */
88
+ fallback?: { provider: string; model: string }
89
+ }
90
+
91
+ /** Optional member-level route requested by the captain. */
92
+ export interface MemberLlmSelectionRequest {
93
+ /** Explicit LLM provider route; requires an explicit model. */
94
+ provider?: string
95
+ /** Explicit model id; otherwise the plugin default or captain model is used. */
96
+ model?: string
97
+ /** Plugin-level member model default. */
98
+ defaultModel?: string
99
+ /** Configured member LLM provider, paired with `defaultModel` (issue #189). */
100
+ defaultProvider?: string
101
+ /** Explicit reasoning effort; "default" selects the target model's default effort. */
102
+ reasoningEffort?: string
103
+ /** Configured fallback route. */
104
+ fallback?: { provider: string; model: string }
105
+ }
106
+
107
+ /** A composed member route plus where each half came from. */
108
+ export interface MemberRouteResolution {
109
+ readonly provider: { readonly value: string; readonly source: 'request' | 'config' | 'captain' }
110
+ readonly model: { readonly value: string; readonly source: 'request' | 'config' | 'captain' }
111
+ /**
112
+ * Whether the provider half was *derived* rather than named. Only a
113
+ * model-only plugin default may have its owner looked up in the provider
114
+ * catalogs; a provider or model the caller named is never re-pointed.
115
+ */
116
+ readonly derivedProvider: boolean
117
+ }
118
+
119
+ /**
120
+ * Compose one member route from request, plugin configuration and the captain
121
+ * session, without performing any I/O. This is the single place where the
122
+ * precedence between the captain's route and a configured member default is
123
+ * decided, so a configured model can never be silently paired with whichever
124
+ * provider the captain happens to sit on (issue #189).
125
+ *
126
+ * Precedence: explicit request > plugin configuration > captain session. Model
127
+ * ids are used verbatim: a `/` inside a model id is part of that id and is
128
+ * never treated as a provider separator.
129
+ *
130
+ * `derivedProvider` is true only for a bare configured `memberModel` with no
131
+ * provider anywhere, which is the one shape whose owner must come from the
132
+ * provider catalogs.
133
+ * @param request - the captain-supplied and plugin-configured route halves.
134
+ * @param captain - the captain's current session route.
135
+ * @returns the composed route, or `undefined` when a half cannot be determined.
136
+ */
137
+ export function composeMemberRoute(
138
+ request: Pick<MemberLlmSelectionRequest, 'provider' | 'model' | 'defaultModel' | 'defaultProvider'>,
139
+ captain: { readonly provider: string; readonly model: string },
140
+ ): MemberRouteResolution | undefined {
141
+ const explicitProvider = request.provider?.trim()
142
+ const explicitModel = request.model?.trim()
143
+ const configuredModel = request.defaultModel?.trim()
144
+ const configuredProvider = request.defaultProvider?.trim()
145
+ if (explicitProvider !== undefined && explicitModel === undefined) return undefined
146
+ if (explicitProvider === '' || explicitModel === '' || configuredModel === '' || configuredProvider === '') return undefined
147
+
148
+ const providerValue = explicitProvider ?? configuredProvider ?? captain.provider
149
+ const providerSource = explicitProvider !== undefined ? 'request' as const : configuredProvider !== undefined ? 'config' as const : 'captain' as const
150
+ const modelValue = explicitModel ?? configuredModel ?? captain.model
151
+ const modelSource = explicitModel !== undefined ? 'request' as const : configuredModel !== undefined ? 'config' as const : 'captain' as const
152
+ return {
153
+ provider: { value: providerValue, source: providerSource },
154
+ model: { value: modelValue, source: modelSource },
155
+ // A named provider is authoritative, and a named model keeps the route the
156
+ // caller asked for. Only a model-only plugin default is allowed to have its
157
+ // owner discovered from the catalogs.
158
+ derivedProvider: providerSource === 'captain' && modelSource === 'config',
159
+ }
160
+ }
161
+
162
+ /** Process-local bridge between spawn admission and synchronous child setup. */
163
+ export interface MemberSelectionRuntime {
164
+ /** Trusted fresh-child admission, before the durable member id is written. */
165
+ isPendingMember(agent: Agent): boolean
166
+ /** Make one selection visible while Harness materializes the fresh child. */
167
+ withPending<T>(
168
+ parentSessionId: string,
169
+ label: string,
170
+ selection: MemberLlmSelection,
171
+ operation: () => Promise<T>,
172
+ setup?: TeamMember['runtimeSetup'],
173
+ ): Promise<T>
174
+ }
175
+
176
+ /**
177
+ * Validate a resolved roster against every provider catalog before any child
178
+ * session is created. Catalogs are advisory when empty (some adapters accept
179
+ * dynamic model ids), but a non-empty catalog is authoritative enough to
180
+ * catch a typo that would otherwise boot a child and fail on its first turn.
181
+ */
182
+ export async function validateMemberLlmSelections(
183
+ ctx: Context,
184
+ selections: readonly MemberLlmSelection[],
185
+ signal?: AbortSignal,
186
+ ): Promise<void> {
187
+ const catalogs = new Map<string, Awaited<ReturnType<typeof ctx.llm.listModels>>>()
188
+ for (const selection of selections) {
189
+ if (signal?.aborted === true) throw signal.reason ?? new Error('member model validation was cancelled')
190
+ let catalog = catalogs.get(selection.provider)
191
+ if (catalog === undefined) {
192
+ catalog = await ctx.llm.listModels(selection.provider)
193
+ catalogs.set(selection.provider, catalog)
194
+ }
195
+ if (catalog.length === 0 || catalog.some((model) => model.id === selection.model)) continue
196
+ const available = catalog.slice(0, 8).map((model) => model.id).join(', ')
197
+ throw new Error(
198
+ `unknown member model "${selection.model}" for provider "${selection.provider}"`
199
+ + `${available === '' ? '' : ` (available: ${available}${catalog.length > 8 ? ', …' : ''})`}`,
200
+ )
201
+ }
202
+ }
203
+
204
+ const MEMBER_LABEL_PREFIX = 'agent-teams:'
205
+ const FALLBACK_FAILURE_CODES = new Set([
206
+ 'QUOTA', 'RATE_LIMIT', 'AUTH', 'MISSING_CREDENTIAL', 'NO_ADAPTER',
207
+ // The account-backed DeepSeek adapter remaps equivalent provider failures.
208
+ 'ACCOUNT_QUOTA', 'ACCOUNT_TOKEN_INVALID', 'ACCOUNT_SIGN_IN_REQUIRED',
209
+ ])
210
+
211
+ export function isFallbackFailureCode(code: string): boolean {
212
+ return FALLBACK_FAILURE_CODES.has(code)
213
+ }
214
+
215
+ /** Pure state transition used by the request-error handler and TDD tests. */
216
+ export function selectFallbackRoute(
217
+ current: { provider: string; model: string },
218
+ fallback: { provider: string; model: string } | undefined,
219
+ failureCode: string,
220
+ alreadySwitched: boolean,
221
+ ): { retry: boolean; switched: boolean; selection: { provider: string; model: string } } {
222
+ if (alreadySwitched || fallback === undefined || !isFallbackFailureCode(failureCode)) {
223
+ return { retry: false, switched: alreadySwitched, selection: current }
224
+ }
225
+ return { retry: true, switched: true, selection: fallback }
226
+ }
227
+
228
+ /** Deliver a durable member report to the live captain at its next model step. */
229
+ export function steerCaptainReport(captain: Pick<Agent, 'steer'> & SessionFormatBearer, from: string, content: string, receipt?: string): boolean {
230
+ try {
231
+ captain.steer(createUserMessage({
232
+ content: [{ type: 'text', text: receipt ?? `AgentTeams message from member ${from}:\n\n${content}` }],
233
+ source: agentTeamsSource({ kind: 'agent-teams' }, observedSessionFormatVersion(captain)),
234
+ }))
235
+ return true
236
+ } catch {
237
+ return false
238
+ }
239
+ }
240
+
241
+ interface FailedMemberAttempt {
242
+ readonly captainSessionId: string
243
+ readonly memberId: string
244
+ readonly task?: Pick<TeamTask, 'id' | 'attempt' | 'attemptId'>
245
+ readonly openAttemptOnly?: boolean
246
+ }
247
+
248
+ /** How a final member turn failure relates to the durable record. */
249
+ export type MemberFailureDisposition =
250
+ /** A live observed attempt was failed and its task marked failed. */
251
+ | 'failed_attempt'
252
+ /** The work had already settled; only a durable captain note was added. */
253
+ | 'noted_settled'
254
+ /** No record: stale generation, superseded attempt, retired member, or no team. */
255
+ | 'ignored'
256
+
257
+ /**
258
+ * Classify a final member turn failure against the durable record. Pure, so the
259
+ * policy is testable without a lock or a Harness.
260
+ *
261
+ * A failure may only mutate the attempt the plugin actually observed. When that
262
+ * attempt is gone — the member moved on to newer work, the task was
263
+ * reassigned to a newer attempt, or the member generation was replaced — the
264
+ * late error carries no authority and stays silent. When the failure belongs to
265
+ * the current generation but its work already settled, the task and member are
266
+ * left exactly as they are and only a durable captain note is added: otherwise
267
+ * an operator cannot tell a clean run from one whose member's last turn died
268
+ * (429, auth failure, crash) after the delivery landed (issue #205).
269
+ * @param observed - the live member/task capability captured at the error event.
270
+ * @param current - the current durable member record and open task, if any.
271
+ * @returns the disposition for this failure.
272
+ */
273
+ export function classifyMemberFailure(
274
+ observed: FailedMemberAttempt,
275
+ current: {
276
+ readonly member?: Pick<TeamMember, 'id' | 'status'> | undefined
277
+ readonly task?: Pick<TeamTask, 'id' | 'attempt' | 'attemptId'> | undefined
278
+ /** The durable record of the task the observation referred to, settled or not. */
279
+ readonly observedRecord?: Pick<TeamTask, 'id' | 'status' | 'subject'> | undefined
280
+ },
281
+ ): MemberFailureDisposition {
282
+ const member = current.member
283
+ // Only the exact member generation observed at the error event may report it.
284
+ // A replaced generation (same name, new session id) or a member record that is
285
+ // gone cannot be failed by that child's late error.
286
+ if (member === undefined || member.id !== observed.memberId) return 'ignored'
287
+ const task = current.task
288
+ if (task === undefined) {
289
+ if (observed.openAttemptOnly === true) return 'ignored'
290
+ // No open attempt is owned by this generation any more, so nothing here may
291
+ // be mutated — but the failure itself must still be recorded. `working` is
292
+ // NOT evidence of newer work: `syncMemberStatus` writes it as soon as the
293
+ // turn runs, while a task completed earlier in that same turn leaves no open
294
+ // attempt behind (the reporter's run A). Only a *concrete* superseded open
295
+ // attempt — the branch below — or a replaced generation may stay silent.
296
+ return 'noted_settled'
297
+ }
298
+ if (task.id !== observed.task?.id || task.attemptId !== observed.task?.attemptId
299
+ || task.attempt !== observed.task?.attempt) return 'ignored'
300
+ return 'failed_attempt'
301
+ }
302
+
303
+ /**
304
+ * The surviving durable record of the capability observed at the error event,
305
+ * or `undefined` when there is nothing honest to say about it.
306
+ *
307
+ * A task is only described as *settled* when its durable status is terminal
308
+ * (`completed`/`failed`/`cancelled`). A non-terminal record — for example a task
309
+ * that was claimed and then unclaimed or reassigned while the error was queued —
310
+ * must fall back to the plain "no open attempt" wording instead of implying a
311
+ * delivery landed.
312
+ */
313
+ export function settledTaskRecord(
314
+ observed: Pick<TeamTask, 'id'> | undefined,
315
+ tasks: readonly Pick<TeamTask, 'id' | 'status' | 'subject'>[],
316
+ ): Pick<TeamTask, 'id' | 'status' | 'subject'> | undefined {
317
+ if (observed === undefined) return undefined
318
+ const record = tasks.find(candidate => candidate.id === observed.id)
319
+ if (record === undefined) return undefined
320
+ return TERMINAL_TASK_STATUSES.includes(record.status) ? record : undefined
321
+ }
322
+
323
+ /**
324
+ * Build the durable captain note for one recorded failure. Pure, so the wording
325
+ * boundaries are testable without a lock or a Harness.
326
+ * @param memberName - the member that failed.
327
+ * @param summary - the failure message plus its code.
328
+ * @param disposition - what the failure was allowed to do.
329
+ * @param task - the open attempt that was failed, when there was one.
330
+ * @param settledRecord - the terminal record of the observed task, when it exists.
331
+ * @returns the exact message the captain will read.
332
+ */
333
+ export function memberFailureMessage(
334
+ memberName: string,
335
+ summary: string,
336
+ disposition: MemberFailureDisposition,
337
+ task: Pick<TeamTask, 'id' | 'subject'> | undefined,
338
+ settledRecord: Pick<TeamTask, 'id' | 'status' | 'subject'> | undefined,
339
+ ): string {
340
+ const head = `Member "${memberName}" hit an unrecoverable turn failure: ${summary}.`
341
+ if (disposition === 'failed_attempt' && task !== undefined) {
342
+ return `${head} Task ${task.id} ("${task.subject}") was marked failed; reassign it or retry when ready.`
343
+ }
344
+ if (settledRecord === undefined) {
345
+ return disposition === 'noted_settled'
346
+ ? `${head} No open attempt was owned; no task state was changed.`
347
+ : `${head} No open attempt was owned.`
348
+ }
349
+ // Only a completed record supports a claim about delivered work. A failed or
350
+ // cancelled record is described by its actual closed state.
351
+ return settledRecord.status === 'completed'
352
+ ? `${head} Task ${settledRecord.id} ("${settledRecord.subject}") had already completed; its state and output were left unchanged. This member's last turn died after its work landed.`
353
+ : `${head} Task ${settledRecord.id} ("${settledRecord.subject}") was already closed as ${settledRecord.status}; its record was left unchanged. This member's last turn died after that task had closed.`
354
+ }
355
+
356
+ /** Record a final turn failure, never an intermediate request retry. */
357
+ export async function failMemberOpenAttempt(
358
+ ctx: Context,
359
+ stateRoot: string,
360
+ teamId: string,
361
+ memberName: string,
362
+ failure: { readonly code: string; readonly message: string },
363
+ fallbackSession: Session,
364
+ observed: FailedMemberAttempt,
365
+ ): Promise<boolean> {
366
+ const summary = `${failure.message} (code ${failure.code})`
367
+ const lockKey = `team:${stateRoot}:${teamId}`
368
+ const prepared = await withTeamLock(lockKey, async () => {
369
+ const team = await readTeam(stateRoot, teamId)
370
+ if (team === undefined || team.halted === true || team.captainSessionId !== observed.captainSessionId) return
371
+ const member = team.members.find(candidate => candidate.name === memberName && candidate.id === observed.memberId)
372
+ const task = team.tasks.find(candidate => candidate.assignee === memberName
373
+ && (candidate.status === 'claimed' || candidate.status === 'in_progress'))
374
+ // A reassign, completion, or recreated member may win the lock while the
375
+ // final error is queued. Only the capability observed at that event may fail.
376
+ const disposition = classifyMemberFailure(observed, {
377
+ member,
378
+ task,
379
+ observedRecord: observed.task === undefined
380
+ ? undefined
381
+ : team.tasks.find(candidate => candidate.id === observed.task!.id),
382
+ })
383
+ if (disposition === 'ignored') return
384
+ if (disposition === 'failed_attempt' && task !== undefined) {
385
+ // Historical records may lack a capability id. Bind this failure report
386
+ // to the terminal attempt so a later retry invalidates unread mail.
387
+ if (observed.openAttemptOnly === true) task.attemptId ??= randomUUID()
388
+ task.status = 'failed'
389
+ task.output = summary
390
+ task.updatedAt = Date.now()
391
+ }
392
+ if (member !== undefined && ctx.agents.get(brandedSessionId(member.id))?.status !== 'running') member.status = 'idle'
393
+ // Only a terminal record of the observed task may be described, and only a
394
+ // completed one supports a claim about delivered work. Anything else — a
395
+ // never-assigned member, or a record left pending/claimed while the error was
396
+ // queued — gets the plain "no open attempt" wording.
397
+ const settledRecord = disposition === 'noted_settled'
398
+ ? settledTaskRecord(observed.task, team.tasks)
399
+ : undefined
400
+ const message = {
401
+ ...createMessage(memberName, CAPTAIN_KEY, memberFailureMessage(memberName, summary, disposition, task, settledRecord)),
402
+ ...observed.openAttemptOnly === true && task?.attemptId !== undefined
403
+ ? { sourceTaskId: task.id, sourceAttemptId: task.attemptId, sourceTaskStatus: 'failed' as const }
404
+ : {},
405
+ deliveryClaimedAt: Date.now(),
406
+ }
407
+ if (disposition === 'failed_attempt') await writeTeam(stateRoot, team)
408
+ await appendMailbox(stateRoot, team.id, CAPTAIN_KEY, message)
409
+ if (disposition === 'failed_attempt' && task !== undefined) {
410
+ appendTeamEvent(ctx, captainSessionOf(ctx, team.captainSessionId, fallbackSession), 'agent-teams/task-updated', {
411
+ teamId, taskId: task.id, status: task.status, assignee: memberName, output: task.output,
412
+ })
413
+ }
414
+ appendTeamEvent(ctx, captainSessionOf(ctx, team.captainSessionId, fallbackSession), 'agent-teams/message-sent', {
415
+ teamId: team.id,
416
+ messageId: message.id,
417
+ from: memberName,
418
+ to: CAPTAIN_KEY,
419
+ content: message.content,
420
+ ts: message.ts,
421
+ })
422
+ return { captainSessionId: team.captainSessionId, message }
423
+ })
424
+ if (prepared === undefined) return false
425
+ // Use the same lease/acknowledgment contract as send_message, outside the
426
+ // team lock: steering can synchronously start another agent turn.
427
+ const captain = nearestLiveLead(ctx, { captainSessionId: prepared.captainSessionId })
428
+ const delivered = captain !== undefined && steerCaptainReport(captain, memberName, prepared.message.content, mailboxPrompt(teamId, CAPTAIN_KEY, [prepared.message]))
429
+ await withTeamLock(lockKey, () => delivered
430
+ ? markMailboxDelivered(stateRoot, teamId, CAPTAIN_KEY, [prepared.message.id])
431
+ : releaseMailboxDelivery(stateRoot, teamId, CAPTAIN_KEY, [prepared.message.id]))
432
+ return true
433
+ }
434
+
435
+ async function commitFallbackRoute(
436
+ stateRoot: string,
437
+ teamId: string,
438
+ memberName: string,
439
+ child: Agent,
440
+ fallback: { provider: string; model: string },
441
+ signal: AbortSignal,
442
+ ctx: Context,
443
+ activate: () => void,
444
+ ): Promise<boolean> {
445
+ return withTeamLock(`team:${stateRoot}:${teamId}`, async () => {
446
+ const team = await readTeam(stateRoot, teamId)
447
+ if (signal.aborted || team === undefined || team.captainSessionId !== child.session.header.parentSession || team.halted === true) return false
448
+ const member = team.members.find(candidate => candidate.name === memberName && candidate.id === child.id)
449
+ if (member === undefined || member.status === 'removed' || member.stopping === true) return false
450
+ member.activeProvider = fallback.provider
451
+ member.activeModel = fallback.model
452
+ member.fallbackActive = true
453
+ let committed = false
454
+ const onCommit = (): void => {
455
+ committed = true
456
+ activate()
457
+ }
458
+ try {
459
+ await writeTeam(stateRoot, team, { signal, onCommit })
460
+ } catch (error: unknown) {
461
+ if (committed) throw error
462
+ ctx.logger.warn(`agent-teams: failed to persist fallback route: ${String(error)}`)
463
+ if (!signal.aborted) onCommit()
464
+ }
465
+ return committed
466
+ })
467
+ }
468
+
469
+ function pendingSelectionKey(parentSessionId: string, label: string): string {
470
+ return `${parentSessionId}\u0000${label}`
471
+ }
472
+
473
+ function selectionFromMember(member: TeamMember | undefined): MemberLlmSelection | undefined {
474
+ if (member?.provider === undefined || member.model === undefined) return undefined
475
+ const provider = (member.activeProvider ?? member.provider).trim()
476
+ const model = (member.activeModel ?? member.model).trim()
477
+ if (provider === '' || model === '') return undefined
478
+ // Effort ids belong to the original model. After a fallback, its own
479
+ // provider default remains authoritative, including after cold recovery.
480
+ const reasoningEffort = member.fallbackActive === true ? undefined : member.reasoningEffort?.trim()
481
+ return {
482
+ provider,
483
+ model,
484
+ ...reasoningEffort === undefined || reasoningEffort === '' ? {} : { reasoningEffort },
485
+ ...member.fallback === undefined || member.fallbackActive === true ? {} : { fallback: member.fallback },
486
+ }
487
+ }
488
+
489
+ function modelSelection(selection: MemberLlmSelection): ModelSelection {
490
+ return {
491
+ provider: selection.provider,
492
+ model: selection.model,
493
+ ...selection.reasoningEffort === undefined
494
+ ? {}
495
+ : { reasoningEffort: ReasoningEffortId(selection.reasoningEffort) },
496
+ }
497
+ }
498
+
499
+ /**
500
+ * Resolve one member's complete model selection. Ordinary members snapshot the
501
+ * captain's current request route and reasoning effort. When provider or model
502
+ * changes, effort is intentionally omitted so the target model materializes
503
+ * its own default instead of receiving an adapter-owned id from another route.
504
+ * An explicit effort overrides either policy; the sentinel "default" also
505
+ * selects the target model's default. The final effort is validated against
506
+ * the target model before a child is created.
507
+ *
508
+ * A configured `memberModel` is a route preference, not a blind model-id
509
+ * override: it is paired with `memberLlmProvider` (or its own `provider/model`
510
+ * form) when configured, and when only a bare model id is configured it is
511
+ * adopted by the captain's provider only if that provider actually advertises
512
+ * it. Otherwise the catalog decides: exactly one advertising provider wins,
513
+ * none or several produce an actionable error listing them (issue #189). A
514
+ * provider the caller *named* — explicitly or via configuration — is never
515
+ * silently switched away from.
516
+ */
517
+ export async function resolveMemberLlmSelection(
518
+ ctx: Context,
519
+ captain: Agent,
520
+ request: MemberLlmSelectionRequest,
521
+ signal?: AbortSignal,
522
+ ): Promise<MemberLlmSelection> {
523
+ const explicitProvider = request.provider?.trim()
524
+ const explicitModel = request.model?.trim()
525
+ const defaultModel = request.defaultModel?.trim()
526
+ const defaultProvider = request.defaultProvider?.trim()
527
+ const explicitEffort = request.reasoningEffort?.trim()
528
+ const fallback = request.fallback
529
+ if (request.provider !== undefined && explicitProvider === '') {
530
+ throw new Error('member LLM provider must not be empty')
531
+ }
532
+ if (request.model !== undefined && explicitModel === '') {
533
+ throw new Error('member model must not be empty')
534
+ }
535
+ if (request.defaultModel !== undefined && defaultModel === '') {
536
+ throw new Error('configured memberModel must not be empty')
537
+ }
538
+ if (request.defaultProvider !== undefined && defaultProvider === '') {
539
+ throw new Error('configured memberLlmProvider must not be empty')
540
+ }
541
+ if (request.reasoningEffort !== undefined && explicitEffort === '') {
542
+ throw new Error('member reasoning effort must not be empty')
543
+ }
544
+ // An explicit provider needs an explicit model; `memberModel` is used
545
+ // verbatim, so a `/` inside a model id is never a provider separator.
546
+ if (explicitProvider !== undefined && explicitModel === undefined) {
547
+ throw new Error('an explicit member LLM provider requires an explicit member model')
548
+ }
549
+
550
+ const current = captain.session.requestHeader()?.config
551
+ const currentProvider = current?.provider ?? captain.options.provider
552
+ const currentModel = current?.model ?? captain.options.model
553
+ if (currentProvider === undefined || currentModel === undefined) {
554
+ throw new Error('cannot resolve the member LLM route from the current captain session')
555
+ }
556
+ // The plugin-wide default only applies where the caller did not choose a
557
+ // model. `request.defaultModel` belongs to the plugin configuration; a
558
+ // request-level `model` is a user choice and is never re-routed.
559
+ const composed = composeMemberRoute({
560
+ provider: request.provider,
561
+ model: request.model,
562
+ defaultModel: defaultModel,
563
+ defaultProvider: defaultProvider,
564
+ }, { provider: currentProvider, model: currentModel })
565
+ if (composed === undefined) {
566
+ throw new Error('cannot resolve the member LLM route from the current captain session')
567
+ }
568
+ // Only a bare configured `memberModel` may have its owner resolved from the
569
+ // catalogs. A named provider (explicit or configured) is authoritative — a
570
+ // model it does not advertise is a hard error, never a silent switch — and a
571
+ // model the caller named keeps that caller's route.
572
+ const provider = composed.derivedProvider
573
+ ? await resolveMemberModelOwner(ctx, currentProvider, composed.model.value, signal)
574
+ : composed.provider.value
575
+
576
+ // Effort ids belong to one exact provider/model capability. Preserve the
577
+ // captain's effort only on the same route; a changed route must resolve its
578
+ // own default. Explicit effort still wins, while "default" forces that
579
+ // target-default behavior even when the route did not change.
580
+ const model = composed.model.value
581
+ assertMemberModelSelection(ctx, captain, { provider, model })
582
+ if (fallback !== undefined) assertMemberModelSelection(ctx, captain, fallback)
583
+ const sameRoute = provider === currentProvider && model === currentModel
584
+ const reasoningEffort = explicitEffort === undefined
585
+ ? sameRoute
586
+ ? current?.reasoningEffort
587
+ : undefined
588
+ : explicitEffort === 'default'
589
+ ? undefined
590
+ : ReasoningEffortId(explicitEffort)
591
+ let resolved: Awaited<ReturnType<typeof ctx.llm.resolveCallConfig>>
592
+ try {
593
+ resolved = await ctx.llm.resolveCallConfig({
594
+ provider,
595
+ model,
596
+ ...reasoningEffort === undefined
597
+ ? {}
598
+ : { reasoningEffort },
599
+ }, signal)
600
+ } catch (error: unknown) {
601
+ throw new Error(describeMemberRouteFailure(provider, model, error), { cause: error })
602
+ }
603
+ assertMemberModelSelection(ctx, captain, resolved)
604
+ return {
605
+ provider: resolved.provider,
606
+ model: resolved.model,
607
+ ...resolved.reasoningEffort === undefined
608
+ ? {}
609
+ : { reasoningEffort: String(resolved.reasoningEffort) },
610
+ ...fallback === undefined ? {} : { fallback },
611
+ }
612
+ }
613
+
614
+ /**
615
+ * Pick the provider that owns a configured bare model id when the captain's
616
+ * provider does not advertise it. Only an unambiguous owner is accepted: zero
617
+ * advertising providers and several advertising providers both fail with the
618
+ * catalog, because guessing between real providers changes which account and
619
+ * quota the user's members run on (issue #189).
620
+ * @returns the resolved provider id.
621
+ */
622
+ async function resolveMemberModelOwner(
623
+ ctx: Context,
624
+ captainProvider: string,
625
+ model: string,
626
+ signal?: AbortSignal,
627
+ ): Promise<string> {
628
+ // Enumeration is optional: an adapter that cannot list its providers must not
629
+ // turn a resolvable route into a crash. Such a route keeps the captain's
630
+ // provider and lets the durable adapter report the real failure.
631
+ const listProviders = ctx.llm.listProviders
632
+ if (typeof listProviders !== 'function') return captainProvider
633
+ const owners: string[] = []
634
+ for (const provider of listProviders.call(ctx.llm)) {
635
+ if (signal?.aborted === true) throw signal.reason ?? new Error('member model resolution was cancelled')
636
+ const catalog = await ctx.llm.listModels(provider.id)
637
+ if (catalog.length === 0) continue
638
+ if (catalog.some((candidate) => candidate.id === model)) owners.push(provider.id)
639
+ }
640
+ if (owners.includes(captainProvider)) return captainProvider
641
+ if (owners.length === 1) return owners[0]!
642
+ if (owners.length === 0) {
643
+ throw new Error(
644
+ `no configured provider advertises the member model "${model}".`
645
+ + ` The captain's provider "${captainProvider}" does not serve it either.`
646
+ + ' Name the owner explicitly with memberLlmProvider, or pass provider + model to agent_teams_add_member.',
647
+ )
648
+ }
649
+ throw new Error(
650
+ `the member model "${model}" is advertised by ${owners.length} providers (${owners.join(', ')}),`
651
+ + ' so its owner is ambiguous. Name it explicitly with memberLlmProvider, or pass provider + model to agent_teams_add_member.',
652
+ )
653
+ }
654
+
655
+ /** Turn a raw adapter failure into an actionable, route-naming error. */
656
+ function describeMemberRouteFailure(provider: string, model: string, error: unknown): string {
657
+ const message = error instanceof Error ? error.message : String(error)
658
+ const code = typeof error === 'object' && error !== null && 'code' in error ? String((error as { code: unknown }).code) : ''
659
+ const hint = code === 'UNKNOWN_MODEL' || code === 'NO_ADAPTER' || code === 'INVALID_CONFIG'
660
+ ? ` The member route was composed from the captain's session and the plugin configuration;`
661
+ + ' set memberLlmProvider when the configured member model belongs to a'
662
+ + " different provider than the captain's session."
663
+ : ''
664
+ return `cannot use the member LLM route "${provider}/${model}": ${message}${code === '' ? '' : ` (code ${code})`}.${hint}`
665
+ }
666
+
667
+ /**
668
+ * Install the member selection bridge for every fresh or cold-resumed
669
+ * continuable child. Fresh creation reads the pending in-memory selection;
670
+ * cold resume restores the same selection from the owning team's durable
671
+ * record. Legacy members without a complete saved route retain Harness's
672
+ * descriptor provider/model behavior.
673
+ */
674
+ export function installMemberSelectionRuntime(
675
+ ctx: Context,
676
+ stateDir: string,
677
+ onFailureSettled?: (workspace: string, teamId: string, memberName: string) => Promise<void>,
678
+ ): MemberSelectionRuntime {
679
+ const pending = new Map<string, MemberLlmSelection>()
680
+ const pendingSetup = new Map<string, NonNullable<TeamMember['runtimeSetup']>>()
681
+ installContinuableMemberSetup(ctx, (childCtx, child) => {
682
+ const descriptor = foldSubagentDescriptor(sessionOwnEvents(child.session))
683
+ if (descriptor?.mode !== 'continuable' || !descriptor.label.startsWith(MEMBER_LABEL_PREFIX)) {
684
+ return () => undefined
685
+ }
686
+
687
+ const parentSessionId = child.session.header.parentSession
688
+ if (parentSessionId === undefined) return () => undefined
689
+ const identity = descriptor.label.slice(MEMBER_LABEL_PREFIX.length)
690
+ const separator = identity.indexOf(':')
691
+ if (separator < 1 || separator === identity.length - 1) return () => undefined
692
+ const teamId = identity.slice(0, separator)
693
+ const memberName = identity.slice(separator + 1)
694
+ const workspace = child.session.header.cwd ?? process.cwd()
695
+ const stateRoot = join(workspace, stateDir)
696
+ const key = pendingSelectionKey(parentSessionId, descriptor.label)
697
+ // Internal settlement wakeups bypass the public delivery guard. Recheck
698
+ // exact durable membership on every proposed step, including cold resume.
699
+ const disposeAdmission = childCtx.on('agent/pre-step', async (payload, next) => {
700
+ if (payload.agent.id !== child.id) return next()
701
+ const admitted = await withTeamLock(`team:${stateRoot}:${teamId}`, async () => {
702
+ const team = await readTeam(stateRoot, teamId)
703
+ return team?.captainSessionId === parentSessionId && team.phase !== 'staged' && team.halted !== true
704
+ && team.members.some(member => member.id === child.id && member.name === memberName && member.status !== 'removed' && member.stopping !== true)
705
+ && !team.tasks.some(task => task.reassigning === true && task.assignee === memberName)
706
+ })
707
+ if (!admitted) return { kind: 'reject' }
708
+ return next()
709
+ })
710
+ // New activations no longer persist persona/toolFilter in host descriptors.
711
+ // Install them before the first request, and restore the exact saved values
712
+ // after a cold resume. Historical descriptors remain owned by Harness.
713
+ const savedTeam = pending.has(key) ? undefined : readTeamSync(stateRoot, teamId)
714
+ const savedMember = savedTeam?.captainSessionId === parentSessionId
715
+ ? savedTeam.members.find(member => member.id === child.id && member.name === memberName)
716
+ : undefined
717
+ const setup = pendingSetup.get(key) ?? savedMember?.runtimeSetup
718
+ if (usesManagedActivations(ctx.subagents) && savedMember !== undefined
719
+ && setup === undefined && descriptor.toolFilter === undefined) {
720
+ disposeAdmission()
721
+ throw new Error('agent-teams: saved member runtime setup is missing; refusing an unrestricted resume')
722
+ }
723
+ let disposeSetup = (): void => undefined
724
+ if (usesManagedActivations(ctx.subagents) && setup !== undefined) {
725
+ try {
726
+ const stopFilter = childCtx.tools.restrict(setup.toolFilter)
727
+ try {
728
+ const stopPersona = childCtx.systemPrompt.section({
729
+ name: 'deployment:persona-prefix',
730
+ order: childCtx.systemPrompt.getSectionOrder('DEPLOYMENT_PERSONA_PREFIX'),
731
+ text: setup.persona,
732
+ })
733
+ disposeSetup = () => { stopPersona(); stopFilter() }
734
+ } catch (error) { stopFilter(); throw error }
735
+ } catch (error) { disposeAdmission(); throw error }
736
+ }
737
+ const cleanupAdmission = (): void => { disposeSetup(); disposeAdmission() }
738
+ let selection = pending.get(key)
739
+ if (selection === undefined) {
740
+ const team = readTeamSync(stateRoot, teamId)
741
+ if (team?.captainSessionId !== parentSessionId) return cleanupAdmission
742
+ const durableMember = team.members.find(member => member.name === memberName)
743
+ selection = selectionFromMember(durableMember)
744
+ if (selection !== undefined && (descriptor.agentProvider !== durableMember?.provider || descriptor.agentModel !== durableMember?.model)) {
745
+ throw new Error(
746
+ `agent-teams: saved model route for member "${memberName}" does not match its subagent descriptor`,
747
+ )
748
+ }
749
+ }
750
+
751
+ const observeFailedAttempt = (): FailedMemberAttempt | undefined => {
752
+ try {
753
+ // Capture the capability synchronously, before a handoff or lock wait
754
+ // can move the member to another task attempt.
755
+ const snapshot = readTeamSync(stateRoot, teamId)
756
+ if (snapshot?.captainSessionId !== parentSessionId) return
757
+ const member = snapshot.members.find(item => item.id === child.id && item.name === memberName && item.status !== 'removed')
758
+ if (member === undefined) return
759
+ const task = snapshot.tasks.find(item => item.assignee === memberName
760
+ && (item.status === 'claimed' || item.status === 'in_progress'))
761
+ return { captainSessionId: parentSessionId, memberId: child.id, task }
762
+ } catch (error: unknown) {
763
+ ctx.logger.warn(`agent-teams: failed to observe member turn failure: ${String(error)}`)
764
+ }
765
+ }
766
+
767
+ let lastFailedTurn: number | undefined
768
+ const recordFailure = async (turn: number, failure: { code: string; message: string }, observed: FailedMemberAttempt): Promise<void> => {
769
+ if (turn === lastFailedTurn) return
770
+ lastFailedTurn = turn
771
+ try {
772
+ const recorded = await failMemberOpenAttempt(ctx, stateRoot, teamId, memberName, failure, child.session, observed)
773
+ if (!recorded) return
774
+ // The failure event precedes driver quiescence. Observe the real
775
+ // lifecycle and kick explicitly even if its idle event was missed.
776
+ // Never force an active Agent's status to idle or retry the failed task.
777
+ await child.whenIdle()
778
+ await withTeamLock(`team:${stateRoot}:${teamId}`, async () => {
779
+ const team = await readTeam(stateRoot, teamId)
780
+ const current = team?.members.find(item => item.id === child.id && item.name === memberName && item.status !== 'removed')
781
+ if (team?.captainSessionId !== parentSessionId || current === undefined || child.status !== 'idle') return
782
+ if (current.status !== 'idle') {
783
+ current.status = 'idle'
784
+ await writeTeam(stateRoot, team)
785
+ }
786
+ })
787
+ await onFailureSettled?.(workspace, teamId, memberName)
788
+ } catch (error: unknown) {
789
+ ctx.logger.warn(`agent-teams: failed to record member turn failure: ${String(error)}`)
790
+ }
791
+ }
792
+
793
+ // Harness emits agent/error only after request recovery is exhausted. In
794
+ // particular, llm-retry's "always" policy calls downstream request-error
795
+ // listeners before it retries; that waterfall cannot declare a turn dead.
796
+ const disposeFailure = childCtx.on('agent/error', (payload) => {
797
+ if (payload.agent.id !== child.id || payload.turn === lastFailedTurn) return
798
+ const observed = observeFailedAttempt()
799
+ if (observed === undefined) return
800
+ const failure = payload.error instanceof LlmError ? payload.error.failure : {
801
+ code: 'UNKNOWN',
802
+ message: payload.error instanceof Error ? payload.error.message : String(payload.error),
803
+ }
804
+ return recordFailure(payload.turn, failure, observed)
805
+ })
806
+
807
+ let cappedAttempt: { turn: number; observed: FailedMemberAttempt } | undefined
808
+ const disposeOutputLimit = childCtx.on('session/event', (session, event) => {
809
+ if (session !== child.session) return
810
+ // The host's turn reason stays max-tokens even if fresh steering runs
811
+ // another step. Only the last executed step can leave an attempt stuck.
812
+ if (event.type === 'step/start') cappedAttempt = undefined
813
+ const turn = outputLimitTurn(event)
814
+ if (turn !== undefined) {
815
+ const observed = observeFailedAttempt()
816
+ if (observed?.task !== undefined) cappedAttempt = { turn, observed }
817
+ }
818
+ if (event.type !== 'turn/end') return
819
+ const capped = cappedAttempt
820
+ cappedAttempt = undefined
821
+ if (capped?.turn !== event.data.turn || event.data.reason?.kind !== 'max-tokens') return
822
+ return recordFailure(capped.turn, {
823
+ code: 'MAX_TOKENS',
824
+ message: 'Model output-token limit reached before the member closed this task',
825
+ }, { ...capped.observed, openAttemptOnly: true })
826
+ })
827
+
828
+ const cleanupFailure = (): void => { disposeOutputLimit(); disposeFailure(); cleanupAdmission() }
829
+ // Legacy teams still need failure reporting even without a saved route.
830
+ if (selection === undefined) return cleanupFailure
831
+ const selectionRef = { current: modelSelection(selection), assembled: undefined as ModelSelection | undefined }
832
+ // Newer Harness owns the next-step selection in the Agent's durable model
833
+ // API. Its installModelSelection hook now only contributes switch notices.
834
+ const model = (child as Agent & { model?: { select(selection: Readonly<ModelSelection>): void } }).model
835
+ const nativeModel = typeof model?.select === 'function' ? model : undefined
836
+ nativeModel?.select(selectionRef.current)
837
+ const disposeSelection = installMemberModelSelection(childCtx, selectionRef)
838
+ const fallback = selection.fallback
839
+ let switched = false
840
+ const recoveryLifetime = new AbortController()
841
+ const disposeFallback = childCtx.on('agent/request-error', async (payload, next) => {
842
+ if (payload.agent.id !== child.id) return next()
843
+ const transition = selectFallbackRoute(selectionRef.current, fallback, payload.failure.code, switched)
844
+ if (fallback === undefined || !transition.retry) return next()
845
+ // The turn can survive plugin unload. Stop any queued recovery when
846
+ // this child setup is disposed while waiting for the team lock.
847
+ const signal = AbortSignal.any([payload.signal, recoveryLifetime.signal])
848
+ if (signal.aborted) return next()
849
+ const committed = await commitFallbackRoute(stateRoot, teamId, memberName, child, fallback, signal, ctx, () => {
850
+ switched = transition.switched
851
+ selectionRef.current = transition.selection
852
+ ctx.logger.warn(`agent-teams: member ${child.id} switching to fallback ${fallback.provider}/${fallback.model} after ${payload.failure.code}`)
853
+ if (nativeModel === undefined) {
854
+ // Legacy recovery rebuilds the request without rerunning assembly.
855
+ selectionRef.assembled = transition.selection
856
+ return
857
+ }
858
+
859
+ // Modern recovery fixes the route for all retries of a prepared step.
860
+ // Close that step without failing its task, then wake the same member in
861
+ // a new turn. The assignment and any completed calls are already in its
862
+ // session history, so there is no task retry or replay of input.
863
+ nativeModel.select(transition.selection)
864
+ const continuation = createUserMessage({
865
+ content: [{ type: 'text', text: 'AgentTeams switched to the configured fallback model. Continue the current work from the conversation history and recorded task state.' }],
866
+ source: agentTeamsSource({ kind: 'agent-teams' }, observedSessionFormatVersion(child)),
867
+ })
868
+ if (signal.aborted) return
869
+ child.cancel({ kind: 'hook', reason: 'agent-teams/model-fallback' }, { keepInbox: true })
870
+ try {
871
+ child.followup(continuation)
872
+ } catch (error) {
873
+ // Cancellation suppresses the host's agent/error event, so a rejected
874
+ // continuation still needs to settle the observed attempt.
875
+ const observed = observeFailedAttempt()
876
+ if (observed !== undefined) void recordFailure(payload.turn, payload.failure, observed)
877
+ throw error
878
+ }
879
+ })
880
+ if (!committed) return next()
881
+ return nativeModel === undefined ? { kind: 'retry' as const } : undefined
882
+ })
883
+ return () => {
884
+ recoveryLifetime.abort()
885
+ disposeFallback()
886
+ disposeSelection()
887
+ cleanupFailure()
888
+ }
889
+ })
890
+
891
+ return {
892
+ isPendingMember(agent) {
893
+ const parent = agent.session.header.parentSession
894
+ const descriptor = foldSubagentDescriptor(sessionOwnEvents(agent.session))
895
+ return parent !== undefined && descriptor?.mode === 'continuable'
896
+ && pending.has(pendingSelectionKey(parent, descriptor.label))
897
+ },
898
+ async withPending<T>(
899
+ parentSessionId: string,
900
+ label: string,
901
+ selection: MemberLlmSelection,
902
+ operation: () => Promise<T>,
903
+ setup?: TeamMember['runtimeSetup'],
904
+ ): Promise<T> {
905
+ const key = pendingSelectionKey(parentSessionId, label)
906
+ if (pending.has(key)) {
907
+ throw new Error(`member model selection is already pending for "${label}"`)
908
+ }
909
+ pending.set(key, selection)
910
+ if (setup !== undefined) pendingSetup.set(key, setup)
911
+ try {
912
+ return await operation()
913
+ } finally {
914
+ pending.delete(key)
915
+ pendingSetup.delete(key)
916
+ }
917
+ },
918
+ }
919
+ }
920
+
921
+ function configuredExecutionPrompt(member: TeamMember, config: MemberRuntimeConfig): string | undefined {
922
+ const prompt = member.executionPrompt?.trim() || config.executionPrompt?.trim()
923
+ return prompt === undefined || prompt === '' ? undefined : prompt
924
+ }
925
+
926
+ function truncatedPersonaProtocol(protocol: string | undefined): string {
927
+ if (protocol === undefined || protocol.trim() === '') return '(none)'
928
+ if (protocol.length <= PERSONA_PROTOCOL_MAX_CHARS) return protocol
929
+ return `${protocol.slice(0, PERSONA_PROTOCOL_MAX_CHARS)}… [truncated]`
930
+ }
931
+
932
+ function assignedNonTerminalCount(team: TeamState, memberName: string): number {
933
+ return team.tasks.filter(task => (
934
+ task.assignee === memberName && !TERMINAL_TASK_STATUSES.includes(task.status)
935
+ )).length
936
+ }
937
+
938
+ /**
939
+ * The member's system prompt (persona), shadowing the deployment persona for
940
+ * that child. Self-contained: it replaces the whole persona section.
941
+ * Frozen at spawn: draft must already carry the Team goal and profile protocol.
942
+ * @param team - the team the member joined.
943
+ * @param member - the member record (name/role are read before spawning).
944
+ * @param stateDir - configured state directory, so the member can locate the
945
+ * team files with its own file tools.
946
+ */
947
+ export function memberPersona(team: TeamState, member: TeamMember, stateDir: string, executionPrompt?: string): string {
948
+ const goal = team.description?.trim() || '(not provided)'
949
+ const injectedPrompt = member.executionPrompt?.trim() || executionPrompt?.trim()
950
+ const protocol = truncatedPersonaProtocol(team.profile?.protocol)
951
+ return `You are ${member.name}, a member of the multi-agent team "${team.name}" running inside DeepSeek Harness AgentTeams. The captain leads the team; you are a worker member${member.role ? ` with the role: ${member.role}` : ''}.
952
+
953
+ Team context:
954
+ - Team id: ${team.id}
955
+ - Your name inside the team (use it as \`from\`/identity): ${member.name}
956
+ - Team goal: ${goal}
957
+ - Profile protocol: ${protocol}
958
+ ${injectedPrompt === undefined || injectedPrompt === '' ? '' : `- Execution guidance:
959
+ ${injectedPrompt}
960
+ `}- The team state lives under ${stateDir}/${team.id}/ (team.json and inbox/*.jsonl). You may inspect these files read-only for diagnostics, but never edit them directly; use the agent_teams_* tools so JSON escaping and concurrent updates stay safe.
961
+ - The captain and your teammates reach you through messages. Coordination arrives at your nearest model step. Apply it to your current attempt; a task assignment starts a separate turn.
962
+ When you receive a task, treat the assignment prompt's dependency results as source material. Do not ignore them.
963
+
964
+ Working rules:
965
+ 1. When you receive a task assignment, call agent_teams_claim_task with the task id. Keep the returned attempt_id: include it in every agent_teams_update_task call for that execution attempt. Then mark the task in_progress.
966
+ 2. Work thoroughly with your available tools; do not cut corners.
967
+ 3. When finishing a task:
968
+ - use status=completed only when the task's success criteria are satisfied;
969
+ - use status=failed when blocking findings or validation failures mean downstream work must not proceed;
970
+ - include a concise output in either case;
971
+ - a stale-attempt rejection means the captain reassigned or took over the task; stop touching that task and wait for new work.
972
+ claimed cannot jump to completed. Mark in_progress first, then completed or failed.
973
+ Include attempt_id on every update. Then report once as described below and become idle.
974
+ 4. Send one short report with agent_teams_send_message (to=captain) when you complete a task or hit a blocker. Include source_task_id and source_attempt_id in task reports; a stale source rejection means stop, never relabel an old result with a new attempt. The captain is also your parent: this single message satisfies both reporting duties. Do not repeat it through the native send_message tool or send acknowledgments that add no new information.
975
+ 5. To ask a teammate something, use agent_teams_send_message with to=<teammate name>; the message lands in their mailbox and wakes them directly — teammates talk to each other without the captain in the loop. The same applies to the captain (to=captain).
976
+ 6. After your turn becomes idle, the shared task scheduler may assign your next ready task automatically. Never claim a second task while you still own unfinished work.
977
+ 7. If you already own an open attempt (claimed or in_progress) and receive mail, treat it as guidance for that same attempt_id unless the mail explicitly tells you to stop or fail. Do not claim a new task in that turn.
978
+ 8. Do not start a teammate's assigned task. Do not privately tell the next-stage member to start; the scheduler assigns unlocked work after you become idle.
979
+ 9. You are a worker: do not create or delete teams, reassign tasks, or add/remove members — that is the captain's job.
980
+ 10. Quality-gate kinds carry a contract (kind, objective, inScope, acceptance, verify). Stay inside inScope. Do not mark your own implementation as review pass. Review/requirements complete only with verdict=pass; needs_revision/reject must fail with findings. Mail is not a formal next review. Completed work must not be repeated to attach late evidence: call update_task on the original task with its attempt_id and acceptanceResults/commandsRun/evidence_note; supplements are append-only and cannot change its verdict.`
981
+ }
982
+
983
+ /**
984
+ * The initial user message delivered when the member is created.
985
+ * Counts non-terminal tasks already assigned to this member on the in-memory draft.
986
+ * @param team - the team the member joined.
987
+ * @param memberName - canonical member name used to count assigned pending work.
988
+ */
989
+ export function memberWelcome(team: TeamState, memberName: string): string {
990
+ const assigned = assignedNonTerminalCount(team, memberName)
991
+ return `You have joined the team "${team.name}" as a member. Wait for an automatic assignment or a captain message.
992
+ Current team status: ${team.tasks.length} task(s), ${assigned} pending task(s) assigned to you.
993
+ Do not start work until the scheduler or captain assigns a task in this turn.`
994
+ }
995
+
996
+ /**
997
+ * Spawn one member as a durable continuable subagent of the captain and fill
998
+ * `member.id` with its child session id. On failure nothing is persisted.
999
+ * @param ctx - the plugin context (injects `subagents`).
1000
+ * @param config - member runtime knobs.
1001
+ * @param selections - fresh/cold child model-selection bridge.
1002
+ * @param llmSelection - resolved provider/model/reasoning snapshot.
1003
+ * @param captain - the exact live captain agent (the calling agent).
1004
+ * @param team - the team record (read-only here).
1005
+ * @param member - the member draft whose `id` is filled on success.
1006
+ * @param stateDir - configured state directory (for the persona).
1007
+ * @param signal - caller cancellation, forwarded to the start.
1008
+ * @param initialPrompt - first turn text; the welcome message when omitted.
1009
+ * @param resolvedFilter - the member's effective tool filter (a selected
1010
+ * policy, or the legacy captain-only filter when the member has none). The
1011
+ * caller resolves it so `spawnMember` forwards exactly one immutable filter
1012
+ * to `startContinuable`.
1013
+ * @param relaxableDeny - deny names the lenient retry may drop for this
1014
+ * member; the caller narrows it for a policy member so a name the owner
1015
+ * declared is never silently removed.
1016
+ */
1017
+ export async function spawnMember(
1018
+ ctx: Context,
1019
+ config: MemberRuntimeConfig,
1020
+ selections: MemberSelectionRuntime,
1021
+ llmSelection: MemberLlmSelection,
1022
+ captain: Agent,
1023
+ team: TeamState,
1024
+ member: TeamMember,
1025
+ stateDir: string,
1026
+ signal: AbortSignal,
1027
+ initialPrompt?: string,
1028
+ resolvedFilter?: MemberToolFilter,
1029
+ relaxableDeny?: readonly string[],
1030
+ ): Promise<void> {
1031
+ // Fail loud at the first use: provider registration is a sibling plugin's
1032
+ // effect and may settle after this plugin mounts. Capability checks here
1033
+ // mirror what startContinuable would reject, with an actionable error.
1034
+ const provider = ctx.subagents.getProvider(config.provider)
1035
+ if (provider === undefined) {
1036
+ throw new Error(
1037
+ `agent-teams: no subagent provider "${config.provider}" is registered (available: ${ctx.subagents.list().join(', ') || 'none'}) — `
1038
+ + 'check that the subagent provider row (e.g. subagent-spawn) is mounted in the composition',
1039
+ )
1040
+ }
1041
+ if (provider.prepareContinuable === undefined) {
1042
+ throw new Error(`agent-teams: provider "${config.provider}" does not support continuable members`)
1043
+ }
1044
+ const legacyCapabilities = provider.capabilities as unknown as { persona?: boolean; toolFilter?: boolean }
1045
+ if (!usesManagedActivations(ctx.subagents) && !legacyCapabilities.persona) {
1046
+ throw new Error(`agent-teams: provider "${config.provider}" cannot apply a member persona`)
1047
+ }
1048
+ if (!usesManagedActivations(ctx.subagents) && !legacyCapabilities.toolFilter) {
1049
+ throw new Error(`agent-teams: provider "${config.provider}" cannot restrict captain-only tools for members`)
1050
+ }
1051
+ const label = `${MEMBER_LABEL_PREFIX}${team.id}:${member.name}`
1052
+ // The legacy filter of a member without a configured tool policy: the
1053
+ // captain-only deny list plus the depth entries this host registers.
1054
+ const requestedFilter = resolvedFilter ?? memberToolFilter(config.maxDepth, restrictableToolNames(captain))
1055
+ // The lenient retry may drop names this host reports unknown; keep the exact
1056
+ // filter the host accepted for the durable member setup.
1057
+ let acceptedFilter = requestedFilter
1058
+ const start = await startMemberWithLenientFilter(
1059
+ toolFilter => {
1060
+ acceptedFilter = toolFilter
1061
+ const setup = { persona: memberPersona(team, member, stateDir, config.executionPrompt), toolFilter }
1062
+ return selections.withPending(captain.id, label, llmSelection, () => startMember(ctx.subagents, {
1063
+ provider: config.provider,
1064
+ label,
1065
+ request: {
1066
+ prompt: [{ type: 'text', text: initialPrompt ?? memberWelcome(team, member.name) }],
1067
+ parent: captain,
1068
+ persona: memberPersona(team, member, stateDir, config.executionPrompt),
1069
+ // Depth deny entries name host tools; resolve them against the
1070
+ // running host's registry so a renamed delegation tool cannot abort
1071
+ // the spawn (see memberToolFilter). Depth is still enforced by the
1072
+ // parent-chain guard installed at plugin mount. A filter the host
1073
+ // still rejects is retried without the names it reported.
1074
+ toolFilter,
1075
+ agentOptions: {
1076
+ provider: llmSelection.provider,
1077
+ model: llmSelection.model,
1078
+ ...llmSelection.reasoningEffort === undefined
1079
+ ? {}
1080
+ : { reasoningEffort: ReasoningEffortId(llmSelection.reasoningEffort) },
1081
+ },
1082
+ // Harness request.maxDepth caps the absolute depth of THIS creation;
1083
+ // it is not inherited by later delegations. The guard below enforces
1084
+ // the configured member-relative descendant budget instead.
1085
+ },
1086
+ signal,
1087
+ }), setup)
1088
+ },
1089
+ requestedFilter,
1090
+ relaxableDeny,
1091
+ )
1092
+ member.id = start.childId
1093
+ if (usesManagedActivations(ctx.subagents)) {
1094
+ member.runtimeSetup = { persona: memberPersona(team, member, stateDir, config.executionPrompt), toolFilter: acceptedFilter }
1095
+ }
1096
+ // Only a policy member carries a persisted filter snapshot; a member without
1097
+ // a policy keeps its public record shape. Legacy descriptors or runtimeSetup
1098
+ // restore the filter on cold resume, depending on the host generation.
1099
+ if (member.toolFilter !== undefined) member.toolFilter = { ...acceptedFilter }
1100
+ }
1101
+
1102
+ /**
1103
+ * Deliver one message to a member as its next FIFO turn. Best effort: a
1104
+ * failure (member gone or not continuable) is logged and reported as `false`
1105
+ * so the caller can decide (mailbox delivery still happened).
1106
+ *
1107
+ * Any team sender can route through this helper: the captain is the direct
1108
+ * parent of every member, and the caller passes the captain's live Agent
1109
+ * (its own when the captain calls, the registry-resolved one when a member
1110
+ * sends) — mirroring the Claude Code mailbox model where the writer writes
1111
+ * the target's inbox and the target picks it up on its own.
1112
+ * @param ctx - the plugin context (injects `subagents`).
1113
+ * @param captain - the exact live captain agent (the member's direct parent).
1114
+ * @param childId - the member's durable child session id.
1115
+ * @param text - the message content.
1116
+ * @param signal - caller cancellation, forwarded to the delivery.
1117
+ * @returns whether the member inbox accepted the message.
1118
+ */
1119
+ export async function deliverToMember(
1120
+ ctx: Context,
1121
+ captain: Agent,
1122
+ childId: string,
1123
+ text: string,
1124
+ signal: AbortSignal,
1125
+ mode: 'queue' | 'steer' = 'queue',
1126
+ ): Promise<boolean> {
1127
+ try {
1128
+ const content = [{ type: 'text' as const, text }]
1129
+ if (mode === 'steer') await steerMemberPrompt(ctx.subagents, captain, brandedSessionId(childId), content, signal, ctx.agents.get(brandedSessionId(childId)))
1130
+ else await queueMemberPrompt(ctx.subagents, captain, brandedSessionId(childId), content, signal)
1131
+ return true
1132
+ } catch (error: unknown) {
1133
+ ctx.logger.warn(`agent-teams: prompt delivery to member ${childId} failed: ${String(error)}`)
1134
+ return false
1135
+ }
1136
+ }
1137
+
1138
+ /**
1139
+ * Request cancellation of one live member's current turn. Best effort, fire
1140
+ * and return; the target may keep running until it observes the signal.
1141
+ * @param ctx - the plugin context (injects `subagents`).
1142
+ * @param captain - the exact live captain agent (the member's parent).
1143
+ * @param childId - the member's durable child session id.
1144
+ */
1145
+ export function interruptMember(ctx: Context, captain: Agent, childId: string): void {
1146
+ try {
1147
+ ctx.subagents.interrupt(brandedSessionId(childId), { kind: 'ancestor', agent: captain })
1148
+ } catch (error: unknown) {
1149
+ ctx.logger.warn(`agent-teams: interrupt of member ${childId} failed: ${String(error)}`)
1150
+ }
1151
+ }
1152
+
1153
+ /**
1154
+ * Install the missing per-child retirement boundary above Harness rc.6.
1155
+ *
1156
+ * Upstream `interrupt()` deliberately preserves continuable sessions and the
1157
+ * upstream seam exposes no targeted forget/retire method. The durable
1158
+ * AgentTeams index therefore rejects every inbox delivery before it can cold-resume a
1159
+ * retired member. Catalog rows deliberately remain discoverable: Harness rc.8
1160
+ * uses the direct-child catalog to authorize historical transcript reads and
1161
+ * `openSubagent()`, so filtering those rows would make an archived member's
1162
+ * persisted conversation inaccessible. Exact ids keep unrelated subagents
1163
+ * untouched while the delivery boundary still prevents further model turns.
1164
+ */
1165
+ export function installRetiredMemberGuard(ctx: Context, stateDir: string): void {
1166
+ guardSubagentDelivery(ctx, async (parent, childId) => {
1167
+ const retired = await readRetiredMemberIds(join(parent.session.header.cwd ?? process.cwd(), stateDir))
1168
+ return retired.has(childId)
1169
+ })
1170
+ }
1171
+
1172
+ /** Bound all descendant creation, including renamed tools and code-runtime calls. */
1173
+ export function installMemberDelegationGuard(ctx: Context, stateDir: string, maxDepth: number): void {
1174
+ let active = true
1175
+ const check = (parent: Agent): void => {
1176
+ if (!active) return
1177
+ let ancestor: Agent | undefined = parent
1178
+ let depth = 1
1179
+ while (ancestor !== undefined) {
1180
+ const descriptor = foldSubagentDescriptor(sessionOwnEvents(ancestor.session))
1181
+ if (descriptor?.label?.startsWith(MEMBER_LABEL_PREFIX)) {
1182
+ const identity = descriptor.label.slice(MEMBER_LABEL_PREFIX.length)
1183
+ const separator = identity.indexOf(':')
1184
+ let team: ReturnType<typeof readTeamSync>
1185
+ try {
1186
+ team = readTeamSync(join(ancestor.session.header.cwd ?? process.cwd(), stateDir), identity.slice(0, separator))
1187
+ } catch (error: unknown) {
1188
+ // Distinguish "team state unreadable" (e.g. a corrupt team.json) from
1189
+ // the guarded rejections below: reject with an actionable message
1190
+ // instead of leaking the raw parse error through subagents.start.
1191
+ throw new Error(`AgentTeams delegation guard could not read the team state of "${identity.slice(0, separator)}" (its team.json may be corrupt or unreadable): ${String(error)}`)
1192
+ }
1193
+ const member = team?.members.find(item => item.id === ancestor!.id && item.name === identity.slice(separator + 1))
1194
+ if (member === undefined || member.status === 'removed' || member.stopping === true || team?.halted === true) throw new Error('AgentTeams member is no longer admitting delegated work')
1195
+ if (depth > maxDepth) throw new Error(`AgentTeams member delegation limit (${maxDepth}) reached; report to the captain instead of spawning another agent`)
1196
+ return
1197
+ }
1198
+ const parentId: SessionId | undefined = ancestor.session.header.parentSession
1199
+ ancestor = parentId === undefined ? undefined : ctx.agents.get(parentId)
1200
+ depth++
1201
+ }
1202
+ }
1203
+ guardSubagentCreation(ctx, check)
1204
+ ctx.effect(() => () => { active = false }, 'agent-teams: delegation guard lifetime')
1205
+ }
1206
+
1207
+ /**
1208
+ * Snapshot the real driver activity for durable member ids.
1209
+ *
1210
+ * The team record is the membership authority, so this path intentionally no
1211
+ * longer depends on `listChildren()`'s versioned projection shape. Harness
1212
+ * rc.8 changed those rows to branded `SessionId` values plus residency-only
1213
+ * `activity`; neither is needed to answer whether the live Agent driver is
1214
+ * running, idle, or absent/ready.
1215
+ * @param ctx - the plugin context (injects `agents`).
1216
+ * @param memberIds - child ids restored from the durable team record.
1217
+ * @returns child id → live activity.
1218
+ */
1219
+ export function memberActivity(
1220
+ ctx: Context,
1221
+ memberIds: readonly string[],
1222
+ ): Map<string, 'running' | 'idle' | 'ready'> {
1223
+ const activity = new Map<string, 'running' | 'idle' | 'ready'>()
1224
+ for (const id of memberIds) {
1225
+ if (id === '') continue
1226
+ const live = ctx.agents.get(brandedSessionId(id))
1227
+ activity.set(id, live === undefined ? 'ready' : live.status)
1228
+ }
1229
+ return activity
1230
+ }