@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,193 @@
1
+ import { LlmAdapter, ToolCallId, LlmError } from '@deepseek-ai/dsh-llm';
2
+ import { appendFileSync, readFileSync, existsSync } from 'node:fs';
3
+ import { join } from 'node:path';
4
+ import { createHash } from 'node:crypto';
5
+ let seq = 0;
6
+ let memberStarted = false;
7
+ const delayedMembers = new Set();
8
+ const capturedRequests = new Set();
9
+ const model = { provider: 'runtime-lab', id: 'fixture-model', name: 'Deterministic fixture', context: { contextWindow: 262144 }, defaultMaxTokens: 8192, reasoning: { efforts: [{ id: 'low', name: 'low' }, { id: 'high', name: 'high' }], defaultEffort: 'low' } };
10
+ function record(data) { appendFileSync(process.env.LAB_TRACE, JSON.stringify({ ...data, time: Date.now() }) + '\n'); }
11
+ function textChunks(text) { return [{ type: 'block-start', index: 0, blockType: 'text' }, { type: 'text-delta', index: 0, text }, { type: 'block-end', index: 0, block: { type: 'text', text } }, { type: 'usage', usage: { inputTokens: 10, outputTokens: 3 } }, { type: 'finish', reason: { kind: 'stop' } }]; }
12
+ function call(name, args) { const id = ToolCallId('lab-' + Date.now().toString(36) + '-' + (++seq)), arguments_ = JSON.stringify(args); return [{ type: 'block-start', index: 0, blockType: 'tool-call' }, { type: 'tool-call-delta', index: 0, id, name, argumentsDelta: arguments_ }, { type: 'block-end', index: 0, block: { type: 'tool-call', id, name, arguments: arguments_ } }, { type: 'usage', usage: { inputTokens: 10, outputTokens: 3 } }, { type: 'finish', reason: { kind: 'tool-calls' } }]; }
13
+ function history(options) { return options.messages.flatMap(m => m.role === 'tool' ? [{ type: 'tool-result', content: m.content, isError: m.isError, toolCallId: m.toolCallId }] : m.content ?? []); }
14
+ class FixtureAdapter extends LlmAdapter {
15
+ async listModels() { return [model, { ...model, id: 'fixture-failing' }, { ...model, id: 'fixture-fallback' }]; }
16
+ async resolveModel(provider, id) { return { ...model, provider, id }; }
17
+ async *stream(options) {
18
+ const system = options.system ?? options.messages.filter(message => message.role === 'system').flatMap(message => message.content.filter(block => block.type === 'text').map(block => block.text)).join('\n');
19
+ const blocks = history(options), tools = blocks.filter(b => b.type === 'tool-call'), names = tools.map(b => b.name);
20
+ const userText = options.messages.filter(m => m.role === 'user').flatMap(m => m.content.filter(b => b.type === 'text').map(b => b.text)).join('\n');
21
+ const lastUserText = options.messages.filter(m => m.role === 'user' && m.source?.kind === 'user').map(m => m.content.filter(b => b.type === 'text').map(b => b.text).join('\n')).filter(Boolean).at(-1) ?? '';
22
+ const currentNames = options.messages.slice(options.messages.findLastIndex(m => m.role === 'user' && m.source?.kind === 'user') + 1).flatMap(m => m.content ?? []).filter(b => b.type === 'tool-call').map(b => b.name);
23
+ const toolText = blocks.filter(b => b.type === 'tool-result').flatMap(b => b.content?.filter(t => t.type === 'text').map(t => t.text) ?? []).join('\n');
24
+ const isMember = system?.includes('MEMBER_FIXTURE') === true;
25
+ const teamTools = (options.tools ?? []).filter(t => t.name.startsWith('agent_teams_'));
26
+ const requestKey = JSON.stringify([options.purpose, isMember, teamTools.map(t => t.name)]);
27
+ if (!capturedRequests.has(requestKey)) {
28
+ capturedRequests.add(requestKey);
29
+ record({ event: 'request-snapshot', purpose: options.purpose, isMember, system: system, tools: options.tools, messages: options.messages });
30
+ }
31
+ record({ event: 'request-budget', sessionId: options.sessionId, purpose: options.purpose, isMember,
32
+ systemBytes: Buffer.byteLength(system ?? ''), systemSha256: createHash('sha256').update(system ?? '').digest('hex'),
33
+ toolsSha256: createHash('sha256').update(JSON.stringify(options.tools ?? [])).digest('hex'),
34
+ teamSchemaBytes: Buffer.byteLength(JSON.stringify(teamTools)), teamTools: teamTools.map(t => t.name) });
35
+ record({ event: 'request', sessionId: options.sessionId, purpose: options.purpose, provider: options.provider, model: options.model, reasoningEffort: options.reasoningEffort, isMember, toolNames: (options.tools ?? []).map(t => t.name), called: names, lastToolText: toolText.slice(-12000), userText: userText.slice(-6000), userMessages: options.messages.filter(m => m.role === 'user').map(m => m.content.filter(b => b.type === 'text').map(b => b.text).join('\n')) });
36
+ let chunks;
37
+ if (isMember && options.model === 'fixture-failing' && userText.includes('AgentTeams automatic task assignment')) {
38
+ // In the fallback scenario, fail after the primary has already
39
+ // committed a tool effect to the open attempt.
40
+ if (process.env.LAB_SCENARIO !== 'fallback' || names.includes('agent_teams_update_task')) {
41
+ if (process.env.LAB_SCENARIO === 'fallback') {
42
+ const team = JSON.parse(readFileSync(join(process.cwd(), '.agent-teams/runtime-lab/team.json'), 'utf8'));
43
+ const task = team.tasks.find(task => task.id === 't1');
44
+ if (task?.status !== 'in_progress' || !task.attemptId)
45
+ throw Error('Fallback fixture requires the primary to have committed an open attempt');
46
+ record({ event: 'fallback-primary-auth', sessionId: options.sessionId, attemptId: task.attemptId });
47
+ }
48
+ throw new LlmError('Runtime fixture rejected primary route', 'AUTH', { status: 401 });
49
+ }
50
+ }
51
+ if (options.purpose)
52
+ chunks = textChunks('Runtime lab');
53
+ else if (!process.env.LAB_TEAMS)
54
+ chunks = textChunks('HARNESS_PRODUCT_TURN_OK');
55
+ else if (process.env.LAB_SCENARIO === 'progressive-entry' && lastUserText.includes('ENTRY_NO_ACTIVATION'))
56
+ chunks = textChunks('ORDINARY_ENTRY_OK');
57
+ else if (isMember) {
58
+ if (userText.includes('COLD_WAKE_FIXTURE')) {
59
+ for (const chunk of textChunks('COLD_MEMBER_OK'))
60
+ yield chunk;
61
+ record({ event: 'cold-member-completed', sessionId: options.sessionId, reasoningEffort: options.reasoningEffort, model: options.model });
62
+ return;
63
+ }
64
+ memberStarted = true;
65
+ if (!delayedMembers.has(options.sessionId)) {
66
+ delayedMembers.add(options.sessionId);
67
+ await new Promise(r => setTimeout(r, 1000));
68
+ }
69
+ if (!userText.includes('AgentTeams automatic task assignment') && !userText.includes('COLD_WAKE_FIXTURE'))
70
+ chunks = textChunks('MEMBER_READY');
71
+ else if (!names.includes('agent_teams_claim_task'))
72
+ chunks = call('agent_teams_claim_task', { task_id: 't1', ...(process.env.LAB_SCENARIO === 'progressive-entry' ? { assignee: '' } : {}) });
73
+ else if (process.env.LAB_SCENARIO === 'progressive-entry' && tools.filter(t => t.name === 'agent_teams_claim_task').length === 1)
74
+ chunks = call('agent_teams_claim_task', { task_id: 't1', assignee: 'worker' });
75
+ else if (tools.filter(t => t.name === 'agent_teams_update_task').length < 2) {
76
+ if (process.env.LAB_SCENARIO === 'progressive-entry') {
77
+ const claims = tools.filter(t => t.name === 'agent_teams_claim_task');
78
+ const results = claims.map(t => blocks.find(b => b.type === 'tool-result' && b.toolCallId === t.id));
79
+ const attempts = results.map(r => JSON.stringify(r).match(/attempt_id ([^,\s)]+)/)?.[1]);
80
+ if (results.some(r => !r || r.isError) || attempts.length !== 2 || !attempts[0] || attempts[0] !== attempts[1])
81
+ throw Error('Materialized blank/self claim must keep the same attempt capability');
82
+ record({ event: 'materialized-claim-passed', sessionId: options.sessionId, attempt: attempts[0] });
83
+ }
84
+ const attempt = toolText.match(/attempt_id ([^,\s)]+)/)?.[1];
85
+ if (!attempt)
86
+ throw Error('Fixture could not read model-visible claim capability');
87
+ chunks = call('agent_teams_update_task', { task_id: 't1', status: tools.filter(t => t.name === 'agent_teams_update_task').length === 0 ? 'in_progress' : 'completed', output: 'MEMBER_TASK_DONE', attempt_id: attempt });
88
+ }
89
+ else if (!names.includes('agent_teams_send_message'))
90
+ chunks = call('agent_teams_send_message', { to: 'captain', content: 'MEMBER_REPORT_OK' });
91
+ else if (userText.includes('SECOND_WAKE_FIXTURE'))
92
+ chunks = textChunks('SECOND_WAKE_OK');
93
+ else
94
+ chunks = textChunks('MEMBER_FIRST_TURN_OK');
95
+ }
96
+ else if (process.env.LAB_COLD === '1') {
97
+ if (!tools.some(t => t.name === 'agent_teams_send_message' && t.arguments.includes('COLD_WAKE_FIXTURE')))
98
+ chunks = call('agent_teams_send_message', { to: 'worker', content: 'COLD_WAKE_FIXTURE' });
99
+ else {
100
+ await new Promise(r => setTimeout(r, 1000));
101
+ chunks = textChunks('COLD_CAPTAIN_OK');
102
+ }
103
+ }
104
+ else if (process.env.LAB_SCENARIO === 'progressive-entry' && lastUserText.includes('END_ENTRY')) {
105
+ chunks = names.includes('agent_teams_delete') ? textChunks('ENDED_ENTRY_OK') : call('agent_teams_delete', {});
106
+ }
107
+ else if (process.env.LAB_SCENARIO === 'progressive-entry' && lastUserText.includes('INSPECT_ENDED_ENTRY')) {
108
+ if (!currentNames.includes('agent_teams_status')) chunks = call('agent_teams_status', {});
109
+ else {
110
+ const result = blocks.filter(b => b.type === 'tool-result').at(-1);
111
+ if (!result?.isError || !JSON.stringify(result).includes('you do not lead or belong to any active team yet'))
112
+ throw Error('Archived-team inspection must report no active team');
113
+ chunks = textChunks('INSPECTED_ENDED_ENTRY_OK');
114
+ }
115
+ }
116
+ else if (process.env.LAB_SCENARIO === 'progressive-entry') {
117
+ const failed = blocks.find(b => b.type === 'tool-result' && b.isError);
118
+ if (failed) throw Error('Entry workflow tool failed: ' + JSON.stringify(failed));
119
+ const profile = userText.includes('demo-profile');
120
+ if (!names.includes('agent_teams_create'))
121
+ chunks = call('agent_teams_create', { name: 'runtime-lab', description: 'Entry workflow', approval: 'required', ...(profile ? { profile: 'demo-profile' } : {}) });
122
+ else if (!profile && !names.includes('agent_teams_add_member'))
123
+ chunks = call('agent_teams_add_member', { name: 'worker', role: 'MEMBER_FIXTURE', executionPrompt: 'MEMBER_FIXTURE: complete the assigned task and report.', reasoning_effort: 'high' });
124
+ else if (!names.includes('agent_teams_create_task'))
125
+ chunks = call('agent_teams_create_task', { subject: 'Entry task', description: 'Complete the deterministic task', assignee: 'worker' });
126
+ else if (userText.includes('APPROVE_ENTRY')) {
127
+ if (!names.includes('agent_teams_approve'))
128
+ chunks = call('agent_teams_approve', { confirmation: 'APPROVE_ENTRY: I approve this plan. Start it now.' });
129
+ else if (!(toolText + userText).includes('MEMBER_REPORT_OK')) {
130
+ await new Promise(r => setTimeout(r, 150));
131
+ chunks = call('agent_teams_status', {});
132
+ } else chunks = textChunks('APPROVED_ENTRY_OK');
133
+ }
134
+ else if (userText.includes('REOPEN_ENTRY') && !currentNames.includes('agent_teams_status'))
135
+ chunks = call('agent_teams_status', {});
136
+ else chunks = textChunks('STAGED_ENTRY_OK');
137
+ }
138
+ else if (!names.includes('agent_teams_create'))
139
+ chunks = call('agent_teams_create', { name: 'runtime-lab', description: 'Deterministic real Harness test', approval: 'automatic' });
140
+ else if (!names.includes('agent_teams_add_member'))
141
+ chunks = call('agent_teams_add_member', { name: 'worker', role: 'MEMBER_FIXTURE', executionPrompt: 'MEMBER_FIXTURE: complete the assigned task and report.', reasoning_effort: 'high', ...(process.env.LAB_SCENARIO === 'fallback' || process.env.LAB_SCENARIO === 'failure' ? { model: 'fixture-failing' } : {}) });
142
+ else if (!names.includes('agent_teams_create_task'))
143
+ chunks = call('agent_teams_create_task', { subject: 'Runtime fixture task', description: 'MEMBER_FIXTURE: complete the deterministic task', assignee: 'worker' });
144
+ else if (process.env.LAB_SCENARIO === 'captain-idle-wakeup') {
145
+ if ((toolText + userText).includes('MEMBER_REPORT_OK')) {
146
+ record({ event: 'captain-notified-after-yield', sessionId: options.sessionId });
147
+ chunks = textChunks('CAPTAIN_RESUMED_FROM_MEMBER_REPORT');
148
+ }
149
+ else
150
+ chunks = textChunks('CAPTAIN_YIELDED_WAITING_FOR_MEMBER');
151
+ }
152
+ else if (process.env.LAB_SCENARIO === 'failure' && toolText.includes('AUTH'))
153
+ chunks = textChunks('AGENTTEAMS_EXPECTED_FAILURE_OK');
154
+ else if (process.env.LAB_SCENARIO === 'fallback' && toolText.includes('AUTH'))
155
+ chunks = textChunks('FALLBACK_NOT_RECOVERED');
156
+ else if (process.env.LAB_SCENARIO === 'lifecycle' && !tools.some(t => t.name === 'agent_teams_send_message' && t.arguments.includes('FIFO_FIRST'))) {
157
+ for (let i = 0; i < 100 && !memberStarted; i++)
158
+ await new Promise(r => setTimeout(r, 20));
159
+ chunks = call('agent_teams_send_message', { to: 'worker', content: 'FIFO_FIRST' });
160
+ }
161
+ else if (process.env.LAB_SCENARIO === 'lifecycle' && !tools.some(t => t.name === 'agent_teams_send_message' && t.arguments.includes('FIFO_SECOND')))
162
+ chunks = call('agent_teams_send_message', { to: 'worker', content: 'FIFO_SECOND' });
163
+ else if (!(toolText + userText).includes('MEMBER_REPORT_OK')) {
164
+ // Wait inside the scripted response for the actual product task;
165
+ // repeated timed status calls can trip the host's loop guard.
166
+ const file = join(process.cwd(), '.agent-teams/runtime-lab/team.json');
167
+ const deadline = Date.now() + 20000;
168
+ while (Date.now() < deadline) {
169
+ options.signal?.throwIfAborted();
170
+ if (existsSync(file) && JSON.parse(readFileSync(file, 'utf8')).tasks.some(task => ['completed', 'failed'].includes(task.status))) break;
171
+ await new Promise(resolve => setTimeout(resolve, 10));
172
+ }
173
+ chunks = call('agent_teams_status', {});
174
+ }
175
+ else if (!tools.some(t => t.name === 'agent_teams_send_message' && t.arguments.includes('SECOND_WAKE_FIXTURE')))
176
+ chunks = call('agent_teams_send_message', { to: 'worker', content: 'SECOND_WAKE_FIXTURE' });
177
+ else {
178
+ await new Promise(r => setTimeout(r, 800));
179
+ chunks = textChunks('AGENTTEAMS_PRODUCT_TURN_OK');
180
+ }
181
+ record({ event: 'response', sessionId: options.sessionId, isMember, text: chunks.filter(c => c.type === 'text-delta').map(c => c.text).join('') });
182
+ for (const chunk of chunks) {
183
+ options.signal?.throwIfAborted();
184
+ if (chunk.type === 'block-end' && chunk.block.type === 'tool-call'
185
+ && !(options.tools ?? []).some(t => t.name === chunk.block.name))
186
+ throw Error('Fixture attempted a tool absent from the model request: ' + chunk.block.name);
187
+ yield chunk;
188
+ }
189
+ }
190
+ }
191
+ export const name = 'runtime-lab-fixture';
192
+ export const inject = ['llm'];
193
+ export function apply(ctx) { ctx.llm.registerAdapter(['runtime-lab'], new FixtureAdapter()); record({ event: 'fixture-activated' }); }
@@ -0,0 +1,187 @@
1
+ /** Published CLI/Loader regression for fixed captain rules. Only the LLM is
2
+ * scripted: actual tools, code runtime, pruning, compaction and restore run.
3
+ * This proves request content and persisted effects, not real-model reasoning.
4
+ */
5
+ import assert from 'node:assert/strict';
6
+ import { appendFileSync, readFileSync, mkdirSync, existsSync } from 'node:fs';
7
+ import { join } from 'node:path';
8
+ import { createHash, randomUUID } from 'node:crypto';
9
+ import { createUserMessage, LlmAdapter, ToolCallId } from '@deepseek-ai/dsh-llm';
10
+
11
+ const businessNames = ['agent_teams_create', 'agent_teams_approve', 'agent_teams_edit_plan', 'agent_teams_add_member', 'agent_teams_remove_member', 'agent_teams_create_task', 'agent_teams_reassign_task', 'agent_teams_claim_task', 'agent_teams_update_task', 'agent_teams_send_message', 'agent_teams_status', 'agent_teams_resume', 'agent_teams_delete'];
12
+ const goal = 'Use AgentTeams to prepare a plan, then wait for my approval.';
13
+ const cases = new Map(), requests = [];
14
+ const model = { provider: 'runtime-lab', id: 'fixture-model', name: 'Protocol compatibility fixture', context: { contextWindow: 262144 }, defaultMaxTokens: 8192, reasoning: { efforts: [{ id: 'low', name: 'low' }], defaultEffort: 'low' } };
15
+ let callSequence = 0;
16
+ const hash = value => createHash('sha256').update(value).digest('hex');
17
+ function record(value) { appendFileSync(process.env.LAB_TRACE, JSON.stringify(value) + '\n'); }
18
+ function assertProtocol(system) {
19
+ 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);
20
+ }
21
+ function sessionEvents(session) {
22
+ // Alpha.2 exposes the immutable events property; later supported hosts
23
+ // expose snapshotEvents(). Never substitute an empty log on an unknown API.
24
+ const events = typeof session.snapshotEvents === 'function' ? session.snapshotEvents() : session.events;
25
+ assert.ok(Array.isArray(events), 'Unsupported host Session event-read API');
26
+ return events;
27
+ }
28
+ function textChunks(text) {
29
+ return [{ type: 'block-start', index: 0, blockType: 'text' }, { type: 'text-delta', index: 0, text }, { type: 'block-end', index: 0, block: { type: 'text', text } }, { type: 'usage', usage: { inputTokens: 10, outputTokens: 3 } }, { type: 'finish', reason: { kind: 'stop' } }];
30
+ }
31
+ function call(name, args) {
32
+ const id = ToolCallId('protocol-' + (++callSequence)), argumentText = JSON.stringify(args);
33
+ return [{ type: 'block-start', index: 0, blockType: 'tool-call' }, { type: 'tool-call-delta', index: 0, id, name, argumentsDelta: argumentText }, { type: 'block-end', index: 0, block: { type: 'tool-call', id, name, arguments: argumentText } }, { type: 'usage', usage: { inputTokens: 10, outputTokens: 3 } }, { type: 'finish', reason: { kind: 'tool-calls' } }];
34
+ }
35
+ class ProtocolAdapter extends LlmAdapter {
36
+ async listModels() { return [model]; }
37
+ async resolveModel(provider, id) { return { ...model, provider, id }; }
38
+ async *stream(options) {
39
+ const system = options.system ?? options.messages.filter(message => message.role === 'system').flatMap(message => message.content.filter(block => block.type === 'text').map(block => block.text)).join('\n');
40
+ if (options.purpose) {
41
+ record({ event: 'protocol-background-request', purpose: options.purpose });
42
+ yield* textChunks(options.purpose === 'compaction' ? 'A staged team named protocol-team has task t1 awaiting user review.' : 'Protocol lab');
43
+ return;
44
+ }
45
+ const scenario = cases.get(options.sessionId);
46
+ assert.ok(scenario, 'Unexpected live agent request');
47
+ assertProtocol(system);
48
+ assert.doesNotMatch(system ?? '', /agent_teams_open/);
49
+ assert.ok(!(options.tools ?? []).some(tool => tool.name === 'agent_teams_open'));
50
+ const blocks = options.messages.flatMap(message => message.role === 'tool' ? [{ type: 'tool-result', content: message.content, isError: message.isError, toolCallId: message.toolCallId }] : message.content ?? []);
51
+ const failed = blocks.find(block => block.type === 'tool-result' && block.isError);
52
+ assert.equal(failed, undefined, JSON.stringify(failed));
53
+ const resultText = blocks.filter(block => block.type === 'tool-result').flatMap(block => block.content?.filter(content => content.type === 'text').map(content => content.text) ?? []).join('\n');
54
+ const snapshot = { event: 'protocol-request', label: scenario.label, phase: scenario.phase, step: scenario.step, sessionId: options.sessionId, system: system, tools: options.tools, messages: options.messages, systemSha256: hash(system ?? ''), toolsSha256: hash(JSON.stringify(options.tools ?? [])) };
55
+ requests.push(snapshot); record(snapshot);
56
+ if (!scenario.ptc && scenario.phase === 'plan' && scenario.step === 0) {
57
+ // Anonymous names cannot convey their purpose by themselves. The
58
+ // original thirteen-tool allowlist must still see the configured
59
+ // directory in its FIRST request, before any business or error result.
60
+ const north = system.split('\n').find(line => line.startsWith('- north '));
61
+ const south = system.split('\n').find(line => line.startsWith('- south '));
62
+ assert.match(north ?? '', /1 member, captain planning/);
63
+ assert.match(north ?? '', /Investigate an existing codebase and design a goal-specific task DAG/);
64
+ assert.match(south ?? '', /1 member, 1 task/);
65
+ assert.match(south ?? '', /Apply a fixed release-readiness checklist to a prepared release/);
66
+ assert.deepEqual(options.tools.map(tool => tool.name).sort(), [...businessNames].sort());
67
+ record({ event: 'protocol-legacy-profile-directory', sessionId: options.sessionId, onlyOriginalTools: true, northPurposeVisible: true, southPurposeVisible: true, north, south });
68
+ }
69
+ if (scenario.phase === 'revise') {
70
+ if (scenario.step++ === 0) {
71
+ const args = { operations: [{ action: 'update_task', task_id: 't1', subject: 'Recovered task' }] };
72
+ yield* scenario.ptc ? call('run_code', { code: `return await tools.agent_teams_edit_plan(${JSON.stringify(args)});`, description: 'Revise the existing staged task after history compaction' }) : call('agent_teams_edit_plan', args);
73
+ } else yield* textChunks('EXISTING_PLAN_REVISED');
74
+ return;
75
+ }
76
+ if (scenario.phase === 'archive') {
77
+ if (scenario.step++ === 0) yield* scenario.ptc ? call('run_code', { code: 'return await tools.agent_teams_delete({});', description: 'Archive the team at the user request' }) : call('agent_teams_delete', {});
78
+ else yield* textChunks('TEAM_ARCHIVED');
79
+ return;
80
+ }
81
+ if (scenario.ptc && scenario.step === 1) {
82
+ scenario.step++;
83
+ yield* call('run_code', { code: 'await tools.agent_teams_status({}); return "STATUS_OUTPUT_DISCARDED\\n" + "historical-output ".repeat(1000);', description: 'Inspect current team status, retaining only a receipt' });
84
+ return;
85
+ }
86
+ if (scenario.ptc && scenario.step === 2) {
87
+ assert.match(resultText, /STATUS_OUTPUT_DISCARDED/);
88
+ assert.doesNotMatch(resultText, /AgentTeams captain protocol|Tasks carry attempt_id/);
89
+ record({ event: 'protocol-ptc-output-discarded', tool: 'agent_teams_status', sessionId: options.sessionId, systemRulesPresent: true });
90
+ }
91
+ const rawStep = scenario.step++;
92
+ const step = rawStep - (scenario.ptc && rawStep > 1 ? 1 : 0);
93
+ const actions = [
94
+ ['agent_teams_create', { name: 'protocol-team', description: goal, approval: 'required', ...scenario.ptc ? {} : { profile: 'north' } }],
95
+ ...scenario.ptc ? [['agent_teams_add_member', { name: 'worker', role: 'Implement the assigned task', executionPrompt: 'Complete assigned work and report.' }]] : [],
96
+ ['agent_teams_create_task', { subject: 'Original task', description: 'A deterministic staged task', assignee: 'worker' }],
97
+ ];
98
+ if (step >= actions.length) { yield* textChunks('STAGED_PLAN_READY'); return; }
99
+ const [name, args] = actions[step];
100
+ yield* scenario.ptc ? call('run_code', { code: `return await tools.${name}(${JSON.stringify(args)});`, description: 'Build the user-reviewable staged plan' }) : call(name, args);
101
+ }
102
+ }
103
+
104
+ async function enablePtc(agent) {
105
+ if (typeof agent.ctx.tools.presentAs === 'function') return agent.ctx.tools.presentAs('ptc');
106
+ const ptc = await import('@deepseek-ai/dsh-tool-executor-ptc');
107
+ const fork = agent.ctx.plugin({ name: ptc.name, inject: ptc.inject, Config: ptc.Config, apply: ptc.apply });
108
+ return () => fork.dispose();
109
+ }
110
+
111
+ export const name = 'runtime-lab-protocol-compatibility';
112
+ export const inject = ['llm', 'agents', 'sessions', 'systemPrompt', 'compaction', 'toolResultPruner', 'tools'];
113
+ export function apply(ctx) {
114
+ ctx.llm.registerAdapter(['runtime-lab'], new ProtocolAdapter());
115
+ void (async () => {
116
+ await ctx.get('loader').await();
117
+ const send = async (agent, text) => {
118
+ agent.followup(createUserMessage({ content: [{ type: 'text', text }], source: { kind: 'user' } }));
119
+ await agent.whenIdle();
120
+ };
121
+ const usage = async agent => (await ctx.systemPrompt.assemble({ agent, scope: agent })).sections.find(section => section.name === 'agent-teams:usage')?.text ?? '';
122
+ for (const ptc of [false, true]) {
123
+ const label = ptc ? 'ptc-discard-and-compact' : 'legacy-allowlist-cold-compact';
124
+ const cwd = join(process.cwd(), label); mkdirSync(cwd, { recursive: true });
125
+ let handle = await ctx.agents.create({ sessionId: 'session-' + randomUUID(), meta: { cwd }, agentOptions: { provider: 'runtime-lab', model: 'fixture-model' } });
126
+ ctx.effect(() => () => handle.dispose());
127
+ let agent = handle.agent; await agent.whenIdle();
128
+ const scenario = { label, ptc, phase: 'plan', step: 0 }; cases.set(agent.id, scenario);
129
+ let restore = ptc ? await enablePtc(agent) : agent.ctx.tools.restrict({ allow: businessNames });
130
+ const beforeUsage = await usage(agent); assertProtocol(beforeUsage);
131
+ if (!ptc) {
132
+ const exposed = (await ctx.systemPrompt.assemble({ agent, scope: agent })).tools.map(tool => tool.name);
133
+ assert.deepEqual(exposed.sort(), [...businessNames].sort());
134
+ assert.equal(agent.ctx.tools.get('agent_teams_open', agent), undefined);
135
+ }
136
+ await send(agent, goal);
137
+ const file = join(cwd, '.agent-teams/protocol-team/team.json');
138
+ const state = () => JSON.parse(readFileSync(file, 'utf8'));
139
+ assert.equal(state().phase, 'staged'); assert.equal(state().tasks.length, 1); assert.equal(state().members.length, 1);
140
+ assert.equal(state().description, goal, 'The complete user goal must survive in durable team context');
141
+ if (!ptc) {
142
+ assert.equal(state().profile?.name, 'north');
143
+ assert.equal(state().profile?.taskPlanning, 'captain');
144
+ assert.match(state().profile?.protocol ?? '', /Investigate an existing codebase/);
145
+ }
146
+ assert.ok(!state().members[0].id, 'Staging must not spawn a member');
147
+ assert.equal(await usage(agent), beforeUsage);
148
+ if (ptc) {
149
+ assert.ok(sessionEvents(agent.session).some(event => ['tool/code-dispatch', 'tool/ptc-dispatch'].includes(event.type) && event.data.name === 'agent_teams_status'));
150
+ const pruned = ctx.toolResultPruner.pruneSession(agent.session);
151
+ assert.ok(sessionEvents(agent.session).some(event => event.type === 'compaction/prune'), 'Oversized PTC receipt must actually be pruned');
152
+ record({ event: 'protocol-pruned', label, result: pruned });
153
+ } else {
154
+ const id = agent.id;
155
+ await ctx.sessions.flush(agent.session); await restore(); await handle.dispose();
156
+ handle = await ctx.agents.resume({ resumeSessionId: id, agentOptions: { provider: 'runtime-lab', model: 'fixture-model' } });
157
+ agent = handle.agent; await agent.whenIdle();
158
+ restore = agent.ctx.tools.restrict({ allow: businessNames });
159
+ assert.equal(await usage(agent), beforeUsage);
160
+ record({ event: 'protocol-cold-restored', label, sessionId: id });
161
+ }
162
+ const compacted = await ctx.compaction.compactNow(agent, new AbortController().signal);
163
+ assert.ok(compacted, 'The fixture must actually compact useful history');
164
+ assert.ok(sessionEvents(agent.session).some(event => event.type === 'compaction/summary'));
165
+ assert.equal(await usage(agent), beforeUsage);
166
+ record({ event: 'protocol-compacted', label, compacted });
167
+ scenario.phase = 'revise'; scenario.step = 0;
168
+ await send(agent, 'Change the existing staged task t1 subject to Recovered task. Keep the same team and wait for my approval.');
169
+ assert.equal(state().tasks[0].subject, 'Recovered task');
170
+ assert.equal(state().tasks.length, 1); assert.equal(state().members.length, 1); assert.equal(state().phase, 'staged');
171
+ assert.equal(await usage(agent), beforeUsage);
172
+ const finalState = state();
173
+ scenario.phase = 'archive'; scenario.step = 0;
174
+ await send(agent, 'End and archive this team and its unfinished staged task.');
175
+ assert.equal(existsSync(file), false, 'Archived team must leave active state');
176
+ assert.equal(existsSync(join(cwd, '.agent-teams/archive/protocol-team/team.json')), true);
177
+ assert.equal(await usage(agent), beforeUsage);
178
+ const captured = requests.filter(request => request.sessionId === agent.id);
179
+ assert.equal(new Set(captured.map(request => request.systemSha256)).size, 1, 'System prefix changed across planning, restore or compaction');
180
+ assert.equal(new Set(captured.map(request => request.toolsSha256)).size, 1, 'Tools prefix changed across planning, restore or compaction');
181
+ record({ event: 'protocol-case-passed', label, requests: captured.length, compactedHistory: true, persistedSubject: finalState.tasks[0].subject, archived: true, ...finalState.profile ? { profile: finalState.profile.name } : {} });
182
+ await restore(); await ctx.sessions.flush(agent.session); await handle.dispose();
183
+ }
184
+ process.stdout.write('PROTOCOL_COMPATIBILITY_OK\n');
185
+ ctx.get('appExit')(0);
186
+ })().catch(error => { process.stderr.write(String(error.stack ?? error) + '\n'); ctx.get('appExit')(1); });
187
+ }
@@ -0,0 +1,24 @@
1
+ /** Test-only driver mounted by the real published CLI after a cold restart. */
2
+ import { createUserMessage } from '@deepseek-ai/dsh-llm';
3
+ export const name = 'runtime-lab-cold-resume';
4
+ export const inject = ['agents', 'sessions'];
5
+ export function apply(ctx) {
6
+ void (async () => {
7
+ await ctx.get('loader').await();
8
+ const handle = await ctx.agents.resume({ resumeSessionId: process.env.LAB_PARENT_SESSION, agentOptions: { provider: 'runtime-lab', model: 'fixture-model' } });
9
+ ctx.effect(() => () => handle.dispose());
10
+ await handle.agent.whenIdle();
11
+ handle.agent.followup(createUserMessage({ content: [{ type: 'text', text: 'COLD_RESTORE_FIXTURE' }], source: { kind: 'user' } }));
12
+ await handle.agent.whenIdle();
13
+ for (const agent of ctx.agents.list()) {
14
+ await agent.whenIdle();
15
+ // Best effort: a handle may close while this loop awaits an earlier
16
+ // agent. Closing persists, so a closed handle needs no flush — and
17
+ // the host rejects flushing one.
18
+ try { if (ctx.sessions.get(agent.id) === agent.session) await ctx.sessions.flush(agent.session); }
19
+ catch (error) { if (String(error?.name) !== 'SessionHandleClosedError') throw error; }
20
+ }
21
+ process.stdout.write('COLD_RESTORE_DRIVER_DONE\n');
22
+ ctx.get('appExit')(0);
23
+ })().catch(error => { process.stderr.write(String(error) + '\n'); ctx.get('appExit')(1); });
24
+ }