@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,262 @@
1
+ /**
2
+ * Artwork resolution for the team panel: a configured custom directory
3
+ * replaces the packaged whale mascot slug by slug, so a profile can use its
4
+ * own character art without patching the bundle.
5
+ *
6
+ * Two slug families are served:
7
+ * - the packaged set (role and action art shipped inside the bundle);
8
+ * - the vendor namespace, `member-<vendor>-<role>`, `member-<vendor>` and
9
+ * `team-lead-<vendor>`, so the same role can look different depending on
10
+ * which model vendor a member runs on. Missing combinations degrade along
11
+ * a fixed chain instead of breaking the image.
12
+ * @module dsh-agent-teams/artwork-source
13
+ */
14
+
15
+ import { readFile } from 'node:fs/promises'
16
+ import { join } from 'node:path'
17
+
18
+ /** Model vendors that may carry their own character art. */
19
+ export const ARTWORK_VENDORS: ReadonlyArray<string> = [
20
+ 'deepseek', 'qwen', 'glm', 'kimi',
21
+ 'claude', 'gemini', 'grok', 'gpt',
22
+ 'hunyuan',
23
+ // 2026-10-08:第二轮素材把厂商命名空间从 9 个扩到 15 个。前 10 个有厂商 × 岗位图,
24
+ // 后 5 个只有厂商通用图与立绘(岗位请求沿 vendor 兜底,不会 404)。
25
+ 'minimax', 'meta', 'mistral', 'rwkv', 'seed', 'ernie',
26
+ // 2026-10-11:第三轮素材把命名空间从 15 个扩到 17 个。这两个同样只有厂商通用图
27
+ // 与立绘,岗位请求沿 vendor 兜底 —— 与 meta / mistral / rwkv / seed / ernie 同档。
28
+ 'stepfun', 'jev', 'mimo',
29
+ ]
30
+
31
+ /** Role buckets the panel assigns artwork to. */
32
+ export const ARTWORK_ROLES: ReadonlyArray<string> = [
33
+ 'engineer', 'qa', 'security', 'researcher',
34
+ 'designer', 'docs', 'data', 'operator',
35
+ // 2026-10-05 登记、2026-10-08 出图:audio / video 已有 10 个厂商的岗位图,
36
+ // 其余 5 个厂商沿 vendor 通用图兜底。
37
+ 'audio', 'video',
38
+ ]
39
+
40
+ /** Artwork that ships inside the bundle; always available as a fallback. */
41
+ export const PACKAGED_ARTWORK_SLUGS: ReadonlyArray<string> = [
42
+ 'team-lead-v2.png',
43
+ 'member-researcher-v2.png', 'member-engineer-v2.png',
44
+ 'member-qa-v2.png', 'member-designer-v2.png',
45
+ 'member-security-v2.png', 'member-docs-v2.png',
46
+ 'member-data-v2.png', 'member-operator-v2.png',
47
+ 'action-working-v2.png', 'action-thinking-v2.png',
48
+ 'action-reporting-v2.png', 'action-celebrating-v2.png',
49
+ 'action-sleeping-v2.png', 'action-sending-v2.png',
50
+ ]
51
+
52
+ /** Accepted custom image extensions and their media types, most preferred first. */
53
+ const CUSTOM_EXTENSIONS: ReadonlyArray<readonly [string, string]> = [
54
+ ['.png', 'image/png'],
55
+ ['.webp', 'image/webp'],
56
+ ['.jpg', 'image/jpeg'],
57
+ ['.jpeg', 'image/jpeg'],
58
+ ['.gif', 'image/gif'],
59
+ ['.svg', 'image/svg+xml'],
60
+ ]
61
+
62
+ /** Decorative stem suffixes, stripped in any order. */
63
+ const STEM_SUFFIXES: ReadonlyArray<string> = ['-v2', '-full']
64
+
65
+ /**
66
+ * Media type for a packaged artwork file, derived from its extension.
67
+ *
68
+ * The bundle ships both `.png` artwork and `brand-<vendor>.svg` marks, so the
69
+ * host half must not assume PNG: sending SVG bytes as `image/png` makes the
70
+ * browser fail to decode them, and the badge then degrades to the activity
71
+ * image on `onError` — which looks exactly like "the SVG was never packaged"
72
+ * (that is what shipped in 0.3.1).
73
+ * @param slug - packaged artwork file name, for example `brand-qwen.svg`.
74
+ * @returns the media type for that extension, or `application/octet-stream`.
75
+ */
76
+ export function packagedArtworkContentType(slug: string): string {
77
+ for (const [extension, contentType] of CUSTOM_EXTENSIONS) {
78
+ if (slug.endsWith(extension)) return contentType
79
+ }
80
+ return 'application/octet-stream'
81
+ }
82
+
83
+ /** One artwork file on disk that answers a requested slug; packaged or custom. */
84
+ export interface ArtworkFile {
85
+ /** Absolute path the bytes were read from; reported in diagnostics. */
86
+ path: string
87
+ /** Media type derived from the file extension. */
88
+ contentType: string
89
+ /** File bytes. */
90
+ data: Buffer
91
+ }
92
+
93
+ /** Historical name of {@link ArtworkFile}, kept for the custom-directory call sites. */
94
+ export type CustomArtwork = ArtworkFile
95
+
96
+ /** Strip the decorative suffixes from a stem. */
97
+ function coreStem(stem: string): string {
98
+ let core = stem
99
+ for (let pass = 0; pass < STEM_SUFFIXES.length; pass++) {
100
+ for (const suffix of STEM_SUFFIXES) {
101
+ if (core.endsWith(suffix)) core = core.slice(0, -suffix.length)
102
+ }
103
+ }
104
+ return core
105
+ }
106
+
107
+ /** Whether the stem asks for the large-preview variant. */
108
+ function wantsFull(stem: string): boolean {
109
+ return stem.split('-').includes('full')
110
+ }
111
+
112
+ /** Split a `member-…` core into its vendor and role, either of which may be absent. */
113
+ function memberParts(core: string): { vendor: string | undefined; role: string | undefined } {
114
+ const parts = core.slice('member-'.length).split('-')
115
+ return {
116
+ vendor: parts.find((part) => ARTWORK_VENDORS.includes(part)),
117
+ role: parts.find((part) => ARTWORK_ROLES.includes(part)),
118
+ }
119
+ }
120
+
121
+ /**
122
+ * Ordered lookup chain for one requested slug, most specific first:
123
+ * `vendor+role` → `vendor` → `role` → `team-lead`. A `-full` request also
124
+ * lists its non-full sibling, so a missing large preview degrades to the
125
+ * avatar art instead of an empty frame.
126
+ *
127
+ * 厂商那一跳必须排在岗位之前(2026-10-11 修复)。此前顺序是
128
+ * `vendor+role → role → vendor`,而岗位通用图(随包鲸鱼)对**每一个**岗位都存在,
129
+ * 于是「岗位」那一跳永远抢先命中,厂商那一跳是死代码:
130
+ * - 只有厂商通用图的 7 家(meta / mistral / rwkv / seed / ernie / stepfun / jev)
131
+ * 的厂商角色永远不可达 —— 现场是「徽标显示 StepFun,头像却是通用岗位鲸鱼」;
132
+ * - `member-<vendor>-full-v2.webp` 这 17 张厂商立绘同样永远轮不到,点击放大只
133
+ * 拿到 256 岗位头像。
134
+ * 厂商身份是这套头像的主诉求(岗位通用图对任何厂商都长一样),所以厂商优先;
135
+ * 岗位图仍留在链尾,厂商未知或厂商素材缺失时照旧兜底。
136
+ * @param slug - requested artwork slug, for example `member-deepseek-qa-v2.png`.
137
+ * @returns slugs to try, most preferred first; empty when the slug is foreign.
138
+ */
139
+ export function artworkCandidates(slug: string): ReadonlyArray<string> {
140
+ if (PACKAGED_ARTWORK_SLUGS.includes(slug)) return [slug]
141
+ const stem = slug.replace(/\.[^.]+$/u, '')
142
+ // Vendor brand marks are an independent family served for the state badge:
143
+ // `brand-<vendor>.svg` first, then a `.png` sibling of the same name, then
144
+ // the family default. A brand mark has no role to degrade to, so the client
145
+ // keeps the activity art when its request fails.
146
+ if (stem.startsWith('brand-')) {
147
+ const vendor = stem.slice('brand-'.length)
148
+ return ARTWORK_VENDORS.includes(vendor)
149
+ ? [`brand-${vendor}.svg`, `brand-${vendor}.png`, 'brand.svg', 'brand.png']
150
+ : []
151
+ }
152
+ // The panel only ever requests `.png` slugs; the file on disk may use any
153
+ // accepted extension, but the requested name itself stays strict.
154
+ if (!slug.endsWith('.png')) return []
155
+ const core = coreStem(stem)
156
+ const full = wantsFull(stem)
157
+ const out: string[] = []
158
+ const push = (base: string): void => {
159
+ const names = full ? [`${base}-full-v2.png`, `${base}-v2.png`] : [`${base}-v2.png`]
160
+ for (const name of names) if (!out.includes(name)) out.push(name)
161
+ }
162
+ if (core === 'team-lead') push('team-lead')
163
+ else if (core.startsWith('team-lead-')) {
164
+ const vendor = core.slice('team-lead-'.length)
165
+ if (ARTWORK_VENDORS.includes(vendor)) {
166
+ push(`team-lead-${vendor}`)
167
+ push('team-lead')
168
+ }
169
+ } else if (core.startsWith('member-')) {
170
+ const { vendor, role } = memberParts(core)
171
+ if (vendor !== undefined && role !== undefined) {
172
+ push(`member-${vendor}-${role}`)
173
+ push(`member-${vendor}`)
174
+ push(`member-${role}`)
175
+ } else if (role !== undefined) push(`member-${role}`)
176
+ else if (vendor !== undefined) push(`member-${vendor}`)
177
+ }
178
+ return out
179
+ }
180
+
181
+ /**
182
+ * Whether the asset route may serve this slug. Nothing outside the packaged
183
+ * set and the vendor namespace reaches the filesystem, which also keeps `..`
184
+ * segments and absolute paths out.
185
+ * @param slug - requested artwork slug.
186
+ */
187
+ export function isAllowedArtwork(slug: string): boolean {
188
+ return artworkCandidates(slug).length > 0
189
+ }
190
+
191
+ /**
192
+ * File stems that answer one requested slug: the exact stem, then the same
193
+ * stem without the `-v2` release suffix (so `member-qa.png` also answers
194
+ * `member-qa-v2.png`).
195
+ * @param slug - requested artwork slug, for example `member-qa-v2.png`.
196
+ * @returns stems to probe, most specific first.
197
+ */
198
+ export function artworkStems(slug: string): ReadonlyArray<string> {
199
+ const stem = slug.replace(/\.[^.]+$/u, '')
200
+ const legacy = stem.replace(/-v2$/u, '')
201
+ return legacy === stem ? [stem] : [stem, legacy]
202
+ }
203
+
204
+ /**
205
+ * Resolve one requested slug inside a custom artwork directory.
206
+ * @param dir - absolute custom artwork directory.
207
+ * @param slug - requested artwork slug; rejected unless the panel knows it.
208
+ * @returns the first matching file, or `undefined` to fall back to packaged art.
209
+ */
210
+ export async function findCustomArtwork(dir: string, slug: string): Promise<CustomArtwork | undefined> {
211
+ if (!isAllowedArtwork(slug)) return undefined
212
+ for (const stem of artworkStems(slug)) {
213
+ for (const [extension, contentType] of CUSTOM_EXTENSIONS) {
214
+ const path = join(dir, `${stem}${extension}`)
215
+ try {
216
+ return { path, contentType, data: await readFile(path) }
217
+ } catch {
218
+ // Missing, unreadable, or a directory: try the next candidate name.
219
+ }
220
+ }
221
+ }
222
+ return undefined
223
+ }
224
+
225
+ /**
226
+ * Slug families the bundle may ship under an extension other than `.png`.
227
+ *
228
+ * The panel always requests `member-…-v2.png` / `team-lead-…-v2.png`, but the
229
+ * `-full` preview family ships as WebP: at preview resolution a lossless PNG is
230
+ * several megabytes per image, while a quality-92 WebP is a tenth of that, and
231
+ * the browser decodes both through the same `<img>` slot. Probing the accepted
232
+ * extensions for one stem — most preferred first — is exactly what the custom
233
+ * directory already does, so the bundle stays consistent with it. Brand marks
234
+ * keep the strict candidate name: their family already lists `.svg` before
235
+ * `.png`, and rewriting that order would change which mark wins.
236
+ */
237
+ const PROBED_PACKAGED_STEM = /^(?:member-|team-lead)/u
238
+
239
+ /** File names to probe for one packaged candidate, most preferred first. */
240
+ export function packagedArtworkNames(candidate: string): ReadonlyArray<string> {
241
+ const stem = candidate.replace(/\.[^.]+$/u, '')
242
+ if (!candidate.endsWith('.png') || !PROBED_PACKAGED_STEM.test(stem)) return [candidate]
243
+ return CUSTOM_EXTENSIONS.map(([extension]) => `${stem}${extension}`)
244
+ }
245
+
246
+ /**
247
+ * Resolve one requested slug inside the packaged artwork directory.
248
+ * @param dir - absolute packaged artwork directory.
249
+ * @param slug - one candidate produced by {@link artworkCandidates}.
250
+ * @returns the first matching file with the media type of the file that matched.
251
+ */
252
+ export async function findPackagedArtwork(dir: string, slug: string): Promise<ArtworkFile | undefined> {
253
+ for (const name of packagedArtworkNames(slug)) {
254
+ const path = join(dir, name)
255
+ try {
256
+ return { path, contentType: packagedArtworkContentType(name), data: await readFile(path) }
257
+ } catch {
258
+ // Not shipped under this extension: try the next one.
259
+ }
260
+ }
261
+ return undefined
262
+ }
@@ -0,0 +1,113 @@
1
+ /** Stable, agent-scoped presentation. Business authority stays in the tools. */
2
+ import { onAgentReady } from './harness-compat.ts'
3
+ import type { Context } from '@deepseek-ai/cordis'
4
+ import type { Agent } from '@deepseek-ai/dsh-agent'
5
+ import { readdirSync } from 'node:fs'
6
+ import { join } from 'node:path'
7
+ import { readTeamSync, readRetiredMemberIdsSync } from './state.ts'
8
+ import { leadIdentityOf, teamLeadMatch } from './lineage.ts'
9
+ import type { TeamState } from './types.ts'
10
+ import { MEMBER_TOOL_NAMES, TEAM_TOOL_NAMES } from './tool-names.ts'
11
+
12
+ export const TEAM_ACTIVATION_PROMPT = 'AgentTeams (Agent Teams) provides multi-agent team collaboration. Apply these rules when the user requests it (including /agent-teams) or when continuing an existing team. Mentioning, quoting, discussing, or declining AgentTeams alone is not a request to start work.'
13
+ export const TEAM_MEMBER_PROMPT = 'You are an AgentTeams member. Follow your assigned member persona and task contract. Use agent_teams_claim_task, agent_teams_update_task, agent_teams_send_message and agent_teams_status for your own work. Include the current attempt_id in updates; report completion or failure to the captain. Do not create, approve, edit or resume a team. If your durable membership is unavailable, report that to the parent instead of creating a replacement.'
14
+
15
+ interface Exposure {
16
+ member: boolean
17
+ dispose: () => void
18
+ }
19
+
20
+ interface CapabilityConfig {
21
+ stateDir: string
22
+ isPendingMember: (agent: Agent) => boolean
23
+ captainPrompt: () => string
24
+ order?: number
25
+ }
26
+
27
+ function stateRoot(agent: Agent, config: CapabilityConfig): string {
28
+ return join(agent.session.header.cwd ?? process.cwd(), config.stateDir)
29
+ }
30
+
31
+ /** Synchronous startup/HMR hydration must finish before the first assembly. */
32
+ function currentTeam(ctx: Context, agent: Agent, config: CapabilityConfig): TeamState | undefined {
33
+ const lead = leadIdentityOf(ctx, agent.session)
34
+ const root = stateRoot(agent, config)
35
+ let entries
36
+ try { entries = readdirSync(root, { withFileTypes: true }) } catch (error) {
37
+ if ((error as NodeJS.ErrnoException).code === 'ENOENT') return undefined
38
+ throw error
39
+ }
40
+ let found: TeamState | undefined
41
+ for (const entry of entries) {
42
+ if (!entry.isDirectory() || entry.name === 'archive') continue
43
+ const team = readTeamSync(root, entry.name)
44
+ if (team === undefined || (!teamLeadMatch(team, lead)
45
+ && !team.members.some(member => member.id === agent.id))) continue
46
+ if (found !== undefined) throw new Error('ambiguous AgentTeams membership')
47
+ found = team
48
+ }
49
+ return found
50
+ }
51
+
52
+ /** Call once, after all business definitions have registered. Never per member. */
53
+ export function installTeamCapabilities(ctx: Context, config: CapabilityConfig): void {
54
+ const states = new WeakMap<Agent, Exposure>()
55
+ const active = new Set<Exposure>()
56
+ let mounted = true
57
+ // Snapshot policy once: profiles, team state, and tool results must never
58
+ // rewrite this prefix or control whether core instructions are available.
59
+ const captainPrompt = `${TEAM_ACTIVATION_PROMPT}\n\n${config.captainPrompt()}`
60
+
61
+ function attach(agent: Agent): Exposure {
62
+ const prior = states.get(agent)
63
+ if (prior !== undefined) return prior
64
+ if (!mounted) throw new Error('AgentTeams capability provider is disposed')
65
+ // Determine a member's role before its first request and retain it for the
66
+ // lifetime of this scope. Team creation/archive must never rewrite the
67
+ // captain's system/tools prefix, even after a long ordinary conversation.
68
+ let member = config.isPendingMember(agent)
69
+ try {
70
+ member ||= readRetiredMemberIdsSync(stateRoot(agent, config)).has(agent.id)
71
+ const team = currentTeam(ctx, agent, config)
72
+ member ||= team !== undefined && !teamLeadMatch(team, leadIdentityOf(ctx, agent.session))
73
+ } catch (error) {
74
+ // Unrelated damaged state must not disable ordinary conversation.
75
+ // Business tools still validate durable team state before acting.
76
+ ctx.logger.warn(`agent-teams: capability hydration failed: ${String(error)}`)
77
+ }
78
+ const state: Exposure = { member, dispose: () => undefined }
79
+ let revoke: (() => void) | undefined
80
+ let disposed = false
81
+ let releaseLifetime: (() => void) | undefined
82
+ state.dispose = () => {
83
+ if (disposed) return
84
+ disposed = true
85
+ revoke?.()
86
+ releaseLifetime?.()
87
+ states.delete(agent)
88
+ active.delete(state)
89
+ }
90
+ states.set(agent, state)
91
+ active.add(state)
92
+ try {
93
+ if (member) revoke = agent.ctx.tools.restrict({
94
+ deny: TEAM_TOOL_NAMES.filter(name => !MEMBER_TOOL_NAMES.includes(name)),
95
+ })
96
+ releaseLifetime = agent.ctx.effect(() => state.dispose, 'agent-teams: capability lifetime')
97
+ return state
98
+ } catch (error) { state.dispose(); throw error }
99
+ }
100
+
101
+ ctx.systemPrompt.section({
102
+ name: 'agent-teams:usage', order: config.order ?? 117,
103
+ text: ({ agent }) => {
104
+ return agent !== undefined && states.get(agent)?.member ? TEAM_MEMBER_PROMPT : captainPrompt
105
+ },
106
+ })
107
+ onAgentReady(ctx, agent => { attach(agent) })
108
+ ctx.effect(() => () => {
109
+ mounted = false
110
+ for (const state of [...active]) state.dispose()
111
+ }, 'agent-teams: capability scopes')
112
+ for (const agent of ctx.agents.list()) attach(agent)
113
+ }