@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,341 @@
1
+ /** Published-artifact Web approval regression. Only the external model is scripted.
2
+ * The driver sends one user message, one successful authenticated HTTP approval,
3
+ * and two rejected boundary requests. A model response gate keeps the member
4
+ * silent until the captain acknowledges Web approval and becomes idle, so the
5
+ * approval and member-report wakeups cannot conflate.
6
+ */
7
+ import assert from 'node:assert/strict';
8
+ import { appendFileSync, readFileSync } from 'node:fs';
9
+ import fs from 'node:fs';
10
+ import { syncBuiltinESMExports } from 'node:module';
11
+ import { createHash, randomUUID } from 'node:crypto';
12
+ import { join } from 'node:path';
13
+ import { createUserMessage, LlmAdapter, ToolCallId } from '@deepseek-ai/dsh-llm';
14
+
15
+ const events = [];
16
+ const handledControlMessages = new Set();
17
+ let callSequence = 0;
18
+ let releaseMember;
19
+ const memberGate = new Promise(resolve => { releaseMember = resolve; });
20
+ const model = { provider: 'runtime-lab', id: 'fixture-model', name: 'Web approval fixture', context: { contextWindow: 262144 }, defaultMaxTokens: 8192, reasoning: { efforts: [{ id: 'low', name: 'low' }, { id: 'high', name: 'high' }], defaultEffort: 'low' } };
21
+ function record(data) {
22
+ const event = { ...data, order: events.length, time: Date.now() };
23
+ events.push(event);
24
+ appendFileSync(process.env.LAB_TRACE, JSON.stringify(event) + '\n');
25
+ return event;
26
+ }
27
+ function textChunks(text) {
28
+ 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' } }];
29
+ }
30
+ function call(name, args) {
31
+ const id = ToolCallId('web-approval-' + (++callSequence)), arguments_ = JSON.stringify(args);
32
+ 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' } }];
33
+ }
34
+ function sha256(value) { return createHash('sha256').update(value).digest('hex'); }
35
+ /** A persisted reviewed revision consumed through the real authenticated route. */
36
+ async function verifyWorkspaceAudit(baseUrl, cookie, captainSessionId) {
37
+ const path = 'audit-336/mask.bin', file = join(process.cwd(), path);
38
+ fs.mkdirSync(join(process.cwd(), 'audit-336'), { recursive: true });
39
+ const bytes = Buffer.alloc(128 * 1024, 65);
40
+ fs.writeFileSync(file, bytes);
41
+ const old = new Date(Date.now() - 10000);
42
+ fs.utimesSync(file, old, old);
43
+ const stats = fs.statSync(file), now = Date.now();
44
+ const team = {
45
+ id: 'audit-336', name: 'audit-336', captainSessionId, createdAt: now, taskSeq: 2, members: [],
46
+ tasks: [
47
+ { id: 't1', subject: 'Generate mask', kind: 'implementation', status: 'completed', dependencies: [], createdAt: now, updatedAt: now, attempt: 1, objective: 'Generate mask', inScope: ['audit-336/'], verify: ['generate mask'], acceptance: ['mask exists'], changedPaths: [path], acceptanceResults: [{ criterion: 'mask exists', status: 'passed' }], commandsRun: [{ command: 'generate mask', status: 'passed', exitCode: 0 }] },
48
+ { id: 't2', subject: 'Review mask', kind: 'review', status: 'completed', dependencies: ['t1'], createdAt: now, updatedAt: now, attempt: 1, verdict: 'pass', reviewedTaskId: 't1', reviewedAttempt: 1, objective: 'Review mask', acceptance: ['no blockers'], reviewedArtifacts: [{ path, present: true, sha256: sha256(bytes), size: bytes.length, mtimeMs: stats.mtimeMs }], reviewedScope: ['audit-336/'] },
49
+ ],
50
+ };
51
+ const dir = join(process.cwd(), '.agent-teams', team.id);
52
+ fs.mkdirSync(join(dir, 'inbox'), { recursive: true });
53
+ const statePath = join(dir, 'team.json'), stateBytes = JSON.stringify(team);
54
+ fs.writeFileSync(statePath, stateBytes);
55
+ const original = { openSync: fs.openSync, readSync: fs.readSync, closeSync: fs.closeSync };
56
+ const resolved = fs.realpathSync(file), handles = new Set();
57
+ let hostBytesRead = 0;
58
+ fs.openSync = function(path, ...args) { const fd = original.openSync.call(this, path, ...args); if (String(path) === resolved) handles.add(fd); return fd; };
59
+ fs.readSync = function(fd, ...args) { const read = original.readSync.call(this, fd, ...args); if (handles.has(fd)) hostBytesRead += read; return read; };
60
+ fs.closeSync = function(fd) { handles.delete(fd); return original.closeSync.call(this, fd); };
61
+ syncBuiltinESMExports();
62
+ try {
63
+ const query = new URLSearchParams({ session: captainSessionId, summary: '1' });
64
+ const poll = async (tag) => {
65
+ const headers = tag === undefined ? { cookie } : { cookie, 'if-none-match': tag };
66
+ const response = await fetch(`${baseUrl}/plugins/dsh-agent-teams/state?${query}`, { headers, signal: AbortSignal.timeout(10000) });
67
+ assert.equal(response.status, 200);
68
+ const snapshot = (await response.json()).teams.find(item => item.teamId === team.id);
69
+ assert.ok(snapshot, 'The published collector must retain the audit team');
70
+ return { snapshot, tag: response.headers.get('etag') };
71
+ };
72
+ const { snapshot: before, tag } = await poll();
73
+ assert.match(tag, /^W\/"/);
74
+ fs.writeFileSync(file, Buffer.alloc(bytes.length, 66));
75
+ fs.utimesSync(file, stats.atime, stats.mtime);
76
+ const { snapshot: after, tag: changedTag } = await poll(tag);
77
+ assert.notEqual(changedTag, tag, 'artifact drift must invalidate an otherwise unchanged snapshot');
78
+ assert.equal(readFileSync(statePath, 'utf8'), stateBytes, 'Only the artifact changed');
79
+ const snapshot = {
80
+ before: { ok: before.delivery.ok, deliverable: before.deliverable },
81
+ after: { ok: after.delivery.ok, deliverable: after.deliverable, stale: typeof after.tasks.find(task => task.id === 't2').verdictStale === 'string' },
82
+ hostBytesRead,
83
+ };
84
+ // Stable credential-free snapshot from a real CLI/Loader, actual
85
+ // published artifact, auth service, HTTP route and worker entry.
86
+ assert.deepEqual(snapshot, { before: { ok: true, deliverable: true }, after: { ok: false, deliverable: false, stale: true }, hostBytesRead: 0 });
87
+ record({ event: 'web-workspace-audit', ...snapshot });
88
+ } finally { Object.assign(fs, original); syncBuiltinESMExports(); }
89
+ }
90
+ async function waitFor(predicate, description) {
91
+ const deadline = Date.now() + 25000;
92
+ while (!predicate()) {
93
+ assert.ok(Date.now() < deadline, 'Timed out: ' + description);
94
+ await new Promise(resolve => setTimeout(resolve, 25));
95
+ }
96
+ }
97
+ class WebApprovalAdapter extends LlmAdapter {
98
+ async listModels() { return [model]; }
99
+ async resolveModel(provider, id) { return { ...model, provider, id }; }
100
+ async *stream(options) {
101
+ 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');
102
+ if (options.purpose) { yield* textChunks('Web approval lab'); return; }
103
+ const blocks = options.messages.flatMap(message => message.role === 'tool' ? [{ type: 'tool-result', content: message.content, isError: message.isError, toolCallId: message.toolCallId }] : message.content ?? []);
104
+ const calls = blocks.filter(block => block.type === 'tool-call');
105
+ const names = calls.map(block => block.name);
106
+ const userText = options.messages.filter(message => message.role === 'user').flatMap(message => message.content.filter(block => block.type === 'text').map(block => block.text)).join('\n');
107
+ const toolText = blocks.filter(block => block.type === 'tool-result').flatMap(block => block.content?.filter(content => content.type === 'text').map(content => content.text) ?? []).join('\n');
108
+ const failed = blocks.find(block => block.type === 'tool-result' && block.isError);
109
+ assert.equal(failed, undefined, 'Real workflow tool failed: ' + JSON.stringify(failed));
110
+ const isMember = system?.includes('WEB_APPROVAL_MEMBER') === true;
111
+ record({ event: 'web-request', sessionId: options.sessionId, isMember, model: options.model, reasoningEffort: options.reasoningEffort, system: system, tools: options.tools, messages: options.messages });
112
+ // Supported pre-v3 hosts use the producer-owned legacy wrapper. Keep
113
+ // checking the plugin identity so unrelated plugin messages cannot
114
+ // satisfy the approval/report assertions.
115
+ const pluginMessages = options.messages.filter(message => message.role === 'user' && (
116
+ message.source?.kind === 'agent-teams'
117
+ || (message.source?.kind === 'plugin' && message.source.plugin === '@nanmicoder/dsh-agent-teams')));
118
+ const messageText = message => message.content.filter(block => block.type === 'text').map(block => block.text).join('\n');
119
+ const approvals = pluginMessages.filter(message => messageText(message).includes('The user approved the staged AgentTeams plan') && messageText(message).includes('from the pre-run review UI.'));
120
+ const reports = pluginMessages.filter(message => messageText(message).includes('AgentTeams message from member worker:') && messageText(message).includes('WEB_MEMBER_REPORT_OK'));
121
+ assert.ok(approvals.length <= 1, 'The Web route must not queue duplicate approval messages');
122
+ assert.ok(reports.length <= 1, 'A single member report must not be delivered twice');
123
+ const approvalNotice = approvals.find(message => !handledControlMessages.has(message.id));
124
+ const reportNotice = reports.find(message => !handledControlMessages.has(message.id));
125
+ let chunks;
126
+ if (isMember) {
127
+ // This gates only external LLM output, never agent/scheduler/HTTP code.
128
+ await memberGate;
129
+ options.signal?.throwIfAborted();
130
+ if (!userText.includes('AgentTeams automatic task assignment')) chunks = textChunks('WEB_MEMBER_READY');
131
+ else if (!names.includes('agent_teams_claim_task')) chunks = call('agent_teams_claim_task', { task_id: 't1' });
132
+ else if (calls.filter(block => block.name === 'agent_teams_update_task').length < 2) {
133
+ const attempt = toolText.match(/attempt_id ([^,\s)]+)/)?.[1];
134
+ assert.ok(attempt, 'Claim result must expose the real task attempt');
135
+ chunks = call('agent_teams_update_task', { task_id: 't1', status: names.includes('agent_teams_update_task') ? 'completed' : 'in_progress', output: 'WEB_MEMBER_TASK_DONE', attempt_id: attempt });
136
+ }
137
+ else if (!names.includes('agent_teams_send_message')) chunks = call('agent_teams_send_message', { to: 'captain', content: 'WEB_MEMBER_REPORT_OK' });
138
+ else chunks = textChunks('WEB_MEMBER_DONE');
139
+ }
140
+ else if (!names.includes('agent_teams_create')) chunks = call('agent_teams_create', { name: 'runtime-lab', description: 'Web approval regression', approval: 'required' });
141
+ else if (!names.includes('agent_teams_add_member')) chunks = call('agent_teams_add_member', { name: 'worker', role: 'WEB_APPROVAL_MEMBER', executionPrompt: 'WEB_APPROVAL_MEMBER: complete the assigned task and report.', reasoning_effort: 'high' });
142
+ else if (!names.includes('agent_teams_create_task')) chunks = call('agent_teams_create_task', { subject: 'Web approval task', description: 'Complete the deterministic task after human approval', assignee: 'worker' });
143
+ else if (reportNotice) {
144
+ handledControlMessages.add(reportNotice.id);
145
+ record({ event: 'web-captain-report-wake', sessionId: options.sessionId, messageId: reportNotice.id, source: reportNotice.source });
146
+ chunks = textChunks('WEB_CAPTAIN_REPORT_RECEIVED');
147
+ }
148
+ else if (approvalNotice) {
149
+ handledControlMessages.add(approvalNotice.id);
150
+ record({ event: 'web-captain-approval-wake', sessionId: options.sessionId, messageId: approvalNotice.id, source: approvalNotice.source });
151
+ chunks = textChunks('WEB_CAPTAIN_APPROVAL_ACKNOWLEDGED_AND_YIELDED');
152
+ }
153
+ else if (options.messages.at(-1)?.source?.kind === 'subagent-settled') {
154
+ // Host bootstrap completion is a distinct pre-existing notification,
155
+ // not another Web approval. Historical approval text is not a trigger.
156
+ record({ event: 'web-host-settled-notice', sessionId: options.sessionId, source: options.messages.at(-1).source });
157
+ chunks = textChunks('WEB_CAPTAIN_MEMBER_READY_NOTICE');
158
+ }
159
+ else chunks = textChunks('WEB_PLAN_STAGED');
160
+ for (const chunk of chunks) {
161
+ options.signal?.throwIfAborted();
162
+ if (chunk.type === 'block-end' && chunk.block.type === 'tool-call') {
163
+ assert.ok((options.tools ?? []).some(tool => tool.name === chunk.block.name), 'Model called a hidden tool: ' + chunk.block.name);
164
+ record({ event: 'web-model-tool-call', sessionId: options.sessionId, isMember, name: chunk.block.name, arguments: chunk.block.arguments });
165
+ }
166
+ yield chunk;
167
+ }
168
+ }
169
+ }
170
+ export const name = 'runtime-lab-web-approval';
171
+ export const inject = ['llm', 'agents', 'sessions', 'webServer', 'connection', 'workspaceRegistry'];
172
+ export function apply(ctx) {
173
+ ctx.llm.registerAdapter(['runtime-lab'], new WebApprovalAdapter());
174
+ // The real browser auth service owns token exchange and cookie verification.
175
+ // An index shell is sufficient; the product approval route remains untouched.
176
+ ctx.effect(() => ctx.webServer.register({ kind: 'exact', path: '/', handler(req, res) {
177
+ if (!ctx.connection.authorizeIndex(req, res)) return;
178
+ res.writeHead(200, { 'content-type': 'text/plain' });
179
+ res.end('Web approval fixture');
180
+ } }));
181
+ void (async () => {
182
+ await ctx.get('loader').await();
183
+ await ctx.workspaceRegistry.create(process.cwd(), 'Web approval regression');
184
+ const handle = await ctx.agents.create({ sessionId: 'session-' + randomUUID(), meta: { cwd: process.cwd() }, agentOptions: { provider: 'runtime-lab', model: 'fixture-model' } });
185
+ ctx.effect(() => () => handle.dispose());
186
+ const captain = handle.agent;
187
+ await captain.whenIdle();
188
+ record({ event: 'web-driver-user-message', sessionId: captain.id });
189
+ captain.followup(createUserMessage({ content: [{ type: 'text', text: 'Prepare an AgentTeams plan with one worker and one task. Wait for my approval in the review UI before running it.' }], source: { kind: 'user' } }));
190
+ await captain.whenIdle();
191
+ const statePath = join(process.cwd(), '.agent-teams/runtime-lab/team.json');
192
+ const readTeam = () => JSON.parse(readFileSync(statePath, 'utf8'));
193
+ const staged = readTeam();
194
+ assert.equal(staged.phase, 'staged');
195
+ assert.equal(staged.captainSessionId, captain.id);
196
+ assert.equal(staged.members.length, 1);
197
+ assert.equal(staged.members[0].id, '');
198
+ assert.equal(staged.tasks.length, 1);
199
+ assert.equal(events.filter(event => event.event === 'web-request' && event.isMember).length, 0);
200
+ record({ event: 'web-staged-idle', sessionId: captain.id, status: captain.status, teamId: staged.id });
201
+
202
+ const baseUrl = `http://127.0.0.1:${ctx.webServer.port}`;
203
+ const auth = await fetch(ctx.connection.authenticatedUrl(baseUrl), { redirect: 'manual', signal: AbortSignal.timeout(10000) });
204
+ assert.equal(auth.status, 303, 'The real browser token exchange must issue a cookie');
205
+ const cookie = auth.headers.get('set-cookie')?.split(';', 1)[0];
206
+ assert.ok(cookie, 'The real connection must mint a browser cookie');
207
+ const stateUrl = baseUrl + '/plugins/dsh-agent-teams/state';
208
+ const stateQuery = new URLSearchParams({ session: captain.id, summary: '1' });
209
+ const getState = (query = '', tag) => fetch(query ? `${stateUrl}?${query}` : stateUrl, {
210
+ headers: tag === undefined ? { cookie } : { cookie, 'if-none-match': tag },
211
+ signal: AbortSignal.timeout(10000),
212
+ });
213
+ const draftResponse = await getState(stateQuery);
214
+ assert.equal(draftResponse.status, 200);
215
+ const draftTag = draftResponse.headers.get('etag');
216
+ assert.match(draftTag, /^W\/"/);
217
+ const draftTeams = (await draftResponse.json()).teams;
218
+ assert.deepEqual(draftTeams.map(team => team.teamId), [staged.id]);
219
+ assert.equal(draftTeams[0].tasks[0].description, staged.tasks[0].description);
220
+ assert.equal(draftTeams[0].members[0].executionPrompt, staged.members[0].executionPrompt);
221
+ const unchanged = await getState(stateQuery, `"other,tag", ${draftTag.slice(2)}`);
222
+ assert.equal(unchanged.status, 304);
223
+ assert.equal(unchanged.headers.get('etag'), draftTag);
224
+ assert.equal(await unchanged.text(), '');
225
+ const malformed = await getState(stateQuery, `${draftTag}, invalid`);
226
+ assert.equal(malformed.status, 200);
227
+ await malformed.arrayBuffer();
228
+ const otherSession = await getState(new URLSearchParams({ session: 'another-captain', summary: '1' }), draftTag);
229
+ assert.equal(otherSession.status, 200);
230
+ assert.deepEqual(await otherSession.json(), { teams: [] });
231
+ const postApproval = teamId => fetch(baseUrl + '/plugins/dsh-agent-teams/plan', { method: 'POST', headers: { 'content-type': 'application/json', origin: baseUrl, cookie }, body: JSON.stringify({ sessionId: captain.id, teamId, action: 'approve' }), signal: AbortSignal.timeout(10000) });
232
+ const beforeInvalidRequests = events.filter(event => event.event === 'web-request' && !event.isMember).length;
233
+ const invalid = await postApproval('missing-team-' + randomUUID());
234
+ const invalidResponse = await invalid.json();
235
+ assert.equal(invalid.status, 404, JSON.stringify(invalidResponse));
236
+ await captain.whenIdle();
237
+ assert.equal(events.filter(event => event.event === 'web-captain-approval-wake').length, 0);
238
+ assert.equal(events.filter(event => event.event === 'web-request' && !event.isMember).length, beforeInvalidRequests, 'Invalid approval must not wake the captain');
239
+ assert.equal(readTeam().phase, 'staged');
240
+ record({ event: 'web-http-invalid-team-rejected', sessionId: captain.id, status: invalid.status });
241
+ record({ event: 'web-http-approval-start', sessionId: captain.id, teamId: staged.id });
242
+ const approval = await postApproval(staged.id);
243
+ const response = await approval.json();
244
+ assert.equal(approval.status, 200, JSON.stringify(response));
245
+ assert.equal(response.ok, true);
246
+ assert.equal(response.phase, 'running');
247
+ record({ event: 'web-http-approved', sessionId: captain.id, status: approval.status, response });
248
+ await waitFor(() => events.some(event => event.event === 'web-captain-approval-wake'), 'HTTP approval must wake the idle captain without a second user message');
249
+ await captain.whenIdle();
250
+ assert.equal(captain.status, 'idle');
251
+ assert.equal(events.filter(event => event.event === 'web-captain-report-wake').length, 0);
252
+ assert.notEqual(readTeam().tasks[0].status, 'completed');
253
+ record({ event: 'web-approved-idle', sessionId: captain.id, status: captain.status });
254
+ const beforeRepeatRequests = events.filter(event => event.event === 'web-request' && !event.isMember).length;
255
+ const repeat = await postApproval(staged.id);
256
+ const repeatResponse = await repeat.json();
257
+ assert.equal(repeat.status, 409, JSON.stringify(repeatResponse));
258
+ await captain.whenIdle();
259
+ assert.equal(events.filter(event => event.event === 'web-captain-approval-wake').length, 1);
260
+ assert.equal(events.filter(event => event.event === 'web-request' && !event.isMember).length, beforeRepeatRequests, 'Rejected repeat approval must not wake the captain');
261
+ assert.equal(readTeam().phase, 'running');
262
+ record({ event: 'web-http-repeat-rejected', sessionId: captain.id, status: repeat.status });
263
+ // #262: the real member is awaiting model output, before in_progress.
264
+ // The panel route must preserve this claim rather than call it ready/running.
265
+ await waitFor(() => events.some(event => event.event === 'web-request' && event.isMember), 'Member request starts before checking claimed state');
266
+ const activityResponse = await getState(stateQuery, draftTag);
267
+ assert.equal(activityResponse.status, 200);
268
+ assert.notEqual(activityResponse.headers.get('etag'), draftTag);
269
+ const activityBody = await activityResponse.json();
270
+ const activityTeam = activityBody.teams.find(team => team.teamId === staged.id);
271
+ assert.ok(activityTeam, 'Real activity route must discover the staged team after approval');
272
+ assert.equal(readTeam().tasks[0].status, 'claimed');
273
+ assert.equal(activityTeam.tasks[0].status, 'claimed');
274
+ assert.equal(activityTeam.tasks[0].state, 'claimed');
275
+ assert.equal(activityTeam.members[0].activity, 'working');
276
+ assert.equal(Object.hasOwn(activityTeam.tasks[0], 'description'), false);
277
+ assert.equal(Object.hasOwn(activityTeam.members[0], 'executionPrompt'), false);
278
+ const legacyResponse = await getState();
279
+ assert.equal(legacyResponse.status, 200);
280
+ const legacyTeam = (await legacyResponse.json()).teams.find(team => team.teamId === staged.id);
281
+ assert.equal(legacyTeam.tasks[0].description, staged.tasks[0].description);
282
+ assert.equal(legacyTeam.members[0].executionPrompt, staged.members[0].executionPrompt);
283
+ record({ event: 'web-claimed-projection', taskStatus: activityTeam.tasks[0].status, visualState: activityTeam.tasks[0].state, memberActivity: activityTeam.members[0].activity });
284
+ record({ event: 'web-member-output-released' });
285
+ releaseMember();
286
+ await waitFor(() => events.some(event => event.event === 'web-captain-report-wake'), 'A real member report must wake the idle captain');
287
+ for (const agent of ctx.agents.list()) {
288
+ await agent.whenIdle();
289
+ // Best effort: a handle may close while this loop awaits an earlier
290
+ // agent. Closing persists, so a closed handle needs no flush — and
291
+ // the host rejects flushing one.
292
+ try { if (ctx.sessions.get(agent.id) === agent.session) await ctx.sessions.flush(agent.session); }
293
+ catch (error) { if (String(error?.name) !== 'SessionHandleClosedError') throw error; }
294
+ }
295
+ await captain.whenIdle();
296
+ const completed = readTeam();
297
+ assert.equal(completed.id, staged.id);
298
+ assert.equal(completed.members.length, 1);
299
+ assert.ok(completed.members[0].id);
300
+ assert.equal(completed.tasks.length, 1);
301
+ assert.equal(completed.tasks[0].status, 'completed');
302
+ assert.equal(completed.tasks[0].output, 'WEB_MEMBER_TASK_DONE');
303
+ const modelCalls = events.filter(event => event.event === 'web-model-tool-call');
304
+ assert.equal(modelCalls[0].name, 'agent_teams_create');
305
+ assert.ok(events.filter(event => event.event === 'web-request').every(event => !event.tools.some(tool => tool.name === 'agent_teams_open')));
306
+ assert.equal(modelCalls.filter(event => event.name === 'agent_teams_approve' || event.name === 'agent_teams_status').length, 0, 'No duplicate approval or status polling');
307
+ assert.equal(modelCalls.filter(event => event.name === 'agent_teams_create').length, 1);
308
+ assert.equal(modelCalls.filter(event => event.name === 'agent_teams_add_member').length, 1);
309
+ assert.equal(modelCalls.filter(event => event.name === 'agent_teams_create_task').length, 1);
310
+ assert.equal(events.filter(event => event.event === 'web-captain-approval-wake').length, 1);
311
+ assert.equal(events.filter(event => event.event === 'web-captain-report-wake').length, 1);
312
+ const captainRequests = events.filter(event => event.event === 'web-request' && !event.isMember);
313
+ const systemSha256 = sha256(captainRequests[0].system ?? ''), toolsSha256 = sha256(JSON.stringify(captainRequests[0].tools ?? []));
314
+ assert.ok(captainRequests.every(request => sha256(request.system ?? '') === systemSha256), 'Captain system must remain stable across staging, Web approval, and reports');
315
+ assert.ok(captainRequests.every(request => sha256(JSON.stringify(request.tools ?? [])) === toolsSha256), 'Captain tool schemas must remain stable across the complete Web workflow');
316
+ const memberRequests = events.filter(event => event.event === 'web-request' && event.isMember);
317
+ assert.ok(memberRequests.length > 0);
318
+ const memberTools = ['agent_teams_claim_task', 'agent_teams_update_task', 'agent_teams_send_message', 'agent_teams_status'].sort();
319
+ for (const request of memberRequests) assert.deepEqual(request.tools.filter(tool => tool.name.startsWith('agent_teams_')).map(tool => tool.name).sort(), memberTools, 'Every real member request must expose exactly the four member tools');
320
+ record({ event: 'web-headers-stable', sessionId: captain.id, systemSha256, toolsSha256, captainRequests: captainRequests.length, memberRequests: memberRequests.length, memberTeamToolCount: memberTools.length });
321
+ await verifyWorkspaceAudit(baseUrl, cookie, captain.id);
322
+ const archivedId = 'runtime-lab-history';
323
+ const archiveDir = join(process.cwd(), '.agent-teams/archive', archivedId);
324
+ fs.mkdirSync(archiveDir, { recursive: true });
325
+ fs.writeFileSync(join(archiveDir, 'team.json'), JSON.stringify({ ...completed, id: archivedId }));
326
+ const archiveQuery = new URLSearchParams({ session: captain.id, archived: '1' });
327
+ const archive = await getState(archiveQuery, draftTag);
328
+ assert.equal(archive.status, 200);
329
+ const archivedTeams = (await archive.json()).teams;
330
+ assert.deepEqual(archivedTeams.map(team => team.teamId), [archivedId]);
331
+ assert.equal(archivedTeams[0].tasks[0].description, staged.tasks[0].description);
332
+ assert.equal(archivedTeams[0].members[0].executionPrompt, staged.members[0].executionPrompt);
333
+ record({ event: 'web-approval-passed', sessionId: captain.id, teamId: completed.id, memberId: completed.members[0].id, taskStatus: completed.tasks[0].status, captainRequests: captainRequests.length });
334
+ process.stdout.write('WEB_APPROVAL_OK\n');
335
+ ctx.get('appExit')(0);
336
+ })().catch(error => {
337
+ releaseMember();
338
+ process.stderr.write(String(error.stack ?? error) + '\n');
339
+ ctx.get('appExit')(1);
340
+ });
341
+ }
@@ -0,0 +1,18 @@
1
+ // Only scheduling/failure delivery is controlled; successful evidence is read
2
+ // by the same real auditor as the shipped worker.
3
+ import { parentPort } from 'node:worker_threads'
4
+ import { appendFileSync, existsSync } from 'node:fs'
5
+ import { setTimeout as delay } from 'node:timers/promises'
6
+ import { auditTeamWorkspace } from '../../lib/workspace-audit.js'
7
+ const url = new URL(import.meta.url)
8
+ const mode = url.searchParams.get('mode')
9
+ parentPort.on('message', async job => {
10
+ if (mode === 'crash') throw new Error('controlled worker crash')
11
+ if (mode === 'exit') process.exit(1)
12
+ if (mode === 'invalid') { parentPort.postMessage({ id: job.id, audit: {} }); return }
13
+ if (mode === 'hang') return
14
+ const audit = auditTeamWorkspace(job.workspace, job.team)
15
+ appendFileSync(url.searchParams.get('started'), JSON.stringify({ id: job.id }) + '\n')
16
+ while (!existsSync(url.searchParams.get('release'))) await delay(2)
17
+ parentPort.postMessage({ id: job.id, audit })
18
+ })
@@ -0,0 +1,64 @@
1
+ /** Record and verify source/build-output digests for script-free Git installation. */
2
+ import { createHash } from 'node:crypto'
3
+ import { existsSync, readdirSync, readFileSync, realpathSync, writeFileSync } from 'node:fs'
4
+ import { dirname, join } from 'node:path'
5
+ import { fileURLToPath, pathToFileURL } from 'node:url'
6
+
7
+ const STAMP = 'lib/git-artifact-stamp.json'
8
+ const REQUIRED = ['lib/index.js', 'lib/client.js', 'lib/types/index.d.ts', 'lib/types/client/index.d.ts']
9
+ // Vendored as a dsh-fish workspace member: the lockfile lives at the monorepo
10
+ // root, so this package has no local pnpm-lock.yaml. Config inputs that are
11
+ // absent from the package are skipped instead of failing the build; in a
12
+ // standalone checkout every listed file exists and the gate is unchanged.
13
+ const CONFIG = ['tsconfig.json', 'tsconfig.client.json', 'tsdown.config.ts', 'pnpm-lock.yaml', 'pnpm-workspace.yaml', 'scripts/clean-build.mjs', 'scripts/git-artifacts.mjs']
14
+ function files(root, directory) {
15
+ return readdirSync(join(root, directory), { withFileTypes: true }).flatMap(entry => {
16
+ const path = `${directory}/${entry.name}`
17
+ if (entry.isDirectory()) return files(root, path)
18
+ if (!entry.isFile()) throw new Error(`Unsupported build input/output: ${path}`)
19
+ return [path]
20
+ }).sort()
21
+ }
22
+ /**
23
+ * Bytes of one hashed input, with line endings normalised to LF.
24
+ *
25
+ * A CRLF checkout on Windows and an LF checkout on a Linux runner are the same
26
+ * source tree, but hashing raw bytes made the stamp valid for exactly one
27
+ * working directory: a fresh checkout then failed with "Git artifacts are stale
28
+ * or modified" at the very same commit. Normalisation is deterministic, so a
29
+ * digest still only changes when a file's content changes; a lone CR (no LF) is
30
+ * left untouched.
31
+ */
32
+ function normalisedBytes(path) {
33
+ const bytes = readFileSync(path)
34
+ if (!bytes.includes(0x0d)) return bytes
35
+ return Buffer.from(bytes.toString('latin1').replace(/\r\n/g, '\n'), 'latin1')
36
+ }
37
+ function digest(root, paths, prefix = '') {
38
+ const hash = createHash('sha256').update(prefix)
39
+ for (const path of [...paths].sort()) hash.update(path).update('\0').update(normalisedBytes(join(root, path))).update('\0')
40
+ return hash.digest('hex')
41
+ }
42
+ function current(root) {
43
+ for (const path of REQUIRED) if (!existsSync(join(root, path))) throw new Error(`Missing Git artifact: ${path}; run pnpm build`)
44
+ const pkg = JSON.parse(readFileSync(join(root, 'package.json'), 'utf8'))
45
+ const settings = JSON.stringify({ name: pkg.name, version: pkg.version, type: pkg.type, exports: pkg.exports, devDependencies: pkg.devDependencies, dependencies: pkg.dependencies, build: pkg.scripts?.build })
46
+ return { schema: 1, source: digest(root, [...files(root, 'src'), ...CONFIG.filter(path => existsSync(join(root, path)))], settings), output: digest(root, files(root, 'lib').filter(path => path !== STAMP)) }
47
+ }
48
+ export function writeGitArtifactStamp(root) {
49
+ writeFileSync(join(root, STAMP), JSON.stringify(current(root), null, 2) + '\n')
50
+ }
51
+ export function verifyGitArtifacts(root) {
52
+ if (!existsSync(join(root, STAMP))) throw new Error('Missing Git artifact stamp; run pnpm build')
53
+ const saved = JSON.parse(readFileSync(join(root, STAMP), 'utf8'))
54
+ const actual = current(root)
55
+ if (saved.schema !== actual.schema || saved.source !== actual.source || saved.output !== actual.output) {
56
+ throw new Error('Git artifacts are stale or modified; run pnpm build and include lib/ with the source changes')
57
+ }
58
+ return actual
59
+ }
60
+ if (process.argv[1] && import.meta.url === pathToFileURL(realpathSync(process.argv[1])).href) {
61
+ const root = dirname(dirname(fileURLToPath(import.meta.url)))
62
+ if (process.argv[2] === '--write') writeGitArtifactStamp(root)
63
+ else { verifyGitArtifacts(root); console.log('Git artifacts match source and build settings.') }
64
+ }
@@ -0,0 +1,32 @@
1
+ import test from 'node:test'
2
+ import assert from 'node:assert/strict'
3
+ import { mkdtempSync, mkdirSync, writeFileSync, rmSync } from 'node:fs'
4
+ import { join } from 'node:path'
5
+ import { tmpdir } from 'node:os'
6
+ import { writeGitArtifactStamp, verifyGitArtifacts } from './git-artifacts.mjs'
7
+ function fixture(t) {
8
+ const root = mkdtempSync(join(tmpdir(), 'agent-teams-artifact-test-'))
9
+ t.after(() => rmSync(root, { recursive: true, force: true }))
10
+ const put = (path, value = '') => { mkdirSync(join(root, path, '..'), { recursive: true }); writeFileSync(join(root, path), value) }
11
+ put('package.json', JSON.stringify({ name: 'test', version: '1.0.0', devDependencies: { typescript: '5.9.3' }, scripts: { build: 'compile' } }))
12
+ for (const path of ['src/index.ts', 'lib/index.js', 'lib/client.js', 'lib/types/index.d.ts', 'lib/types/client/index.d.ts', 'tsconfig.json', 'tsconfig.client.json', 'tsdown.config.ts', 'pnpm-lock.yaml', 'pnpm-workspace.yaml', 'scripts/clean-build.mjs', 'scripts/git-artifacts.mjs']) put(path)
13
+ return { root, put }
14
+ }
15
+ test('complete build matches its stamp and README changes do not invalidate it', t => {
16
+ const { root, put } = fixture(t); writeGitArtifactStamp(root); put('README.md', 'new instructions'); assert.equal(verifyGitArtifacts(root).schema, 1)
17
+ })
18
+ test('source changes require rebuilding', t => {
19
+ const { root, put } = fixture(t); writeGitArtifactStamp(root); put('src/index.ts', 'changed'); assert.throws(() => verifyGitArtifacts(root), /stale or modified/)
20
+ })
21
+ test('dependency settings require rebuilding', t => {
22
+ const { root, put } = fixture(t); writeGitArtifactStamp(root); put('pnpm-workspace.yaml', 'changed'); assert.throws(() => verifyGitArtifacts(root), /stale or modified/)
23
+ })
24
+ test('modified and extra output cannot pass the stamp', t => {
25
+ const { root, put } = fixture(t); writeGitArtifactStamp(root); put('lib/extra.js', 'unexpected'); assert.throws(() => verifyGitArtifacts(root), /stale or modified/)
26
+ })
27
+ test('missing entry cannot be stamped as a valid build', t => {
28
+ const { root } = fixture(t); rmSync(join(root, 'lib/client.js')); assert.throws(() => writeGitArtifactStamp(root), /Missing Git artifact/)
29
+ })
30
+ test('a source tree with no build stamp cannot pass', t => {
31
+ const { root } = fixture(t); assert.throws(() => verifyGitArtifacts(root), /Missing Git artifact stamp/)
32
+ })