@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
@@ -0,0 +1,440 @@
1
+ /** Shared, demand-driven state for the AgentTeams browser monitor. */
2
+
3
+ /** One member row of a host snapshot. */
4
+ export interface ActivityMember {
5
+ readonly id: string
6
+ readonly name: string
7
+ readonly role: string
8
+ readonly provider?: string
9
+ readonly model?: string
10
+ readonly reasoningEffort?: string
11
+ readonly executionPrompt?: string
12
+ readonly status?: 'idle' | 'working' | 'removed'
13
+ readonly activity: 'working' | 'idle' | 'unknown'
14
+ readonly progress: number
15
+ readonly done: number
16
+ readonly total: number
17
+ readonly currentTask: string
18
+ readonly unread: number
19
+ }
20
+
21
+ /** One task row of a host snapshot. */
22
+ export interface ActivityTask {
23
+ readonly id: string
24
+ readonly subject: string
25
+ readonly description?: string
26
+ readonly status: string
27
+ readonly state: 'blocked' | 'open' | 'claimed' | 'running' | 'completed' | 'failed' | 'cancelled'
28
+ readonly assignee: string
29
+ readonly model?: string
30
+ readonly dependencies: readonly string[]
31
+ readonly depth: number
32
+ readonly kind?: string
33
+ readonly round?: number
34
+ readonly verdict?: string
35
+ /**
36
+ * Server-side audit of this task's verdict against the current bytes. Set
37
+ * when the recorded pass (or its generated work order) no longer describes
38
+ * the workspace, so the panel cannot render a bare green verdict.
39
+ */
40
+ readonly verdictStale?: string
41
+ /** Durable last-write stamp; drives the finished-member ordering (issue #192). */
42
+ readonly updatedAt?: number
43
+ }
44
+
45
+ /** One captain-inbox preview row. */
46
+ export interface ActivityMessage {
47
+ readonly from: string
48
+ readonly content: string
49
+ }
50
+
51
+ /** One team snapshot (mirrors the host TeamActivitySnapshot). */
52
+ export interface ActivityTeam {
53
+ readonly workspace: string
54
+ readonly teamId: string
55
+ readonly name: string
56
+ readonly description?: string
57
+ readonly captainSessionId: string
58
+ /** The captain's model route, for the captain's vendor artwork. */
59
+ readonly captainProvider?: string
60
+ readonly captainModel?: string
61
+ readonly phase: 'staged' | 'running'
62
+ readonly planReviewState?: 'awaiting_review' | 'awaiting_feedback'
63
+ readonly halted?: boolean
64
+ readonly members: readonly ActivityMember[]
65
+ readonly tasks: readonly ActivityTask[]
66
+ readonly messageCount: number
67
+ readonly captainInbox: readonly ActivityMessage[]
68
+ }
69
+
70
+ /** A successfully-created conversation card that currently needs updates. */
71
+ export interface ActivityMonitorTarget {
72
+ readonly key: string
73
+ readonly sessionId: string
74
+ readonly teamId: string
75
+ }
76
+
77
+ /** Latest shared response data for both the floater and conversation cards. */
78
+ export interface ActivitySnapshots {
79
+ readonly teams: readonly ActivityTeam[]
80
+ readonly archivedTeams: readonly ActivityTeam[]
81
+ }
82
+
83
+ interface RegisteredTarget extends ActivityMonitorTarget {
84
+ refs: number
85
+ active: boolean
86
+ }
87
+
88
+ const targets = new Map<string, RegisteredTarget>()
89
+ const targetListeners = new Set<() => void>()
90
+ const snapshotListeners = new Set<() => void>()
91
+ let targetSnapshot: readonly ActivityMonitorTarget[] = []
92
+ let activitySnapshots: ActivitySnapshots = { teams: [], archivedTeams: [] }
93
+ // Keep recent successful visits during reconnects without retaining every
94
+ // conversation's activity and full archive for the life of the tab.
95
+ const MAX_RETAINED_SCOPES = 8
96
+ const scopedSnapshots = {
97
+ teams: new Map<string, readonly ActivityTeam[]>(),
98
+ archivedTeams: new Map<string, readonly ActivityTeam[]>(),
99
+ }
100
+
101
+ function targetKey(sessionId: string, teamId: string): string {
102
+ return `${sessionId}\u0000${teamId}`
103
+ }
104
+
105
+ function publishTargets(): void {
106
+ targetSnapshot = [...targets.values()]
107
+ .filter((target) => target.active)
108
+ .map(({ key, sessionId, teamId }) => ({ key, sessionId, teamId }))
109
+ for (const listener of targetListeners) listener()
110
+ }
111
+
112
+ /** Subscribe to the active monitor-target list (React external-store shape). */
113
+ export function subscribeActivityMonitorTargets(listener: () => void): () => void {
114
+ targetListeners.add(listener)
115
+ return () => { targetListeners.delete(listener) }
116
+ }
117
+
118
+ /** Read the stable active-target snapshot. */
119
+ export function getActivityMonitorTargetsSnapshot(): readonly ActivityMonitorTarget[] {
120
+ return targetSnapshot
121
+ }
122
+
123
+ /**
124
+ * Register one successful AgentTeams card as a monitoring demand.
125
+ *
126
+ * The returned cleanup is reference-counted so multiple cards and React
127
+ * StrictMode remounts cannot stop another card's monitor.
128
+ */
129
+ export function monitorAgentTeam(sessionId: string, teamId: string): () => void {
130
+ const owner = sessionId.trim()
131
+ const id = teamId.trim()
132
+ if (owner === '' || id === '') return () => {}
133
+ const key = targetKey(owner, id)
134
+ const existing = targets.get(key)
135
+ if (existing === undefined) {
136
+ targets.set(key, { key, sessionId: owner, teamId: id, refs: 1, active: true })
137
+ publishTargets()
138
+ } else {
139
+ existing.refs += 1
140
+ if (!existing.active) {
141
+ existing.active = true
142
+ publishTargets()
143
+ }
144
+ }
145
+ let released = false
146
+ return () => {
147
+ if (released) return
148
+ released = true
149
+ const current = targets.get(key)
150
+ if (current === undefined) return
151
+ current.refs -= 1
152
+ if (current.refs <= 0) {
153
+ targets.delete(key)
154
+ if (current.active) publishTargets()
155
+ }
156
+ }
157
+ }
158
+
159
+ /** Stop polling targets whose final archived snapshot has been captured. */
160
+ export function settleActivityMonitorTargets(keys: ReadonlySet<string>): void {
161
+ let changed = false
162
+ for (const key of keys) {
163
+ const target = targets.get(key)
164
+ if (target?.active !== true) continue
165
+ target.active = false
166
+ changed = true
167
+ }
168
+ if (changed) publishTargets()
169
+ }
170
+
171
+ /** Subscribe to the shared live/archive snapshot. */
172
+ export function subscribeActivitySnapshots(listener: () => void): () => void {
173
+ snapshotListeners.add(listener)
174
+ return () => { snapshotListeners.delete(listener) }
175
+ }
176
+
177
+ /** Read the stable shared live/archive snapshot. */
178
+ export function getActivitySnapshotsSnapshot(): ActivitySnapshots {
179
+ return activitySnapshots
180
+ }
181
+
182
+ /** Read the rows owned by one route and optional scope for ETag comparison. */
183
+ export function getPublishedActivityRows(
184
+ field: keyof ActivitySnapshots,
185
+ scope?: string,
186
+ ): readonly ActivityTeam[] | undefined {
187
+ return scope === undefined ? activitySnapshots[field] : scopedSnapshots[field].get(scope)
188
+ }
189
+
190
+ function replaceActivityRows(
191
+ field: keyof ActivitySnapshots,
192
+ rows: readonly ActivityTeam[] | undefined,
193
+ scope: string | undefined,
194
+ ): readonly ActivityTeam[] {
195
+ const current = activitySnapshots[field]
196
+ if (rows === undefined) return current
197
+ const recent = scopedSnapshots[field]
198
+ if (scope === undefined) {
199
+ recent.clear()
200
+ return rows
201
+ }
202
+ const previous = recent.get(scope)
203
+ recent.delete(scope)
204
+ recent.set(scope, rows)
205
+ const oldest = recent.size > MAX_RETAINED_SCOPES ? recent.keys().next().value : undefined
206
+ if (oldest !== undefined) recent.delete(oldest)
207
+ if (previous === rows) return current
208
+ const otherRows = current.filter(team => team.captainSessionId !== scope && team.captainSessionId !== oldest)
209
+ return otherRows.length === current.length && rows.length === 0 ? current : [...otherRows, ...rows]
210
+ }
211
+
212
+ /** Publish full state-route responses or replace the rows for just one captain. */
213
+ export function updateActivitySnapshots(update: Partial<ActivitySnapshots>, scope?: string): void {
214
+ const next = {
215
+ teams: replaceActivityRows('teams', update.teams, scope),
216
+ archivedTeams: replaceActivityRows('archivedTeams', update.archivedTeams, scope),
217
+ }
218
+ if (next.teams === activitySnapshots.teams && next.archivedTeams === activitySnapshots.archivedTeams) return
219
+ activitySnapshots = next
220
+ for (const listener of snapshotListeners) listener()
221
+ }
222
+
223
+ /** Poll cadence for the live host snapshot route. */
224
+ export const ACTIVITY_POLL_MS = 1000
225
+ /**
226
+ * Low-frequency probe cadence while a cardless discovery session still owns
227
+ * no team. The probe keeps the panel able to pick up a team created later in
228
+ * that session (e.g. a run_code-wrapped agent_teams_create) without turning
229
+ * every ordinary session into a one-second filesystem scan.
230
+ */
231
+ export const ACTIVITY_PROBE_MS = 5000
232
+ /** Host route serving live and archived team snapshots. */
233
+ export const ACTIVITY_STATE_URL = '/plugins/dsh-agent-teams/state'
234
+ export const ACTIVITY_HALT_URL = '/plugins/dsh-agent-teams/halt'
235
+
236
+ interface ActivityFetchResponse {
237
+ readonly ok: boolean
238
+ readonly status?: number
239
+ readonly headers?: { get(name: string): string | null }
240
+ json(): Promise<unknown>
241
+ }
242
+
243
+ interface PublishedActivitySnapshot {
244
+ readonly teams: readonly ActivityTeam[]
245
+ readonly tag: string | undefined
246
+ }
247
+
248
+ async function readActivityTeams(response: ActivityFetchResponse, scope: string | undefined): Promise<readonly ActivityTeam[]> {
249
+ if (!response.ok) throw new Error('Activity unavailable')
250
+ const body = (await response.json()) as { teams?: unknown } | null
251
+ if (!Array.isArray(body?.teams) || body.teams.some(team =>
252
+ typeof team?.teamId !== 'string' || typeof team?.captainSessionId !== 'string')) {
253
+ throw new Error('Invalid activity response')
254
+ }
255
+ const teams = body.teams as readonly ActivityTeam[]
256
+ // Older hosts can ignore the query and send every team's row.
257
+ return scope === undefined ? teams : teams.filter(team => team.captainSessionId === scope)
258
+ }
259
+
260
+ /** Injectable browser primitives used by the poll controller and its tests. */
261
+ export interface ActivityPollingRuntime {
262
+ /** Connection health for views; never clears the last successful snapshot. */
263
+ readonly onStatus?: (status: 'ready' | 'error') => void
264
+ /**
265
+ * Current captain session to discover after a cold client/host restart.
266
+ * This one-time scope restores teams whose older conversation log has no
267
+ * AgentTeams card capable of registering an explicit monitor target.
268
+ */
269
+ readonly discoverySessionId?: string
270
+ readonly fetchState?: (
271
+ url: string,
272
+ init: {
273
+ readonly cache: 'no-store'
274
+ readonly signal: AbortSignal
275
+ readonly headers?: Readonly<Record<string, string>>
276
+ },
277
+ ) => Promise<ActivityFetchResponse>
278
+ readonly schedule?: (callback: () => void, intervalMs: number) => unknown
279
+ readonly cancel?: (timer: unknown) => void
280
+ readonly publishSnapshots?: (update: Partial<ActivitySnapshots>, scope?: string) => void
281
+ /** Read back the shared store when supplying a custom publisher for it. */
282
+ readonly getPublishedRows?: typeof getPublishedActivityRows
283
+ readonly settleTargets?: (keys: ReadonlySet<string>) => void
284
+ }
285
+
286
+ /** Handle returned by one current-session polling loop. */
287
+ export interface ActivityPollingController {
288
+ /** The immediate first pass, exposed so offline verification can await it. */
289
+ readonly firstTick: Promise<void>
290
+ /** Idempotently stop the timer and abort the current request. */
291
+ stop(): void
292
+ }
293
+
294
+ /**
295
+ * Start the single polling loop for the current session's requested targets.
296
+ *
297
+ * With neither targets nor a discovery session this is deliberately inert.
298
+ * Explicit card targets poll at the live cadence from the start. A discovery
299
+ * session performs an immediate live+archive restore pass, then — while it
300
+ * still owns no team — probes on a low-frequency cadence, so a team created
301
+ * later in that session (e.g. a run_code-wrapped agent_teams_create) is
302
+ * discovered without a manual reload, without turning every ordinary session
303
+ * into a one-second filesystem scan. The moment a team for the discovery
304
+ * session appears, the controller upgrades to the live one-second cadence for
305
+ * the rest of its lifetime. The caller — the session view, which stops the
306
+ * controller when the session is no longer current — bounds the lifetime, and
307
+ * archive state is refreshed when a target or a previously discovered live
308
+ * team disappears.
309
+ */
310
+ export function startActivityPolling(
311
+ monitorTargets: readonly ActivityMonitorTarget[],
312
+ runtime: ActivityPollingRuntime = {},
313
+ ): ActivityPollingController {
314
+ const discoverySessionId = runtime.discoverySessionId?.trim()
315
+ if (monitorTargets.length === 0 && (discoverySessionId === undefined || discoverySessionId === '')) {
316
+ return { firstTick: Promise.resolve(), stop: () => {} }
317
+ }
318
+ const fetchState = runtime.fetchState ?? ((url, init) => fetch(url, init))
319
+ const schedule = runtime.schedule ?? ((callback, intervalMs) => setInterval(callback, intervalMs))
320
+ const cancel = runtime.cancel ?? ((timer) => { clearInterval(timer as ReturnType<typeof setInterval>) })
321
+ const publishSnapshots = runtime.publishSnapshots ?? updateActivitySnapshots
322
+ const getPublishedRows = runtime.getPublishedRows
323
+ ?? (runtime.publishSnapshots === undefined ? getPublishedActivityRows : undefined)
324
+ const settleTargets = runtime.settleTargets ?? settleActivityMonitorTargets
325
+ const owners = new Set(monitorTargets.map(target => target.sessionId))
326
+ if (discoverySessionId) owners.add(discoverySessionId)
327
+ const scope = owners.size === 1 ? owners.values().next().value : undefined
328
+ const sessionQuery = scope ? new URLSearchParams({ session: scope }).toString() : ''
329
+ const liveUrl = sessionQuery === '' ? ACTIVITY_STATE_URL : `${ACTIVITY_STATE_URL}?${sessionQuery}&summary=1`
330
+ const archiveUrl = `${ACTIVITY_STATE_URL}?archived=1${sessionQuery === '' ? '' : `&${sessionQuery}`}`
331
+ const conditionalHeaders = (tag: string | undefined) =>
332
+ tag === undefined ? {} : { headers: { 'if-none-match': tag } }
333
+ // A manual retry can publish to the same store. A 304 only validates the
334
+ // body this controller applied, so send its tag while that body is shown.
335
+ const stillPublished = (field: keyof ActivitySnapshots, snapshot: PublishedActivitySnapshot | undefined) =>
336
+ getPublishedRows === undefined || getPublishedRows(field, scope) === snapshot?.teams
337
+ let cancelled = false
338
+ let inFlight = false
339
+ // Explicit card targets are demanded work: start at the live cadence. A
340
+ // discovery session starts probing low-frequency and upgrades on detection.
341
+ let hot = monitorTargets.length > 0
342
+ let discoveredLiveKeys = new Set<string>()
343
+ // Archive work stays pending after a failed request, even when the next live
344
+ // request is a 304 and does not publish or recompute the live snapshot.
345
+ let archiveRefreshPending = Boolean(discoverySessionId)
346
+ let missingTargets: ReadonlySet<string> = new Set()
347
+ let publishedLive: PublishedActivitySnapshot | undefined
348
+ let publishedArchive: PublishedActivitySnapshot | undefined
349
+ let controller: AbortController | undefined
350
+ let timer: unknown
351
+ const intervalMs = (): number => (hot ? ACTIVITY_POLL_MS : ACTIVITY_PROBE_MS)
352
+ const reschedule = (): void => {
353
+ cancel(timer)
354
+ timer = schedule(() => { void tick() }, intervalMs())
355
+ }
356
+ const tick = async (): Promise<void> => {
357
+ if (inFlight || cancelled) return
358
+ inFlight = true
359
+ controller = new AbortController()
360
+ try {
361
+ const liveTag = stillPublished('teams', publishedLive) ? publishedLive?.tag : undefined
362
+ const liveResponse = await fetchState(liveUrl, {
363
+ cache: 'no-store',
364
+ signal: controller.signal,
365
+ ...conditionalHeaders(liveTag),
366
+ })
367
+ if (cancelled) return
368
+ if (liveResponse.status !== 304 || liveTag === undefined) {
369
+ const liveTeams = await readActivityTeams(liveResponse, scope)
370
+ if (cancelled) return
371
+ publishSnapshots({ teams: liveTeams }, scope)
372
+ if (cancelled) return
373
+ publishedLive = { teams: liveTeams, tag: liveResponse.headers?.get('etag') ?? undefined }
374
+
375
+ const previousDiscoveredKeys = discoveredLiveKeys
376
+ discoveredLiveKeys = new Set(discoverySessionId
377
+ ? liveTeams.filter(team => team.captainSessionId === discoverySessionId).map(team => team.teamId)
378
+ : [])
379
+ archiveRefreshPending ||= [...previousDiscoveredKeys].some(teamId => !discoveredLiveKeys.has(teamId))
380
+ missingTargets = new Set(monitorTargets.filter(target => !liveTeams.some(team =>
381
+ team.captainSessionId === target.sessionId && team.teamId === target.teamId,
382
+ )).map(target => target.key))
383
+ // A discovery session found its first team: keep the live cadence.
384
+ if (!hot && discoveredLiveKeys.size > 0) {
385
+ hot = true
386
+ reschedule()
387
+ }
388
+ } else if (!stillPublished('teams', publishedLive)) {
389
+ // A concurrent write landed while the conditional request was in flight.
390
+ return
391
+ }
392
+ runtime.onStatus?.('ready')
393
+ const archiveReplaced = publishedArchive !== undefined && !stillPublished('archivedTeams', publishedArchive)
394
+ if (cancelled || (missingTargets.size === 0 && !archiveRefreshPending && !archiveReplaced)) return
395
+
396
+ // Archives are immutable per team generation. A successful fallback
397
+ // retires every missing explicit target, including legacy cards whose
398
+ // host archive no longer exists; a discovery session that already
399
+ // upgraded keeps polling, and a still-probing one keeps probing, so a
400
+ // team created later in the same session stays discoverable.
401
+ const archiveTag = archiveReplaced ? undefined : publishedArchive?.tag
402
+ const archivedResponse = await fetchState(archiveUrl, {
403
+ cache: 'no-store',
404
+ signal: controller.signal,
405
+ ...conditionalHeaders(archiveTag),
406
+ })
407
+ if (cancelled) return
408
+ if (archivedResponse.status !== 304 || archiveTag === undefined) {
409
+ const archivedTeams = await readActivityTeams(archivedResponse, scope)
410
+ if (cancelled) return
411
+ publishSnapshots({ archivedTeams }, scope)
412
+ if (cancelled) return
413
+ publishedArchive = { teams: archivedTeams, tag: archivedResponse.headers?.get('etag') ?? undefined }
414
+ } else if (!stillPublished('archivedTeams', publishedArchive)) {
415
+ return
416
+ }
417
+ archiveRefreshPending = false
418
+ const settled = missingTargets
419
+ missingTargets = new Set()
420
+ settleTargets(settled)
421
+ } catch (error: unknown) {
422
+ if ((error as { name?: unknown })?.name === 'AbortError') return
423
+ if (!cancelled) runtime.onStatus?.('error')
424
+ // Host restarting; keep the last snapshot and retry on the next tick.
425
+ } finally {
426
+ inFlight = false
427
+ }
428
+ }
429
+ const firstTick = tick()
430
+ if (timer === undefined) timer = schedule(() => { void tick() }, intervalMs())
431
+ return {
432
+ firstTick,
433
+ stop: () => {
434
+ if (cancelled) return
435
+ cancelled = true
436
+ controller?.abort()
437
+ cancel(timer)
438
+ },
439
+ }
440
+ }
@@ -0,0 +1,250 @@
1
+ /**
2
+ * AgentTeams conversation card: a lightweight in-conversation summary shown
3
+ * when a team is created — the captain's name, the member roster with whale
4
+ * avatars, and an entry point that re-activates the top-right activity
5
+ * panel (useful after the floater was closed, or when re-opening an old
6
+ * session for review).
7
+ *
8
+ * The fold anchors to the Harness's durable `tool/call` + `tool/result`
9
+ * records for `agent_teams_create`. Those are first-party session events, so
10
+ * the card survives restarts without writing an out-of-repo event type.
11
+ * @module dsh-agent-teams/client/card
12
+ */
13
+
14
+ import type {
15
+ ConversationNodeContext,
16
+ ConversationNodeDefinition,
17
+ } from '@deepseek-ai/dsh-client-ui-conversation/client'
18
+ import type { ChatConversationViewNode } from '@deepseek-ai/dsh-client-ui-chat/client'
19
+ // Module-loading imports: the declaration merges below extend modules that
20
+ // must be present in the program — a type-only import both loads them and is
21
+ // erased from the bundle.
22
+ import type {} from '@deepseek-ai/dsh-client-ui-conversation/client'
23
+ import type {} from '@deepseek-ai/dsh-session/types'
24
+
25
+ /** Final keyed Chat payload for the team summary card. */
26
+ export interface AgentTeamsCardData {
27
+ readonly teamId: string
28
+ /** The captain session that owns this team (panel follows it). */
29
+ readonly captainSessionId: string
30
+ /** The captain's model route, so the card picks the captain's vendor art. */
31
+ readonly captainProvider?: string
32
+ readonly captainModel?: string
33
+ readonly teamName: string
34
+ readonly members: readonly {
35
+ readonly id: string
36
+ readonly name: string
37
+ readonly role: string
38
+ /** Model route, so the card can pick the vendor's character art. */
39
+ readonly provider?: string
40
+ readonly model?: string
41
+ }[]
42
+ }
43
+
44
+ declare module '@deepseek-ai/dsh-client-ui-chat/client' {
45
+ interface ChatNodeDataMap {
46
+ /** Lightweight team summary card anchoring the conversation. */
47
+ 'agent-teams': AgentTeamsCardData
48
+ }
49
+ }
50
+
51
+ /** One roster row folded from the create result. */
52
+ export interface AgentTeamsCardMember {
53
+ readonly id: string
54
+ readonly name: string
55
+ readonly role: string
56
+ }
57
+
58
+ /** Folded team record (the node's business state). */
59
+ export interface AgentTeamsNodeState {
60
+ readonly teamId: string
61
+ readonly name: string
62
+ readonly accepted: boolean
63
+ /** Captain session the host reported, or `''` for a pre-#203 record. */
64
+ readonly captainSessionId: string
65
+ /** Roster the host reported, or `[]` for a pre-#203 record. */
66
+ readonly members: readonly AgentTeamsCardMember[]
67
+ }
68
+
69
+ /**
70
+ * Canonical identity the host publishes on the create result (issue #203).
71
+ * The display name intentionally stays the create call's own name.
72
+ */
73
+ export interface AgentTeamsCreateIdentity {
74
+ readonly teamId: string
75
+ readonly captainSessionId: string
76
+ readonly members: readonly AgentTeamsCardMember[]
77
+ }
78
+
79
+ /**
80
+ * Fold a team name the way the host's `sanitizeKey` does, minus the host's
81
+ * digest fallback. The host keeps Unicode letters and digits, so an ASCII-only
82
+ * client derivation turned every CJK name into the shared `team` key and the
83
+ * card could never match its live team (issue #203). Names with no letters or
84
+ * digits at all, and names longer than the host's key limit, still need the
85
+ * host's canonical id; the create result now carries it.
86
+ * @param name - the create call's team name.
87
+ * @returns the host-shaped key for the name.
88
+ */
89
+ export function teamKeyFromName(name: string): string {
90
+ const cleaned = name.normalize('NFC').trim().toLowerCase()
91
+ .replace(/[^\p{L}\p{N}]+/gu, '-')
92
+ .replace(/^-+|-+$/g, '')
93
+ return cleaned === '' ? 'team' : cleaned
94
+ }
95
+
96
+ /** Parse the only create-call fields the historic card owns. */
97
+ export function parseAgentTeamsCreateArgs(value: string): { teamId: string; name: string } | undefined {
98
+ try {
99
+ const parsed: unknown = JSON.parse(value)
100
+ if (typeof parsed !== 'object' || parsed === null || !('name' in parsed) || typeof parsed.name !== 'string') {
101
+ return undefined
102
+ }
103
+ const name = parsed.name.trim()
104
+ if (name === '') return undefined
105
+ return { teamId: teamKeyFromName(name), name }
106
+ } catch {
107
+ return undefined
108
+ }
109
+ }
110
+
111
+ /**
112
+ * Read the canonical identity the host attaches to the `agent_teams_create`
113
+ * result. Records written before the host published it carry no metadata, so
114
+ * an absent or malformed payload falls back to the client derivation.
115
+ * @param meta - the durable `tool/result` metadata payload, if any.
116
+ * @returns the canonical identity, or `undefined` when the host published none.
117
+ */
118
+ export function parseAgentTeamsCreateResult(meta: unknown): AgentTeamsCreateIdentity | undefined {
119
+ if (typeof meta !== 'object' || meta === null) return undefined
120
+ const record = meta as Record<string, unknown>
121
+ const teamId = typeof record.team_id === 'string' ? record.team_id.trim() : ''
122
+ if (teamId === '') return undefined
123
+ const captainSessionId = typeof record.captain_session_id === 'string' ? record.captain_session_id.trim() : ''
124
+ const members: AgentTeamsCardMember[] = []
125
+ if (Array.isArray(record.members)) {
126
+ for (const entry of record.members) {
127
+ if (typeof entry !== 'object' || entry === null) continue
128
+ const member = entry as Record<string, unknown>
129
+ const name = typeof member.name === 'string' ? member.name : ''
130
+ if (name === '') continue
131
+ members.push({
132
+ id: typeof member.id === 'string' ? member.id : '',
133
+ name,
134
+ role: typeof member.role === 'string' ? member.role : '',
135
+ })
136
+ }
137
+ }
138
+ return { teamId, captainSessionId, members }
139
+ }
140
+
141
+ /**
142
+ * Read the canonical team id out of a `tool/result` recorded before the host
143
+ * published {@link parseAgentTeamsCreateResult}'s metadata. Both historic
144
+ * renderings carry it and have been stable since they were introduced:
145
+ * `Team "<name>" created (id <canonical>) under <state_dir>. You are the
146
+ * captain.` and the staged `Team "<name>" plan created under <state_dir>. It is
147
+ * staged: …`, whose `state_dir` ends in the canonical id. This is the only
148
+ * legacy path for names the client cannot re-derive (host digest fallback,
149
+ * over-long names). Matches are taken right-to-left because the team name sits
150
+ * in front of the canonical segment and may itself contain a look-alike.
151
+ * @param text - the concatenated text blocks of one successful create result.
152
+ * @returns the canonical id, or `undefined` when the text carries none.
153
+ */
154
+ export function teamIdFromCreateResultText(text: string): string | undefined {
155
+ const created = [...text.matchAll(/" created \(id ([^()\s]+)\) under /gu)].at(-1)?.[1]
156
+ if (created !== undefined && created !== '') return created
157
+ const stagedPath = [...text.matchAll(/plan created under (.+?)\. It is staged: /gu)].at(-1)?.[1]
158
+ if (stagedPath === undefined) return undefined
159
+ const segment = stagedPath.split(/[\\/]/u).filter((part) => part !== '').at(-1)
160
+ return segment === undefined || segment === '' ? undefined : segment
161
+ }
162
+
163
+ /** Durable first-party tool events folded into one keyed Chat node. */
164
+ export const agentTeamsCardDefinition: ConversationNodeDefinition<AgentTeamsNodeState> = {
165
+ kind: 'agent-teams',
166
+ target: 'chat',
167
+ match: (event) => {
168
+ if (event.type === 'tool/call' && event.data.name === 'agent_teams_create') {
169
+ return parseAgentTeamsCreateArgs(event.data.arguments) === undefined
170
+ ? null
171
+ : { id: String(event.data.callId), role: 'start' }
172
+ }
173
+ if (event.type === 'tool/result' && event.data.message.source.kind === 'tool') {
174
+ return { id: String(event.data.message.source.callId), role: 'update' }
175
+ }
176
+ return null
177
+ },
178
+ start: (_context, match) => {
179
+ if (match.event.type !== 'tool/call') {
180
+ throw new Error('agent-teams card start requires agent_teams_create tool/call')
181
+ }
182
+ const parsed = parseAgentTeamsCreateArgs(match.event.data.arguments)
183
+ if (parsed === undefined) throw new Error('agent-teams card start requires valid create arguments')
184
+ return { ...parsed, accepted: false, captainSessionId: '', members: [] }
185
+ },
186
+ update: (context, match) => {
187
+ if (match.event.type !== 'tool/result') return context.state
188
+ const failed = match.event.data.error !== undefined
189
+ || toolResultFailed(match.event.data.message)
190
+ if (failed) return context.state
191
+ // The host's canonical identity wins over the client derivation. Only the
192
+ // metadata a host published itself is trusted for the roster and captain;
193
+ // a record written before it did still exposes its id in the result text.
194
+ const canonical = parseAgentTeamsCreateResult(match.event.data.meta)
195
+ const legacyId = canonical === undefined
196
+ ? teamIdFromCreateResultText(resultText(match.event.data.message))
197
+ : undefined
198
+ if (canonical === undefined && legacyId === undefined) return { ...context.state, accepted: true }
199
+ return {
200
+ ...context.state,
201
+ accepted: true,
202
+ teamId: canonical?.teamId ?? legacyId ?? context.state.teamId,
203
+ captainSessionId: canonical?.captainSessionId ?? '',
204
+ members: canonical?.members ?? [],
205
+ }
206
+ },
207
+ buildViewNode: (context): ChatConversationViewNode | null => {
208
+ if (context.start === undefined) return null
209
+ const state = context.state as AgentTeamsNodeState
210
+ if (!state.accepted) return null
211
+ return {
212
+ key: context.key,
213
+ kind: 'agent-teams',
214
+ id: context.id,
215
+ target: 'chat',
216
+ anchorSeq: context.start.event.seq,
217
+ location: context.start.location,
218
+ visibility: 'visible',
219
+ data: {
220
+ teamId: state.teamId,
221
+ captainSessionId: state.captainSessionId,
222
+ teamName: state.name,
223
+ members: state.members,
224
+ },
225
+ }
226
+ },
227
+ }
228
+
229
+ /** Concatenate the text blocks of one durable tool-result message. */
230
+ export function resultText(message: { readonly content: readonly unknown[] }): string {
231
+ return message.content
232
+ .filter((block): block is { type: 'text'; text: string } =>
233
+ typeof block === 'object' && block !== null && 'type' in block && block.type === 'text'
234
+ && 'text' in block && typeof block.text === 'string')
235
+ .map((block) => block.text)
236
+ .join('\n')
237
+ }
238
+
239
+ /** V4 tool-role results carry isError directly; older logs nest tool-result blocks. */
240
+ export function toolResultFailed(message: { readonly content: readonly unknown[]; readonly isError?: boolean }): boolean {
241
+ return message.isError === true || message.content.some(block =>
242
+ typeof block === 'object' && block !== null && 'type' in block && block.type === 'tool-result'
243
+ && 'isError' in block && block.isError === true)
244
+ }
245
+
246
+ /** Keep summaries tied to the create turn, including multiple teams in one turn. */
247
+ export function teamCardsForTurn(nodes: Iterable<ChatConversationViewNode>, turn: number): ChatConversationViewNode[] {
248
+ return [...nodes].filter(node => node.kind === 'agent-teams'
249
+ && (node.location.kind === 'turn' || node.location.kind === 'step') && node.location.turn.turn === turn)
250
+ }