@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/lineage.ts ADDED
@@ -0,0 +1,248 @@
1
+ /**
2
+ * Durable session lineage for team identity.
3
+ *
4
+ * Forking is a first-class DSH operation: the fork receives a new session id
5
+ * and records the source session as `header.parentSession`. Team identity must
6
+ * therefore be resolved along that chain, or a captain that continues in its
7
+ * own fork stops matching the team it leads (#176). Membership keeps its exact
8
+ * id match: a member is a subagent child of its captain, so its parent chain
9
+ * also contains the captain and must never be read as lead identity. Only a
10
+ * top-level conversation may inherit lead identity from an ancestor.
11
+ *
12
+ * Authorization paths resolve the chain durably: a hop is read from the live
13
+ * session when that session is resident and from the persistence service's
14
+ * stored header otherwise, so a fork still resolves its team while an
15
+ * intermediate session (or the original captain) is not loaded. The
16
+ * synchronous prompt-assembly path uses the calling session's own durable
17
+ * header plus resolvable live hops; failing to resolve there only leaves the
18
+ * default captain-side prompt in place — every tool re-authorizes
19
+ * asynchronously.
20
+ * @module dsh-agent-teams/lineage
21
+ */
22
+ import type { Context } from '@deepseek-ai/cordis'
23
+ import type { Agent } from '@deepseek-ai/dsh-agent'
24
+ import type { Session, SessionHeader, SessionId } from '@deepseek-ai/dsh-session'
25
+
26
+ /** Maximum fork-chain depth resolved for one identity (cycle- and length-bounded). */
27
+ export const LINEAGE_MAX_DEPTH = 32
28
+
29
+ /** One calling session's durable identity as the team lookups need it. */
30
+ export interface LeadIdentity {
31
+ /** The calling session id. */
32
+ readonly sessionId: string
33
+ /** Ancestor session ids reachable through `header.parentSession`, nearest first. */
34
+ readonly ancestry: readonly string[]
35
+ /** Whether this session may inherit lead identity from an ancestor at all. */
36
+ readonly inheritsLead: boolean
37
+ }
38
+
39
+ /** Minimal structural view of the live session store this module reads. */
40
+ interface SessionStoreView {
41
+ get?: (id: SessionId) => Session | undefined
42
+ }
43
+
44
+ /** Stored-header metadata of one durable session. */
45
+ interface SessionPersistenceView {
46
+ stat?: (id: SessionId, options?: { readonly signal?: AbortSignal }) => Promise<{ readonly header?: SessionHeader } | undefined>
47
+ }
48
+
49
+ /**
50
+ * Official optional service access. `ctx.get` is the reflection accessor for a
51
+ * service a plugin does not declare in `inject`; a missing service yields
52
+ * `undefined` instead of a contract error, and a getter that still refuses is
53
+ * contained here.
54
+ */
55
+ function optionalService<T>(ctx: Context, name: string): T | undefined {
56
+ const get = (ctx as unknown as { get?: (name: string) => unknown }).get
57
+ if (typeof get !== 'function') return undefined
58
+ try {
59
+ return get.call(ctx, name) as T | undefined
60
+ } catch {
61
+ return undefined
62
+ }
63
+ }
64
+
65
+ /** Ancestry this process already resolved for one session. */
66
+ const ancestryCache = new Map<string, readonly string[]>()
67
+
68
+ /** The live session for one id: resident agent first, then the live session store. */
69
+ export function liveSession(ctx: Context, id: string): Session | undefined {
70
+ const branded = id as SessionId
71
+ const agent = ctx.agents.get(branded)
72
+ if (agent !== undefined) return agent.session
73
+ return optionalService<SessionStoreView>(ctx, 'sessions')?.get?.(branded)
74
+ }
75
+
76
+ /** Whether one session is a top-level conversation rather than a subagent child. */
77
+ export function isTopLevelSession(session: Session): boolean {
78
+ return session.header.origin !== 'subagent' && (session.header.delegationDepth ?? 0) === 0
79
+ }
80
+
81
+ /** Durable parent of one session id: the live header, else the stored header. */
82
+ async function durableParent(ctx: Context, id: string): Promise<string | undefined> {
83
+ const live = liveSession(ctx, id)
84
+ if (live !== undefined) return live.header.parentSession
85
+ const persistence = optionalService<SessionPersistenceView>(ctx, 'sessionPersistence')
86
+ try {
87
+ const snapshot = await persistence?.stat?.(id as SessionId)
88
+ const parent: string | undefined = snapshot?.header?.parentSession
89
+ return parent
90
+ } catch {
91
+ // Unreadable stored metadata ends this chain; authorization then fails
92
+ // closed on the identity the caller itself provides.
93
+ return undefined
94
+ }
95
+ }
96
+
97
+ /**
98
+ * Durable ancestry of one session, nearest first. The calling session's own
99
+ * header supplies the first hop; later hops come from resident sessions or
100
+ * stored headers, so a fork resolves through sessions that are not loaded.
101
+ * @param ctx - the plugin context (injects `agents`).
102
+ * @param session - the calling session.
103
+ * @returns ancestor session ids, bounded by {@link LINEAGE_MAX_DEPTH}.
104
+ */
105
+ export async function resolveAncestry(ctx: Context, session: Session): Promise<readonly string[]> {
106
+ const ancestry: string[] = []
107
+ const seen = new Set<string>([session.id])
108
+ let parent: string | undefined = session.header.parentSession
109
+ while (parent !== undefined && ancestry.length < LINEAGE_MAX_DEPTH && !seen.has(parent)) {
110
+ seen.add(parent)
111
+ ancestry.push(parent)
112
+ parent = await durableParent(ctx, parent)
113
+ }
114
+ ancestryCache.set(session.id, ancestry)
115
+ return ancestry
116
+ }
117
+
118
+ /**
119
+ * Ancestry resolvable without awaiting: the calling session's durable first
120
+ * hop, then resident sessions, then whatever the async resolver cached.
121
+ */
122
+ export function sessionAncestry(ctx: Context, session: Session): readonly string[] {
123
+ const cached = ancestryCache.get(session.id)
124
+ if (cached !== undefined) return cached
125
+ const ancestry: string[] = []
126
+ const seen = new Set<string>([session.id])
127
+ let parent: string | undefined = session.header.parentSession
128
+ while (parent !== undefined && ancestry.length < LINEAGE_MAX_DEPTH && !seen.has(parent)) {
129
+ seen.add(parent)
130
+ ancestry.push(parent)
131
+ parent = liveSession(ctx, parent)?.header.parentSession
132
+ }
133
+ return ancestry
134
+ }
135
+
136
+ /** Resolve one session's lead identity synchronously (prompt-assembly path). */
137
+ export function leadIdentityOf(ctx: Context, session: Session): LeadIdentity {
138
+ return {
139
+ sessionId: session.id,
140
+ ancestry: sessionAncestry(ctx, session),
141
+ inheritsLead: isTopLevelSession(session),
142
+ }
143
+ }
144
+
145
+ /** Resolve one session's lead identity durably (authorization paths). */
146
+ export async function leadIdentityOfAsync(ctx: Context, session: Session): Promise<LeadIdentity> {
147
+ return {
148
+ sessionId: session.id,
149
+ ancestry: await resolveAncestry(ctx, session),
150
+ inheritsLead: isTopLevelSession(session),
151
+ }
152
+ }
153
+
154
+ /** The lead-relevant view of a team record. */
155
+ export interface LeadScopedTeam {
156
+ readonly captainSessionId: string
157
+ /** Present on real team state; omitting it keeps the pure exact-id contract. */
158
+ readonly members?: readonly { readonly id: string; readonly status?: string }[]
159
+ }
160
+
161
+ /** Whether one identity leads (or inherits the lead of) a team's recorded captain. */
162
+ export function teamLeadMatch(team: LeadScopedTeam, lead: LeadIdentity): boolean {
163
+ const members = team.members ?? []
164
+ // A listed member is never a lead, retired or not: a member session is a
165
+ // subagent child of its captain, so its parent chain contains the captain id
166
+ // too, and membership revocation must never hand that session lead authority.
167
+ // Member participation itself stays governed by the removed filter in the
168
+ // team lookups.
169
+ if (members.some(member => member.id === lead.sessionId)) return false
170
+ if (team.captainSessionId === lead.sessionId) return true
171
+ if (!lead.inheritsLead) return false
172
+ // Descending from a member (a fork of one) is not lead identity either.
173
+ if (members.some(member => lead.ancestry.includes(member.id))) return false
174
+ return lead.ancestry.includes(team.captainSessionId)
175
+ }
176
+
177
+ /**
178
+ * Whether one live session id leads a team: the recorded captain itself, or a
179
+ * top-level fork descendant of it. Members never match through their parent
180
+ * chain, and a member's fork does not match either.
181
+ */
182
+ export function sessionLeadsTeam(ctx: Context, team: LeadScopedTeam, sessionId: string): boolean {
183
+ if (team.members?.some(member => member.id === sessionId) === true) return false
184
+ if (team.captainSessionId === sessionId) return true
185
+ const session = liveSession(ctx, sessionId)
186
+ return session !== undefined && teamLeadMatch(team, leadIdentityOf(ctx, session))
187
+ }
188
+
189
+ /** Durable {@link sessionLeadsTeam}: resolves the caller's chain through stored headers. */
190
+ export async function sessionLeadsTeamAsync(ctx: Context, team: LeadScopedTeam, sessionId: string): Promise<boolean> {
191
+ if (team.members?.some(member => member.id === sessionId) === true) return false
192
+ if (team.captainSessionId === sessionId) return true
193
+ const session = liveSession(ctx, sessionId)
194
+ return session !== undefined && teamLeadMatch(team, await leadIdentityOfAsync(ctx, session))
195
+ }
196
+
197
+ /**
198
+ * Nearest live lead session of a team: the recorded captain while it is
199
+ * resident, otherwise the closest live fork descendant of it. Captain-directed
200
+ * reports use this so a human working in a fork still receives them, while the
201
+ * durable mail record stays addressed to the recorded captain.
202
+ * @param ctx - the plugin context (injects `agents`).
203
+ * @param team - current team state.
204
+ * @returns the live lead agent, or undefined when no lead session is resident.
205
+ */
206
+ export function nearestLiveLead(
207
+ ctx: Context,
208
+ team: LeadScopedTeam,
209
+ live?: readonly Agent[],
210
+ ): Agent | undefined {
211
+ // The recorded captain is the delivery parent whenever it is resident; a
212
+ // registry without `list` (or with rows the lineage cannot read) only means
213
+ // the fork fallback is unavailable, never that this lookup fails.
214
+ const exact = ctx.agents.get(team.captainSessionId as SessionId)
215
+ if (exact !== undefined) return exact
216
+ let candidates: readonly Agent[]
217
+ try {
218
+ candidates = live ?? ctx.agents.list()
219
+ } catch {
220
+ return undefined
221
+ }
222
+ let best: Agent | undefined
223
+ let bestDistance = Number.POSITIVE_INFINITY
224
+ for (const agent of candidates) {
225
+ try {
226
+ const identity = leadIdentityOf(ctx, agent.session)
227
+ if (!teamLeadMatch(team, identity)) continue
228
+ const distance = identity.ancestry.indexOf(team.captainSessionId)
229
+ if (distance < 0 || distance >= bestDistance) continue
230
+ best = agent
231
+ bestDistance = distance
232
+ } catch {
233
+ continue
234
+ }
235
+ }
236
+ return best
237
+ }
238
+
239
+ /**
240
+ * Diagnostic note for a caller that matched no team but is a fork, so an
241
+ * operator can distinguish "no team exists" from "a team exists that this
242
+ * session does not lead".
243
+ */
244
+ export function forkLineageNote(session: Session): string {
245
+ const parent = session.header.parentSession
246
+ if (parent === undefined) return ''
247
+ return ` (this session is a fork of ${parent}; no active team in this workspace is led by that session or by a lead session in its lineage)`
248
+ }
package/src/mailbox.ts ADDED
@@ -0,0 +1,185 @@
1
+ /** Durable delivery receipts and execution-generation filtering at step admission. */
2
+ import type { Context } from '@deepseek-ai/cordis'
3
+ import { join } from 'node:path'
4
+ import { acknowledgeMailbox, CAPTAIN_KEY, discardMailboxMessages, findTeamByCaptain, readMailbox, readUnreadMailbox, readTeam, sanitizeKey, withTeamLock } from './state.ts'
5
+ import type { TeamMessage, TeamState } from './types.ts'
6
+ import { sessionOwnEvents } from './harness-compat.ts'
7
+ import { leadIdentityOfAsync, sessionLeadsTeamAsync } from './lineage.ts'
8
+
9
+ const PREFIX = 'AgentTeams inbox receipt: '
10
+
11
+ export function isCurrentMail(team: TeamState, message: TeamMessage): boolean {
12
+ if (message.discardedAt !== undefined) return false
13
+ if (message.sourceAttemptId !== undefined && !team.tasks.some(task => task.id === message.sourceTaskId
14
+ && task.attemptId === message.sourceAttemptId && task.assignee === message.from
15
+ && (message.sourceTaskStatus === undefined || !['completed', 'failed', 'cancelled'].includes(task.status) || message.sourceTaskStatus === task.status))) return false
16
+ if (message.attemptId === undefined) return true
17
+ return team.tasks.some(task => task.id === message.taskId && task.attemptId === message.attemptId
18
+ && task.assignee === message.to && (task.status === 'claimed' || task.status === 'in_progress'))
19
+ }
20
+
21
+ /** Include structured provenance even in the status-tool fallback presentation. */
22
+ export function mailboxContent(message: TeamMessage): string {
23
+ return (message.sourceTaskId === undefined ? ''
24
+ : `[Source task ${message.sourceTaskId}, attempt_id ${message.sourceAttemptId}${message.sourceTaskStatus === undefined ? '' : `, status=${message.sourceTaskStatus}`}]\n`) + message.content
25
+ }
26
+
27
+ function mailboxBody(recipient: string, messages: readonly TeamMessage[]): string {
28
+ return messages.map(message => recipient === CAPTAIN_KEY
29
+ ? `AgentTeams message from member ${message.from}:\n\n${mailboxContent(message)}`
30
+ : `AgentTeams message from ${message.from}${message.attemptId === undefined ? '' : ` for task ${message.taskId}, attempt_id ${message.attemptId}`}:\n\n${mailboxContent(message)}`).join('\n\n')
31
+ }
32
+
33
+ /** Read current mail while the caller holds the lock and has verified the team. */
34
+ export async function readCurrentMailboxLocked(root: string, team: TeamState, recipient: string, onMalformed?: (line: number) => void): Promise<TeamMessage[]> {
35
+ const messages = await readUnreadMailbox(root, team.id, recipient, onMalformed)
36
+ const current: TeamMessage[] = []
37
+ const staleIds: string[] = []
38
+ for (const message of messages) {
39
+ if (isCurrentMail(team, message)) current.push(message)
40
+ else staleIds.push(message.id)
41
+ }
42
+ await discardMailboxMessages(root, team.id, recipient, staleIds)
43
+ return current
44
+ }
45
+
46
+ /** Fallback reads must enforce the same current-generation rule as live admission. */
47
+ export async function readCurrentMailbox(root: string, teamId: string, recipient: string, onMalformed?: (line: number) => void): Promise<TeamMessage[]> {
48
+ return withTeamLock(`team:${root}:${teamId}`, async () => {
49
+ const team = await readTeam(root, teamId)
50
+ return team === undefined ? [] : readCurrentMailboxLocked(root, team, recipient, onMalformed)
51
+ })
52
+ }
53
+
54
+ export function mailboxPrompt(teamId: string, recipient: string, messages: readonly TeamMessage[]): string {
55
+ return PREFIX + JSON.stringify({ teamId, recipient, ids: messages.map(message => message.id) }) + '\n\n' + mailboxBody(recipient, messages)
56
+ }
57
+
58
+ interface Receipt { teamId: string; recipient: string; ids: string[] }
59
+ function parseReceipt(text: string): Receipt | undefined {
60
+ if (!text.startsWith(PREFIX)) return undefined
61
+ try {
62
+ const value: unknown = JSON.parse(text.slice(PREFIX.length).split('\n')[0]!)
63
+ if (typeof value !== 'object' || value === null) return undefined
64
+ const raw = value as Record<string, unknown>
65
+ if (typeof raw['teamId'] !== 'string' || typeof raw['recipient'] !== 'string'
66
+ || !Array.isArray(raw['ids']) || !raw['ids'].every(id => typeof id === 'string')) return undefined
67
+ if (raw['teamId'] !== sanitizeKey(raw['teamId'])) return undefined
68
+ return { teamId: raw['teamId'], recipient: raw['recipient'], ids: raw['ids'] as string[] }
69
+ } catch { return undefined }
70
+ }
71
+
72
+ /** Only messages actually admitted to this recipient's step become read. */
73
+ export function installMailboxAdmission(ctx: Context, stateDir: string): void {
74
+ ctx.on('agent/pre-step', async (payload, next) => {
75
+ const decision = await next()
76
+ if (decision.kind !== 'enter') return decision
77
+ const root = join(payload.agent.session.header.cwd ?? process.cwd(), stateDir)
78
+ // The native runtime also wakes a parent when a background activation
79
+ // settles. A successfully delivered Team report already carries that
80
+ // result. Keep abnormal endings and missing reports as fallback signals.
81
+ const successfulSettlements = new Set(decision.messages.flatMap(input => {
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.`
85
+ ? [source.senderSessionId as string] : []
86
+ }))
87
+ const redundantSettlements = new Set<string>()
88
+ if (successfulSettlements.size > 0) {
89
+ // Narrow containment: only AgentTeams state reads degrade silently.
90
+ try {
91
+ const owned = await findTeamByCaptain(root, payload.agent.id, await leadIdentityOfAsync(ctx, payload.agent.session))
92
+ if (owned !== undefined) await withTeamLock(`team:${root}:${owned.id}`, async () => {
93
+ const team = await readTeam(root, owned.id)
94
+ if (team === undefined || !(await sessionLeadsTeamAsync(ctx, team, payload.agent.id)) || team.halted) return
95
+ const reports = await readMailbox(root, team.id, CAPTAIN_KEY)
96
+ for (const member of team.members) {
97
+ if (!successfulSettlements.has(member.id) || member.status === 'removed' || member.stopping) continue
98
+ const tasks = team.tasks.filter(task => task.assignee === member.name)
99
+ if (tasks.some(task => task.status === 'claimed' || task.status === 'in_progress')) continue
100
+ const latest = tasks.filter(task => (task.attempt ?? 0) > 0 || task.status === 'completed').sort((a, b) => b.updatedAt - a.updatedAt)[0]
101
+ if (latest?.status === 'completed' && reports.some(report => report.from === member.name && report.ts >= latest.updatedAt
102
+ && report.discardedAt === undefined && (report.deliveredAt !== undefined || report.readAt !== undefined))) {
103
+ redundantSettlements.add(member.id)
104
+ }
105
+ }
106
+ })
107
+ } catch (error: unknown) {
108
+ // A corrupt AgentTeams state file (e.g. an invalid team.json) must never
109
+ // hold the host's step admission hostage: degrade to plain admission.
110
+ ctx.logger?.warn(`agent-teams: mailbox admission degraded to plain pass-through for agent ${payload.agent.id}: could not read team state under ${root} (a team.json may be corrupt or unreadable): ${String(error)}`)
111
+ return decision
112
+ }
113
+ }
114
+ const batches = new Map<string, { receipt: Receipt; ids: Set<string>; current: Map<string, TeamMessage>; failed?: boolean }>()
115
+ const inputs = decision.messages.map(input => {
116
+ // Alpha.5/0.1.2-rc.1 public steering prepends a native sender block.
117
+ // The host-authored receipt remains a separate text block after it.
118
+ const receipt = input.content.flatMap(block => block.type === 'text' ? [parseReceipt(block.text)] : []).find(value => value !== undefined)
119
+ if (receipt === undefined) return { input }
120
+ const key = JSON.stringify([receipt.teamId, receipt.recipient])
121
+ let batch = batches.get(key)
122
+ if (batch === undefined) { batch = { receipt, ids: new Set(), current: new Map() }; batches.set(key, batch) }
123
+ for (const id of receipt.ids) batch.ids.add(id)
124
+ return { input, receipt, batch }
125
+ })
126
+ // One read/acknowledgement per recipient per step, even for a large burst.
127
+ for (const batch of batches.values()) {
128
+ const { receipt } = batch
129
+ try {
130
+ await withTeamLock(`team:${root}:${receipt.teamId}`, async () => {
131
+ const team = await readTeam(root, receipt.teamId)
132
+ if (team === undefined) return
133
+ // Captain mail is admitted for any lead session of the team: after a
134
+ // fork the human reads it in the fork while members still address the
135
+ // recorded captain. Acknowledging marks it read for both.
136
+ const isCaptainRecipient = receipt.recipient === CAPTAIN_KEY
137
+ && await sessionLeadsTeamAsync(ctx, team, payload.agent.id)
138
+ const recipientId = receipt.recipient === CAPTAIN_KEY ? team.captainSessionId
139
+ : team.members.find(member => member.name === receipt.recipient && member.status !== 'removed' && member.stopping !== true)?.id
140
+ if (!isCaptainRecipient && recipientId !== payload.agent.id) return
141
+ const selected = (await readMailbox(root, team.id, receipt.recipient)).filter(message => batch.ids.has(message.id))
142
+ const current = selected.filter(message => message.readAt === undefined && isCurrentMail(team, message))
143
+ await discardMailboxMessages(root, team.id, receipt.recipient, selected.filter(message => !isCurrentMail(team, message)).map(message => message.id))
144
+ await acknowledgeMailbox(root, team.id, receipt.recipient, current.map(message => message.id))
145
+ batch.current = new Map(current.map(message => [message.id, message]))
146
+ })
147
+ } catch (error: unknown) {
148
+ // Narrow containment, per team: the messages of this batch are not
149
+ // acked (the teamId/recipient above identify the unread mail), but the
150
+ // receipt inputs still pass through untouched instead of holding the
151
+ // host's step admission hostage.
152
+ batch.failed = true
153
+ ctx.logger?.warn(`agent-teams: mailbox admission degraded to plain pass-through for agent ${payload.agent.id}: could not read team "${receipt.teamId}" (state under ${root} may be corrupt or unreadable, recipient ${receipt.recipient} mail left unacked): ${String(error)}`)
154
+ }
155
+ }
156
+ const admitted = []
157
+ 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
160
+ if (receipt === undefined || batch === undefined || batch.failed === true) { admitted.push(input); continue }
161
+ const messages = []
162
+ for (const id of receipt.ids) {
163
+ const message = batch.current.get(id)
164
+ if (message === undefined) continue
165
+ batch.current.delete(id)
166
+ messages.push(message)
167
+ }
168
+ if (messages.length > 0) admitted.push({ ...input, content: [{ type: 'text' as const, text: mailboxBody(receipt.recipient, messages) }] })
169
+ }
170
+ // Reject only a new turn whose sole trigger was obsolete mail. During an
171
+ // existing turn, a status tool may have consumed this same mail already;
172
+ // dropping its duplicate must not block the pending tool-result response.
173
+ if (decision.messages.length > 0 && admitted.length === 0) {
174
+ const events = sessionOwnEvents(payload.agent.session)
175
+ let continuing = false
176
+ for (let i = events.length - 1; i >= 0; i--) {
177
+ const event = events[i]!
178
+ if (event.type === 'step/start' && event.data.turn === payload.turn) { continuing = true; break }
179
+ if (event.type === 'turn/start') break
180
+ }
181
+ if (!continuing) return { kind: 'reject' }
182
+ }
183
+ return { ...decision, messages: admitted }
184
+ })
185
+ }