@fish-under-sea/dsh-agent-teams-fish 1.1.0 → 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 (139) hide show
  1. package/NOTICE.md +12 -6
  2. package/README.en.md +19 -12
  3. package/README.md +19 -12
  4. package/icon.png +0 -0
  5. package/lib/git-artifact-stamp.json +1 -1
  6. package/locale/en.json +6 -0
  7. package/locale/zh.json +6 -0
  8. package/package.json +263 -258
  9. package/release-notes/v2.0.0.md +17 -0
  10. package/scripts/artwork-role-match.test.mjs +517 -0
  11. package/scripts/capabilities.test.mjs +301 -0
  12. package/scripts/check-install-channel.mjs +55 -0
  13. package/scripts/check-install-channel.test.mjs +39 -0
  14. package/scripts/clean-build.mjs +14 -0
  15. package/scripts/client-harness-migration.test.mjs +46 -0
  16. package/scripts/compatibility.test.mjs +187 -0
  17. package/scripts/corrupt-teamjson.test.mjs +180 -0
  18. package/scripts/custom-artwork.test.mjs +273 -0
  19. package/scripts/fallback-tdd.mjs +61 -0
  20. package/scripts/fixtures/harness-benchmark-scope.mjs +16 -0
  21. package/scripts/fixtures/harness-benchmark-scope.test.mjs +18 -0
  22. package/scripts/fixtures/harness-complex-case.mjs +201 -0
  23. package/scripts/fixtures/harness-complex-case.test.mjs +21 -0
  24. package/scripts/fixtures/harness-complex-oracle.mjs +63 -0
  25. package/scripts/fixtures/harness-issue-case.mjs +51 -0
  26. package/scripts/fixtures/harness-issue159-case.mjs +28 -0
  27. package/scripts/fixtures/harness-model-case.mjs +127 -0
  28. package/scripts/fixtures/harness-model-case.test.mjs +37 -0
  29. package/scripts/fixtures/harness-model-driver.mjs +100 -0
  30. package/scripts/fixtures/harness-runtime-credentials.mjs +23 -0
  31. package/scripts/fixtures/harness-runtime-entry.mjs +171 -0
  32. package/scripts/fixtures/harness-runtime-idle.mjs +42 -0
  33. package/scripts/fixtures/harness-runtime-llm.mjs +193 -0
  34. package/scripts/fixtures/harness-runtime-protocol.mjs +187 -0
  35. package/scripts/fixtures/harness-runtime-resume.mjs +24 -0
  36. package/scripts/fixtures/harness-runtime-stability.mjs +282 -0
  37. package/scripts/fixtures/harness-runtime-tools.mjs +13 -0
  38. package/scripts/fixtures/harness-runtime-web-approval.mjs +341 -0
  39. package/scripts/fixtures/issue-336-audit-worker.mjs +18 -0
  40. package/scripts/git-artifacts.mjs +64 -0
  41. package/scripts/git-artifacts.test.mjs +32 -0
  42. package/scripts/harness-compat-tdd.mjs +492 -0
  43. package/scripts/harness-issue-verify.mjs +26 -0
  44. package/scripts/harness-model-benchmark.mjs +163 -0
  45. package/scripts/harness-runtime-platform.test.mjs +31 -0
  46. package/scripts/harness-runtime-scenarios.mjs +297 -0
  47. package/scripts/harness-runtime-verify.mjs +169 -0
  48. package/scripts/harness-source-verify.mjs +211 -0
  49. package/scripts/harness-source-verify.test.mjs +97 -0
  50. package/scripts/harness-validation.mjs +68 -0
  51. package/scripts/harness-validation.test.mjs +95 -0
  52. package/scripts/http-body.test.mjs +72 -0
  53. package/scripts/import-vendor-artwork.mjs +78 -0
  54. package/scripts/inline-plan-blank-optional-tdd.mjs +121 -0
  55. package/scripts/issue-159.test.mjs +78 -0
  56. package/scripts/issue-188.test.mjs +148 -0
  57. package/scripts/issue-189.test.mjs +100 -0
  58. package/scripts/issue-203-card.test.mjs +181 -0
  59. package/scripts/issue-205.test.mjs +163 -0
  60. package/scripts/issue-234.test.mjs +424 -0
  61. package/scripts/issue-236-stale-module.test.mjs +63 -0
  62. package/scripts/issue-236.test.mjs +59 -0
  63. package/scripts/issue-262.test.mjs +98 -0
  64. package/scripts/issue-336.test.mjs +404 -0
  65. package/scripts/legacy-session-source-repair.test.mjs +201 -0
  66. package/scripts/lifecycle-verify.mjs +1573 -0
  67. package/scripts/lineage-identity.test.mjs +77 -0
  68. package/scripts/member-failure-tdd.mjs +451 -0
  69. package/scripts/member-spawn-recovery.test.mjs +92 -0
  70. package/scripts/quality-gates-amend.test.mjs +161 -0
  71. package/scripts/quality-gates-content-bound.test.mjs +572 -0
  72. package/scripts/quality-gates-cross-binding.test.mjs +184 -0
  73. package/scripts/quality-gates-excluded-scope.test.mjs +163 -0
  74. package/scripts/quality-gates-repair-scope.test.mjs +143 -0
  75. package/scripts/quality-gates-repair-wiring.test.mjs +189 -0
  76. package/scripts/quality-gates-tdd.mjs +1238 -0
  77. package/scripts/quality-gates-work-order.test.mjs +494 -0
  78. package/scripts/readme-version.mjs +89 -0
  79. package/scripts/readme-version.test.mjs +77 -0
  80. package/scripts/release-metadata.mjs +45 -0
  81. package/scripts/release-metadata.test.mjs +66 -0
  82. package/scripts/scoped-release.test.mjs +52 -0
  83. package/scripts/stability-tdd.mjs +144 -0
  84. package/scripts/stress-verify.mjs +548 -0
  85. package/scripts/symlink-support.mjs +46 -0
  86. package/scripts/sync-skill.mjs +103 -0
  87. package/scripts/tool-policies.test.mjs +280 -0
  88. package/scripts/update-skills.mjs +105 -0
  89. package/scripts/update-skills.test.mjs +79 -0
  90. package/scripts/upgrade-status.mjs +66 -0
  91. package/scripts/upgrade-status.test.mjs +83 -0
  92. package/scripts/verify-package.mjs +73 -0
  93. package/scripts/verify.mjs +2199 -0
  94. package/scripts/web-routes-verify.mjs +142 -0
  95. package/scripts/workspace-activity.test.mjs +346 -0
  96. package/scripts/workspace-summary.test.mjs +49 -0
  97. package/src/artifacts.ts +487 -0
  98. package/src/artwork-source.ts +262 -0
  99. package/src/capabilities.ts +113 -0
  100. package/src/client/ActivityPanel.module.css +2390 -0
  101. package/src/client/ActivityPanel.tsx +1507 -0
  102. package/src/client/AgentTeamsCard.module.css +148 -0
  103. package/src/client/AgentTeamsCard.tsx +155 -0
  104. package/src/client/StagingPlanEditor.tsx +829 -0
  105. package/src/client/TeamChatEntry.tsx +27 -0
  106. package/src/client/WorkspaceActivity.module.css +41 -0
  107. package/src/client/WorkspaceActivity.tsx +137 -0
  108. package/src/client/activity-model.ts +372 -0
  109. package/src/client/activity-monitor.ts +440 -0
  110. package/src/client/agent-teams-card-definition.ts +250 -0
  111. package/src/client/artwork.ts +374 -0
  112. package/src/client/icons.tsx +17 -0
  113. package/src/client/index.tsx +140 -0
  114. package/src/client/locales.ts +481 -0
  115. package/src/client/panel-geometry.ts +194 -0
  116. package/src/client/session-navigation.ts +73 -0
  117. package/src/client/workspace-state.ts +52 -0
  118. package/src/command.ts +145 -0
  119. package/src/css-modules.d.ts +4 -0
  120. package/src/event-types.ts +177 -0
  121. package/src/events.ts +78 -0
  122. package/src/harness-compat.ts +570 -0
  123. package/src/index.ts +599 -0
  124. package/src/lineage.ts +248 -0
  125. package/src/mailbox.ts +185 -0
  126. package/src/members.ts +1230 -0
  127. package/src/profiles.ts +765 -0
  128. package/src/quality-gates.ts +2124 -0
  129. package/src/scheduler.ts +554 -0
  130. package/src/snapshot.ts +333 -0
  131. package/src/state.ts +1317 -0
  132. package/src/tool-names.ts +14 -0
  133. package/src/tool-policies.ts +219 -0
  134. package/src/tools.ts +2939 -0
  135. package/src/types.ts +414 -0
  136. package/src/web-routes.ts +128 -0
  137. package/src/workspace-audit-service.ts +182 -0
  138. package/src/workspace-audit-worker.ts +12 -0
  139. package/src/workspace-audit.ts +57 -0
@@ -0,0 +1,301 @@
1
+ import test from 'node:test'
2
+ import assert from 'node:assert/strict'
3
+ import { mkdtemp, rm, readFile, writeFile, mkdir } from 'node:fs/promises'
4
+ import { tmpdir } from 'node:os'
5
+ import { join } from 'node:path'
6
+ import { createRequire } from 'node:module'
7
+ import { pathToFileURL } from 'node:url'
8
+ import { Context } from '@deepseek-ai/cordis'
9
+ import { ToolRuntime } from '@deepseek-ai/dsh-tools'
10
+ import { SystemPrompt, renderPrompt } from '@deepseek-ai/dsh-system-prompt'
11
+ import { installTeamCapabilities, TEAM_MEMBER_PROMPT } from '../lib/capabilities.js'
12
+ import { TEAM_TOOL_NAMES, MEMBER_TOOL_NAMES } from '../lib/tool-names.js'
13
+ import { usageSectionText } from '../lib/index.js'
14
+ import { formatProfilesForPrompt } from '../lib/profiles.js'
15
+ import { registerAgentTeamsTools } from '../lib/tools.js'
16
+ import { createTeamDir, archiveTeamDir, recordRetiredMemberIds } from '../lib/state.js'
17
+
18
+ const requireTools = createRequire(import.meta.resolve('@deepseek-ai/dsh-tools'))
19
+ const requireDsh = createRequire(import.meta.resolve('@deepseek-ai/dsh/package.json'))
20
+ const requireBase = createRequire(requireDsh.resolve('@deepseek-ai/dsh-base/package.json'))
21
+ const { ToolResultPruner } = await import(pathToFileURL(requireBase.resolve('@deepseek-ai/dsh-compaction-tool-result-pruner')).href)
22
+ async function mountCodeRuntime(host, workspace) {
23
+ const fibers = []
24
+ const load = async (name, config) => {
25
+ const module = await import(pathToFileURL(requireBase.resolve('@deepseek-ai/dsh-' + name)).href)
26
+ const fiber = host.plugin(module.default ?? module.NodePtcRuntime, config)
27
+ fibers.push(fiber)
28
+ await fiber.await()
29
+ }
30
+ try {
31
+ let modern = false
32
+ try { requireBase.resolve('@deepseek-ai/dsh-ptc-runtime-node'); modern = true } catch {}
33
+ if (modern) {
34
+ await load('session-projection')
35
+ let hasWorkingDirectory = false
36
+ try { requireBase.resolve('@deepseek-ai/dsh-working-directory'); hasWorkingDirectory = true } catch {}
37
+ if (hasWorkingDirectory) await load('working-directory')
38
+ await load('fs-local')
39
+ await load('subprocess-local')
40
+ await load('sandbox-local')
41
+ await load('sandbox-policy', { mode: 'danger-full-access', workspaceRoot: workspace })
42
+ await load('ptc-runtime-node', { timeoutMs: 10000, maxOutputBytes: 1048576, maxOldGenerationSizeMb: 128 })
43
+ } else await load('code-runtime-worker-thread', { computeMs: 3000, maxWallMs: 10000, maxOutputBytes: 1048576, maxOldGenerationSizeMb: 128 })
44
+ return { dispose: async () => { for (const fiber of fibers.reverse()) await fiber.dispose() } }
45
+ } catch (error) { for (const fiber of fibers.reverse()) await fiber.dispose(); throw error }
46
+ }
47
+ const { createScope } = await import(pathToFileURL(requireTools.resolve('@deepseek-ai/dsh-scope')).href)
48
+
49
+ function assertCaptainProtocol(system) {
50
+ for (const rule of [/the user's goal as description/, /attempt_id/, /never approve in that planning turn/i, /Never approve your own implementation/, /depend on a failed task/, /Resume only on a later explicit user request/]) assert.match(system, rule)
51
+ }
52
+
53
+ test('stable tool presentation uses real scoped registry and prompt assembly', async t => {
54
+ const workspace = await mkdtemp(join(tmpdir(), 'agent-teams-capabilities-'))
55
+ const stateRoot = join(workspace, '.agent-teams')
56
+ const host = new Context()
57
+ const prompt = host.plugin(SystemPrompt, { includeHarnessIdentity: false })
58
+ await prompt.await()
59
+ const tools = host.plugin(ToolRuntime, { mode: 'native' })
60
+ await tools.await()
61
+ const worker = await mountCodeRuntime(host, workspace)
62
+ const agents = []
63
+ const scopes = []
64
+ const noop = () => {}
65
+ const definitions = []
66
+ let owned
67
+ registerAgentTeamsTools({
68
+ on: () => noop, effect: setup => setup(), logger: { warn: noop, debug: noop },
69
+ tools: { register: definition => definitions.push(definition) },
70
+ agents: { get: id => agents.find(agent => agent.id === id) },
71
+ subagents: {
72
+ followup: async () => {}, registerContinuableSetup: () => noop,
73
+ async startContinuable() { assert.fail('能力展示测试不应创建成员会话') },
74
+ },
75
+ }, { stateDir: '.agent-teams', memberProvider: 'spawn', memberMaxDepth: 1, maxMembers: 8, profiles: {} })
76
+ const business = host.plugin({ inject: ['tools'], apply(ctx) {
77
+ owned = ctx
78
+ for (const definition of definitions) ctx.tools.register(definition)
79
+ ctx.provide('agents', { list: () => agents })
80
+ } })
81
+ await business.await()
82
+ const createAgent = (id, parentSession, events = []) => {
83
+ events = events.map((event, seq) => ({ ...event, seq }))
84
+ const agent = { id, status: 'idle', session: { header: { cwd: workspace, parentSession, seedLength: 0 }, events,
85
+ inheritedEventCount: 0, get seq() { return events.length },
86
+ snapshotEvents: () => events.slice(), eventAt: seq => events[seq],
87
+ append(type, data) { const event = { seq: events.length, type, data }; events.push(event); return event },
88
+ } }
89
+ const scope = createScope(owned, agent)
90
+ agent.ctx = scope.ctx
91
+ agents.push(agent)
92
+ scopes.push(scope)
93
+ return agent
94
+ }
95
+ const a = createAgent('captain-a'), b = createAgent('ordinary-b')
96
+ const pendingMembers = new Set()
97
+ const core = usageSectionText(TEAM_TOOL_NAMES.join(', '), formatProfilesForPrompt({ demo: { taskPlanning: 'captain', members: [{ name: 'reviewer' }], protocol: 'Review prepared work independently.' } }))
98
+ const options = { stateDir: '.agent-teams', isPendingMember: agent => pendingMembers.has(agent.id), captainPrompt: () => core }
99
+ const plugin = { inject: ['tools', 'systemPrompt', 'agents'], apply(ctx) { installTeamCapabilities(ctx, options) } }
100
+ let fiber = host.plugin(plugin)
101
+ await fiber.await()
102
+ const assemble = agent => host.systemPrompt.assemble({ agent, scope: agent })
103
+ const names = async agent => (await assemble(agent)).tools.map(tool => tool.name)
104
+ const execute = (agent, name, args = {}, signal = new AbortController().signal) => host.tools.execute({ name, arguments: args, callId: name + '-test', agent, signal })
105
+ const captainNames = [...TEAM_TOOL_NAMES].sort()
106
+ const header = async agent => { const assembled = await assemble(agent); return JSON.stringify({ system: renderPrompt(assembled), tools: assembled.tools }) }
107
+ const initialHeader = await header(a)
108
+ const team = { id: 'saved', name: 'Saved', captainSessionId: a.id, createdAt: 1, members: [], tasks: [], taskSeq: 0, phase: 'staged' }
109
+ try {
110
+ await t.test('first request keeps all tools and the complete fixed captain protocol', async () => {
111
+ assert.deepEqual(await names(a), captainNames)
112
+ assertCaptainProtocol(renderPrompt(await assemble(a)))
113
+ assert.equal((await names(a)).length, 14)
114
+ assert.equal(host.tools.get('agent_teams_open', a), undefined)
115
+ assert.doesNotMatch(renderPrompt(await assemble(a)), /agent_teams_open/)
116
+ t.diagnostic(JSON.stringify({ role: 'captain-idle', profiles: ['demo'], promptBytes: Buffer.byteLength(renderPrompt(await assemble(a))), schemaBytes: Buffer.byteLength(JSON.stringify((await assemble(a)).tools)) }))
117
+ })
118
+ await t.test('cancelled and invalid business calls preserve the header', async () => {
119
+ const controller = new AbortController()
120
+ controller.abort()
121
+ assert.equal((await execute(a, 'agent_teams_status', {}, controller.signal)).isError, true)
122
+ const invalid = await execute(a, 'agent_teams_create', { name: 'Invalid', profile: 'missing', approval: 'required' })
123
+ assert.equal(invalid.isError, true)
124
+ assert.match(JSON.stringify(invalid), /unknown AgentTeams profile/)
125
+ assert.equal(await header(a), initialHeader)
126
+ })
127
+ await t.test('user restrictions remain authoritative while fixed profile metadata stays visible', async () => {
128
+ const userDeny = a.ctx.tools.restrict({ deny: ['agent_teams_delete'] })
129
+ try {
130
+ assert.ok((await names(a)).includes('agent_teams_create'))
131
+ assert.ok(!(await names(a)).includes('agent_teams_delete'))
132
+ assert.deepEqual(await names(b), captainNames)
133
+ assert.match(renderPrompt(await assemble(a)), /demo \(1 member, captain planning\): Review prepared work independently/)
134
+ assertCaptainProtocol(renderPrompt(await assemble(a)))
135
+ assert.equal(await header(b), initialHeader)
136
+ } finally { userDeny() }
137
+ assert.equal(await header(a), initialHeader)
138
+ })
139
+ await t.test('the original tool allowlist can directly create and archive', async () => {
140
+ const legacy = createAgent('legacy-captain')
141
+ host.emit('agent/session-start', { agent: legacy, source: 'startup' })
142
+ const restore = legacy.ctx.tools.restrict({ allow: [...TEAM_TOOL_NAMES] })
143
+ try {
144
+ assert.deepEqual((await names(legacy)).sort(), [...TEAM_TOOL_NAMES].sort())
145
+ assert.equal(host.tools.get('agent_teams_open', legacy), undefined)
146
+ assertCaptainProtocol(renderPrompt(await assemble(legacy)))
147
+ for (const name of ['agent_teams_create', 'agent_teams_delete']) {
148
+ const result = await host.tools.execute({ name, arguments: name === 'agent_teams_create' ? { name: 'Legacy', approval: 'required' } : {}, callId: name + '-legacy', agent: legacy, signal: new AbortController().signal })
149
+ assert.equal(result.isError, false, JSON.stringify(result))
150
+ }
151
+ assertCaptainProtocol(renderPrompt(await assemble(legacy)))
152
+ } finally { restore() }
153
+ })
154
+ await t.test('status reports halted work without replacing or resuming it', async () => {
155
+ await createTeamDir(stateRoot, { ...team, phase: 'running', halted: true })
156
+ const file = join(stateRoot, team.id, 'team.json')
157
+ const before = await readFile(file, 'utf8')
158
+ const first = await execute(a, 'agent_teams_status'), second = await execute(a, 'agent_teams_status')
159
+ assert.equal(first.isError, false, JSON.stringify(first))
160
+ assert.equal(second.isError, false, JSON.stringify(second))
161
+ assert.equal(first.value.team_id, team.id)
162
+ assert.equal(first.value.halted, true)
163
+ assert.equal(await readFile(file, 'utf8'), before)
164
+ assert.equal(await header(a), initialHeader)
165
+ })
166
+ await t.test('duplicate creation directs the captain to reuse the existing team without changing it', async () => {
167
+ const file = join(stateRoot, team.id, 'team.json')
168
+ const before = await readFile(file, 'utf8')
169
+ const result = await execute(a, 'agent_teams_create', { name: 'Replacement', approval: 'required' })
170
+ assert.equal(result.isError, true, JSON.stringify(result))
171
+ assert.match(JSON.stringify(result), /Use agent_teams_status and continue the existing team/)
172
+ assert.match(JSON.stringify(result), /Do not delete and recreate it merely to continue work/)
173
+ assert.equal(await readFile(file, 'utf8'), before)
174
+ assert.equal((await execute(a, 'agent_teams_status')).value.team_id, team.id)
175
+ assert.equal(await header(a), initialHeader)
176
+ })
177
+ await t.test('fresh child is restricted to member tools before its id has been persisted', async () => {
178
+ pendingMembers.add('child')
179
+ const member = createAgent('child', a.id, [{ type: 'subagent/descriptor', data: {
180
+ version: 3, mode: 'continuable', provider: 'spawn', label: 'agent-teams:saved:worker', agentProvider: 'fake', agentModel: 'fake',
181
+ } }])
182
+ host.emit('agent/session-start', { agent: member, source: 'startup' })
183
+ pendingMembers.delete('child')
184
+ assert.deepEqual((await names(member)).sort(), [...MEMBER_TOOL_NAMES].sort())
185
+ assert.equal(renderPrompt(await assemble(member)), TEAM_MEMBER_PROMPT)
186
+ assert.equal(host.tools.get('agent_teams_open', member), undefined)
187
+ assert.equal(host.tools.get('agent_teams_approve', member), undefined)
188
+ assert.ok(Buffer.byteLength(TEAM_MEMBER_PROMPT) < 600)
189
+ t.diagnostic(JSON.stringify({ role: 'member', promptBytes: Buffer.byteLength(TEAM_MEMBER_PROMPT), schemaBytes: Buffer.byteLength(JSON.stringify((await assemble(member)).tools)) }))
190
+ })
191
+ await t.test('an ordinary subagent label cannot impersonate durable or pending membership', async () => {
192
+ const child = createAgent('ordinary-child', a.id, [{ type: 'subagent/descriptor', data: {
193
+ version: 3, mode: 'continuable', provider: 'spawn', label: 'agent-teams:saved:worker', agentProvider: 'fake', agentModel: 'fake',
194
+ } }])
195
+ host.emit('agent/session-start', { agent: child, source: 'startup' })
196
+ assert.deepEqual(await names(child), captainNames)
197
+ })
198
+ await t.test('a retired member remains restricted to member operations on cold resume', async () => {
199
+ await recordRetiredMemberIds(stateRoot, ['retired-child'])
200
+ const child = createAgent('retired-child', a.id)
201
+ host.emit('agent/session-start', { agent: child, source: 'resume' })
202
+ assert.deepEqual((await names(child)).sort(), [...MEMBER_TOOL_NAMES].sort())
203
+ })
204
+ await t.test('supported PTC presentation modes keep the operation SDK stable after status', async () => {
205
+ for (const mode of ['ptc', ...(!requireDsh('@deepseek-ai/dsh/package.json').version.startsWith('0.2.1') ? ['both'] : [])]) {
206
+ const restore = a.ctx.tools.presentAs(mode)
207
+ const assembly = await assemble(a)
208
+ const sdk = assembly.sections.find(section => section.name === 'tools:sdk').text
209
+ assert.doesNotMatch(sdk, /agent_teams_open/)
210
+ for (const name of TEAM_TOOL_NAMES) assert.ok(sdk.includes(name), name)
211
+ const before = await header(a)
212
+ const result = await host.tools.execute({ name: 'run_code', arguments: { code: 'return await tools.agent_teams_status({});', description: 'Read current team state' }, callId: 'sdk-status-' + mode, agent: a, signal: new AbortController().signal })
213
+ assert.equal(result.isError, false, JSON.stringify(result))
214
+ assert.equal(await header(a), before)
215
+ restore()
216
+ }
217
+ })
218
+ await t.test('real run_code may discard status output without losing operating rules', async () => {
219
+ const restore = a.ctx.tools.presentAs('ptc')
220
+ try {
221
+ const before = await header(a)
222
+ const result = await host.tools.execute({ name: 'run_code', arguments: { code: 'await tools.agent_teams_status({}); return "STATUS_OUTPUT_DISCARDED";', description: 'Inspect current team without returning the result' }, callId: 'discard-status-output', agent: a, signal: new AbortController().signal })
223
+ assert.equal(result.isError, false, JSON.stringify(result))
224
+ assert.match(JSON.stringify(result.content), /STATUS_OUTPUT_DISCARDED/)
225
+ assert.doesNotMatch(JSON.stringify(result.content), /attempt_id|captain protocol/)
226
+ assert.ok(a.session.events.some(event => event.type === 'tool/ptc-dispatch' && event.data.name === 'agent_teams_status'))
227
+ assertCaptainProtocol(renderPrompt(await assemble(a)))
228
+ assert.equal(await header(a), before)
229
+ } finally { restore() }
230
+ })
231
+ await t.test('HMR removes old masks and restores persisted participants in existing scopes', async () => {
232
+ await fiber.dispose()
233
+ assert.equal(host.tools.get('agent_teams_open', b), undefined)
234
+ assert.equal((await names(b)).length, 14)
235
+ assert.doesNotMatch(renderPrompt(await assemble(b)), /AgentTeams captain protocol/)
236
+ fiber = host.plugin(plugin)
237
+ await fiber.await()
238
+ assert.equal((await names(a)).length, 14)
239
+ assert.deepEqual(await names(b), captainNames)
240
+ assertCaptainProtocol(renderPrompt(await assemble(b)))
241
+ assert.equal(await header(b), initialHeader)
242
+ const retired = agents.find(agent => agent.id === 'retired-child')
243
+ assert.deepEqual((await names(retired)).sort(), [...MEMBER_TOOL_NAMES].sort())
244
+ assert.equal(renderPrompt(await assemble(retired)), TEAM_MEMBER_PROMPT)
245
+ })
246
+ await t.test('a cold captain loads its durable role before its first request', async () => {
247
+ const cold = createAgent(a.id)
248
+ host.emit('agent/session-start', { agent: cold, source: 'resume' })
249
+ assert.equal((await names(cold)).length, 14)
250
+ assert.equal(await header(cold), initialHeader)
251
+ // This new Agent has no historical tool calls. Persisted work is
252
+ // still directly addressable through the original business tools.
253
+ assert.equal(cold.session.events.length, 0)
254
+ const result = await host.tools.execute({ name: 'agent_teams_status', arguments: {}, callId: 'cold-direct-status', agent: cold, signal: new AbortController().signal })
255
+ assert.equal(result.isError, false, JSON.stringify(result))
256
+ assert.match(JSON.stringify(result.content), /Saved/)
257
+ assertCaptainProtocol(renderPrompt(await assemble(cold)))
258
+ })
259
+ await t.test('archive and idle preserve the original captain prefix', async () => {
260
+ await archiveTeamDir(stateRoot, team.id)
261
+ assert.equal((await names(a)).length, 14)
262
+ host.emit('agent/status', { agent: a, status: 'idle' })
263
+ assert.deepEqual(await names(a), captainNames)
264
+ })
265
+ await t.test('create, status and archive preserve the prefix in native and nested dispatch', async () => {
266
+ for (const nested of [false, true]) {
267
+ assert.equal(await header(a), initialHeader)
268
+ const exec = name => host.tools.execute({ name, arguments: name === 'agent_teams_create' ? { name: 'Saved', description: 'Preserve the requested goal', approval: 'required' } : {}, callId: name + '-test', agent: a, signal: new AbortController().signal, ...(nested ? { parent: {} } : {}) })
269
+ for (const name of ['agent_teams_create', 'agent_teams_status', 'agent_teams_delete']) {
270
+ const result = await exec(name)
271
+ assert.equal(result.isError, false, JSON.stringify(result))
272
+ assert.equal(await header(a), initialHeader)
273
+ }
274
+ assert.equal((await exec('agent_teams_status')).isError, true, 'Archived work is no longer an active team')
275
+ host.emit('agent/status', { agent: a, status: 'idle' })
276
+ assert.deepEqual(await names(a), captainNames)
277
+ assert.equal(await header(a), initialHeader)
278
+ }
279
+ })
280
+ await t.test('even aggressive host result pruning cannot remove the system protocol', async () => {
281
+ const pruner = new ToolResultPruner(new Context(), { thresholdChars: 128, headChars: 16, tailChars: 16 })
282
+ const rendered = [{ type: 'text', text: 'x'.repeat(256) + core + 'y'.repeat(256) }]
283
+ const pruned = pruner.pruneContent(rendered)
284
+ assert.ok(pruned, 'the real host pruner must actually remove content')
285
+ assert.doesNotMatch(JSON.stringify(pruned), /attempt_id|captain protocol/)
286
+ assertCaptainProtocol(renderPrompt(await assemble(b)))
287
+ assert.equal(await header(b), initialHeader)
288
+ })
289
+ await t.test('read failure leaves the fixed header intact', async () => {
290
+ await mkdir(join(stateRoot, 'broken'))
291
+ await writeFile(join(stateRoot, 'broken/team.json'), '{broken')
292
+ assert.equal((await execute(b, 'agent_teams_status')).isError, true)
293
+ assert.deepEqual(await names(b), captainNames)
294
+ })
295
+ } finally {
296
+ await fiber.dispose()
297
+ for (const scope of scopes.reverse()) await scope.dispose()
298
+ await business.dispose(); await tools.dispose(); await worker.dispose(); await prompt.dispose()
299
+ await rm(workspace, { recursive: true, force: true })
300
+ }
301
+ })
@@ -0,0 +1,55 @@
1
+ /** Probe real pnpm selection in a fresh profile; metadata visibility alone is insufficient. */
2
+ import { spawn } from 'node:child_process'
3
+ import { mkdtempSync, mkdirSync, writeFileSync, readFileSync, rmSync } from 'node:fs'
4
+ import { tmpdir } from 'node:os'
5
+ import { join, resolve } from 'node:path'
6
+ import { pathToFileURL } from 'node:url'
7
+
8
+ const packageName = '@fish-under-sea/dsh-agent-teams-fish'
9
+ export async function checkInstallChannel({ pnpmCli, registry, expectedVersion }) {
10
+ const url = new URL(registry)
11
+ if (url.protocol !== 'https:' && !(url.protocol === 'http:' && url.hostname === '127.0.0.1')) throw Error('Use HTTPS or a loopback fixture registry')
12
+ if (!/^\d+\.\d+\.\d+(?:-[\w.-]+)?$/.test(expectedVersion)) throw Error('Expected an exact plugin version')
13
+ const root = mkdtempSync(join(tmpdir(), 'agentteams-channel-'))
14
+ const home = join(root, 'home'), project = join(root, 'profile')
15
+ mkdirSync(home); mkdirSync(project)
16
+ writeFileSync(join(project, 'package.json'), JSON.stringify({ name: 'agentteams-channel-probe', private: true }))
17
+ writeFileSync(join(project, 'pnpm-workspace.yaml'), 'packages:\n - .\nautoInstallPeers: false\n')
18
+ const userConfig = join(home, '.npmrc')
19
+ writeFileSync(userConfig, '')
20
+ const env = Object.fromEntries(Object.entries(process.env).filter(([key]) => !/^(?:npm_config_|pnpm_config_|node_auth_token$)/i.test(key)))
21
+ Object.assign(env, { HOME: home, USERPROFILE: home, XDG_CONFIG_HOME: join(home, 'config'), XDG_CACHE_HOME: join(home, 'cache'), PNPM_HOME: join(home, 'pnpm'), npm_config_userconfig: userConfig })
22
+ async function run(args) {
23
+ return new Promise((accept, reject) => {
24
+ const child = spawn(process.execPath, [resolve(pnpmCli), ...args], { cwd: project, env, stdio: ['ignore', 'pipe', 'pipe'] })
25
+ let output = '', timedOut = false
26
+ const append = data => { output = (output + data).slice(-16384) }
27
+ child.stdout.on('data', append); child.stderr.on('data', append)
28
+ const timer = setTimeout(() => { timedOut = true; child.kill('SIGKILL') }, 120000)
29
+ child.on('error', error => { clearTimeout(timer); reject(error) })
30
+ child.on('close', code => { clearTimeout(timer); accept({ code, timedOut, output }) })
31
+ })
32
+ }
33
+ try {
34
+ const version = await run(['--version'])
35
+ if (version.code !== 0 || version.timedOut) throw Error('Cannot identify pnpm: ' + version.output)
36
+ const selected = await run(['add', `${packageName}@latest`, '--save-exact', '--lockfile-only', '--ignore-scripts', `--registry=${registry}`, '--config.fetch-retries=0'])
37
+ if (selected.code !== 0 || selected.timedOut) throw Error('Package resolution failed: ' + selected.output)
38
+ const resolvedVersion = JSON.parse(readFileSync(join(project, 'package.json'), 'utf8')).dependencies?.[packageName]
39
+ if (!resolvedVersion || !/^\d+\.\d+\.\d+(?:-[\w.-]+)?$/.test(resolvedVersion)) throw Error('pnpm did not save an exact selected version')
40
+ return { registry, pnpmVersion: version.output.trim(), requested: `${packageName}@latest`, expectedVersion, resolvedVersion, ready: resolvedVersion === expectedVersion, scope: 'Fresh-profile version resolution only; does not prove host activation or native Desktop UI.' }
41
+ } finally { rmSync(root, { recursive: true, force: true }) }
42
+ }
43
+
44
+ if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
45
+ const flags = new Map()
46
+ for (let i = 2; i < process.argv.length; i += 2) {
47
+ const key = process.argv[i], value = process.argv[i + 1]
48
+ if (!['--pnpm-cli', '--registry', '--expected-version'].includes(key) || !value || flags.has(key)) throw Error('Invalid arguments')
49
+ flags.set(key, value)
50
+ }
51
+ if (flags.size !== 3) throw Error('Required: --pnpm-cli <pnpm.mjs> --registry <url> --expected-version <version>')
52
+ const result = await checkInstallChannel({ pnpmCli: flags.get('--pnpm-cli'), registry: flags.get('--registry'), expectedVersion: flags.get('--expected-version') })
53
+ console.log(JSON.stringify(result, null, 2))
54
+ process.exitCode = result.ready ? 0 : 1
55
+ }
@@ -0,0 +1,39 @@
1
+ import assert from 'node:assert/strict'
2
+ import { createServer } from 'node:http'
3
+ import { createHash } from 'node:crypto'
4
+ import { once } from 'node:events'
5
+ import test from 'node:test'
6
+ import { checkInstallChannel } from './check-install-channel.mjs'
7
+
8
+ // Use the exact desktop pnpm supplied by CI; never silently skip this regression.
9
+ const pnpmCli = process.env.DESKTOP_PNPM_CLI
10
+ assert.ok(pnpmCli, 'DESKTOP_PNPM_CLI must point at pnpm 11.28.5/bin/pnpm.mjs')
11
+
12
+ test('desktop pnpm latest is not ready until the release ages; no policy exemption is added', async () => {
13
+ let matured = false, unavailable = false
14
+ const name = '@fish-under-sea/dsh-agent-teams-fish'
15
+ const server = createServer((request, response) => {
16
+ if (unavailable) { response.writeHead(503).end('unavailable'); return }
17
+ if (decodeURIComponent(request.url).split('?')[0] !== `/${name}`) { response.writeHead(404).end(); return }
18
+ const registry = `http://127.0.0.1:${server.address().port}`
19
+ const integrity = 'sha512-' + createHash('sha512').update('resolution-only').digest('base64')
20
+ const old = new Date(Date.now() - 3 * 86400000).toISOString()
21
+ const recent = new Date(Date.now() - (matured ? 2 * 86400000 : 60000)).toISOString()
22
+ response.setHeader('content-type', 'application/json')
23
+ response.end(JSON.stringify({ name, 'dist-tags': { latest: '1.0.1' }, time: { created: old, modified: recent, '1.0.0': old, '1.0.1': recent }, versions: Object.fromEntries(['1.0.0', '1.0.1'].map(version => [version, { name, version, dist: { tarball: `${registry}/package-${version}.tgz`, integrity } }])) }))
24
+ })
25
+ server.listen(0, '127.0.0.1'); await once(server, 'listening')
26
+ const input = { pnpmCli, registry: `http://127.0.0.1:${server.address().port}`, expectedVersion: '1.0.1' }
27
+ try {
28
+ const fresh = await checkInstallChannel(input)
29
+ assert.equal(fresh.pnpmVersion, '11.28.5')
30
+ assert.equal(fresh.resolvedVersion, '1.0.0')
31
+ assert.equal(fresh.ready, false)
32
+ matured = true
33
+ const aged = await checkInstallChannel(input)
34
+ assert.equal(aged.resolvedVersion, '1.0.1')
35
+ assert.equal(aged.ready, true)
36
+ unavailable = true
37
+ await assert.rejects(checkInstallChannel(input), /resolution failed/i)
38
+ } finally { server.closeAllConnections(); await new Promise(resolve => server.close(resolve)) }
39
+ })
@@ -0,0 +1,14 @@
1
+ import { rm } from 'node:fs/promises'
2
+ import { basename, dirname, join } from 'node:path'
3
+ import { fileURLToPath } from 'node:url'
4
+
5
+ const projectRoot = dirname(dirname(fileURLToPath(import.meta.url)))
6
+ const buildOutput = join(projectRoot, 'lib')
7
+
8
+ // Keep the destructive target explicit and scoped to this package. Stale
9
+ // compiler output otherwise survives source deletions and leaks into npm packs.
10
+ if (dirname(buildOutput) !== projectRoot || basename(buildOutput) !== 'lib') {
11
+ throw new Error(`refusing to clean unexpected build output: ${buildOutput}`)
12
+ }
13
+
14
+ await rm(buildOutput, { recursive: true, force: true })
@@ -0,0 +1,46 @@
1
+ import assert from 'node:assert/strict'
2
+ import test from 'node:test'
3
+ import { currentSessionId, openAgentTeamMember } from '../lib/client/session-navigation.js'
4
+ import { toolResultFailed, teamCardsForTurn } from '../lib/client/agent-teams-card-definition.js'
5
+
6
+ test('panel follows mainView ownership including retained subagents outside the list ids', () => {
7
+ assert.equal(currentSessionId({ current: 'old', byId: {} }), 'old')
8
+ assert.equal(currentSessionId({ current: undefined, byId: {} }), undefined)
9
+ const byId = { root: { id: 'root', retainedBy: { background: 1 } }, child: { id: 'child', retainedBy: { mainView: 1 } } }
10
+ assert.equal(currentSessionId({ byId, ids: ['root'] }), 'child')
11
+ assert.equal(currentSessionId({ byId: { root: byId.root } }), undefined)
12
+ })
13
+
14
+ test('new workspace navigation opens an exact durable member address without removed session methods', async () => {
15
+ const targets = []
16
+ assert.equal(await openAgentTeamMember({}, 'captain', 'child', undefined, { openSession: target => targets.push(target) }), 'subagent')
17
+ assert.deepEqual(targets, [{ parentSessionId: 'captain', childSessionId: 'child', mode: 'continuable' }])
18
+ await assert.rejects(openAgentTeamMember({}, 'captain', 'child'), /does not expose session navigation/)
19
+ })
20
+
21
+ test('failed create results never become successful team cards across both message formats', () => {
22
+ assert.equal(toolResultFailed({ content: [{ type: 'text', text: 'rejected' }], isError: true }), true)
23
+ assert.equal(toolResultFailed({ content: [{ type: 'tool-result', isError: true, content: [] }] }), true)
24
+ assert.equal(toolResultFailed({ content: [{ type: 'text', text: 'created' }] }), false)
25
+ })
26
+
27
+ test('legacy sessions keep their old address navigation even when uiWorkspace exists', async () => {
28
+ const calls = []
29
+ await openAgentTeamMember({ open: id => calls.push(id) }, 'parent', 'child', undefined, {
30
+ openSession: () => { throw new Error('old uiWorkspace does not accept a subagent address') },
31
+ })
32
+ assert.deepEqual(calls, ['child'])
33
+ })
34
+
35
+
36
+ test('turn tail keeps each team summary on its create turn and supports multiple teams', () => {
37
+ const first = { key: 'a', kind: 'agent-teams', location: { kind: 'step', turn: { turn: 1 } } }
38
+ const second = { key: 'b', kind: 'agent-teams', location: { kind: 'turn', turn: { turn: 1 } } }
39
+ const later = { key: 'c', kind: 'agent-teams', location: { kind: 'step', turn: { turn: 2 } } }
40
+ const prose = { key: 'd', kind: 'assistant-step', location: first.location }
41
+ const unbound = { key: 'e', kind: 'agent-teams', location: { kind: 'session' } }
42
+ const nodes = new Map([first, second, later, prose, unbound].map(node => [node.key, node]))
43
+ assert.deepEqual(teamCardsForTurn(nodes.values(), 1), [first, second])
44
+ assert.deepEqual(teamCardsForTurn(nodes.values(), 2), [later])
45
+ assert.deepEqual(teamCardsForTurn(nodes.values(), 3), [])
46
+ })