@myrialabs/clopen 0.4.23 → 0.4.25
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.
- package/backend/chat/stream-manager.ts +41 -13
- package/backend/engine/README.md +18 -0
- package/backend/engine/adapters/claude/message-converter.test.ts +36 -0
- package/backend/engine/adapters/claude/message-converter.ts +40 -4
- package/backend/engine/adapters/claude/stream.ts +68 -3
- package/backend/engine/adapters/claude/workflow-transcript.test.ts +65 -0
- package/backend/engine/adapters/claude/workflow-transcript.ts +248 -0
- package/backend/engine/adapters/coordination-tool-mapping.test.ts +17 -0
- package/backend/engine/adapters/copilot/message-converter.ts +20 -1
- package/backend/engine/adapters/opencode/message-converter.test.ts +80 -0
- package/backend/engine/adapters/opencode/message-converter.ts +32 -0
- package/backend/engine/adapters/opencode/stream.ts +29 -23
- package/backend/engine/adapters/qwen/message-converter.ts +5 -8
- package/backend/engine/docs/adapter-contract.md +29 -1
- package/backend/engine/docs/adding-an-engine.md +8 -1
- package/backend/engine/docs/frontend-and-chat.md +32 -1
- package/backend/engine/docs/lessons-learned.md +49 -2
- package/backend/engine/docs/quick-reference.md +2 -0
- package/backend/mcp/internal/servers/browser-automation/actions/console.ts +3 -0
- package/backend/mcp/internal/servers/browser-automation/actions/inspect.ts +3 -0
- package/backend/mcp/internal/servers/browser-automation/actions/navigation.ts +5 -0
- package/backend/mcp/internal/servers/browser-automation/actions/tabs.ts +8 -0
- package/backend/mcp/internal/servers/browser-automation/actions/types.ts +10 -0
- package/backend/mcp/internal/servers/browser-automation/context.ts +6 -0
- package/backend/mcp/internal/servers/browser-automation/description.ts +1 -1
- package/backend/mcp/internal/servers/browser-automation/runner.ts +21 -1
- package/backend/mcp/internal/servers/browser-automation/schema.ts +1 -1
- package/backend/module-shadowing.test.ts +135 -0
- package/backend/preview/browser/browser-host-bridge.ts +8 -2
- package/backend/preview/browser/browser-interaction-handler.ts +95 -38
- package/backend/preview/browser/browser-mcp-control.ts +332 -22
- package/backend/preview/browser/browser-preview-service.ts +152 -33
- package/backend/preview/browser/browser-tab-manager.ts +25 -1
- package/backend/preview/browser/browser-video-capture.ts +551 -247
- package/backend/preview/browser/scripts/host-bridge.ts +61 -89
- package/backend/preview/browser/scripts/video-stream.ts +32 -0
- package/backend/preview/browser/types.ts +22 -0
- package/backend/preview/index.ts +6 -1
- package/backend/ws/preview/browser/console.ts +12 -10
- package/backend/ws/preview/browser/interact.ts +40 -10
- package/backend/ws/preview/browser/native-ui.ts +35 -10
- package/backend/ws/preview/browser/tab-info.ts +46 -7
- package/backend/ws/preview/browser/webcodecs.ts +6 -1
- package/backend/ws/preview/index.ts +23 -3
- package/dist/assets/{index-DH_GO0Lf.js → index-C4PD7B-x.js} +1 -1
- package/dist/assets/{index-igSQ3JaM.js → index-KBGloYDk.js} +1 -1
- package/dist/assets/{main-D-d8SFfW.js → main-B0AA-88X.js} +364 -358
- package/dist/assets/main-OsjA5Ab5.css +1 -0
- package/dist/index.html +2 -2
- package/package.json +1 -1
- package/shared/types/unified/index.ts +7 -0
- package/shared/types/unified/tool.ts +57 -2
- package/dist/assets/main-BD3-qPfT.css +0 -1
|
@@ -243,6 +243,22 @@ class StreamManager extends EventEmitter {
|
|
|
243
243
|
super();
|
|
244
244
|
// Increase max listeners for high concurrency
|
|
245
245
|
this.setMaxListeners(1000);
|
|
246
|
+
|
|
247
|
+
// MCP browser locks are scoped to a chat session, and every release path
|
|
248
|
+
// runs from this class. Teaching the lock manager how to check liveness
|
|
249
|
+
// closes the gap those paths can't: a tool call that lands after its
|
|
250
|
+
// stream ended used to be able to take a lock nothing would release.
|
|
251
|
+
browserMcpControl.setSessionLivenessProbe((chatSessionId) =>
|
|
252
|
+
this.isChatSessionStreaming(chatSessionId)
|
|
253
|
+
);
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
/** Whether any stream for this chat session is still running. */
|
|
257
|
+
private isChatSessionStreaming(chatSessionId: string): boolean {
|
|
258
|
+
for (const stream of this.activeStreams.values()) {
|
|
259
|
+
if (stream.chatSessionId === chatSessionId && stream.status === 'active') return true;
|
|
260
|
+
}
|
|
261
|
+
return false;
|
|
246
262
|
}
|
|
247
263
|
|
|
248
264
|
/**
|
|
@@ -1302,6 +1318,27 @@ class StreamManager extends EventEmitter {
|
|
|
1302
1318
|
}
|
|
1303
1319
|
}
|
|
1304
1320
|
|
|
1321
|
+
// Abort first, then release the browser locks, and only then ask the
|
|
1322
|
+
// engine to stop.
|
|
1323
|
+
//
|
|
1324
|
+
// The order matters and used to be the other way round. `engine.cancel()`
|
|
1325
|
+
// is awaited for up to five seconds, and a browser-automation batch that
|
|
1326
|
+
// was mid-flight kept resolving its target tab throughout — re-acquiring
|
|
1327
|
+
// control of a tab moments after (or before) it was handed back, under a
|
|
1328
|
+
// chat session whose release had already run. That is the interrupt that
|
|
1329
|
+
// left the tab locked with nobody to unlock it. Aborting up front makes
|
|
1330
|
+
// the batch stop between actions, and releasing before the wait means
|
|
1331
|
+
// anything that slips through is refused rather than orphaned.
|
|
1332
|
+
if (!streamState.abortController?.signal.aborted) {
|
|
1333
|
+
streamState.abortController?.abort();
|
|
1334
|
+
}
|
|
1335
|
+
|
|
1336
|
+
// Auto-release all MCP-controlled tabs for this chat session
|
|
1337
|
+
if (streamState.chatSessionId) {
|
|
1338
|
+
browserMcpControl.releaseSession(streamState.chatSessionId);
|
|
1339
|
+
debug.log('mcp', `✅ Auto-released MCP tabs for session ${streamState.chatSessionId.slice(0, 8)} on stream cancellation`);
|
|
1340
|
+
}
|
|
1341
|
+
|
|
1305
1342
|
// Cancel the per-project engine with a bounded timeout.
|
|
1306
1343
|
// engine.cancel() stops the SDK process (Claude Code: close() kills subprocess,
|
|
1307
1344
|
// OpenCode: aborts controller + HTTP abort to server). If cancel() hangs
|
|
@@ -1320,14 +1357,6 @@ class StreamManager extends EventEmitter {
|
|
|
1320
1357
|
debug.error('chat', 'Error cancelling engine (non-fatal):', error);
|
|
1321
1358
|
}
|
|
1322
1359
|
|
|
1323
|
-
// Abort the stream-manager's controller as a fallback.
|
|
1324
|
-
// engine.cancel() already aborts the same controller, so this is
|
|
1325
|
-
// typically a no-op but ensures cleanup if the engine timed out
|
|
1326
|
-
// or wasn't active.
|
|
1327
|
-
if (!streamState.abortController?.signal.aborted) {
|
|
1328
|
-
streamState.abortController?.abort();
|
|
1329
|
-
}
|
|
1330
|
-
|
|
1331
1360
|
this.emitStreamEvent(streamState, 'cancelled', {
|
|
1332
1361
|
processId: streamState.processId,
|
|
1333
1362
|
timestamp: streamState.completedAt.toISOString()
|
|
@@ -1335,11 +1364,10 @@ class StreamManager extends EventEmitter {
|
|
|
1335
1364
|
|
|
1336
1365
|
this.emitStreamLifecycle(streamState, 'cancelled', reason);
|
|
1337
1366
|
|
|
1338
|
-
//
|
|
1339
|
-
|
|
1340
|
-
|
|
1341
|
-
|
|
1342
|
-
}
|
|
1367
|
+
// Sweep again after the engine has actually stopped: a tool call still
|
|
1368
|
+
// in flight during the wait above may have taken a lock that its own
|
|
1369
|
+
// release path will never reach.
|
|
1370
|
+
browserMcpControl.releaseOrphans();
|
|
1343
1371
|
|
|
1344
1372
|
return true;
|
|
1345
1373
|
}
|
package/backend/engine/README.md
CHANGED
|
@@ -46,6 +46,17 @@ stays **agnostic** to the underlying SDK.
|
|
|
46
46
|
> capture the SDK's real runtime shapes with a throwaway script rather than
|
|
47
47
|
> trusting its `.d.ts`.
|
|
48
48
|
|
|
49
|
+
> **Background parent tools are a streaming category of their own.** `Agent`
|
|
50
|
+
> receives nested activity from the SDK stream, while Claude's `Workflow`
|
|
51
|
+
> writes agent transcripts to JSONL files outside that stream. Both must obey
|
|
52
|
+
> the same UI contract: emit the parent first, stamp every child with the
|
|
53
|
+
> parent's `toolUseId` before it crosses the adapter boundary, and never expose
|
|
54
|
+
> a child on the root timeline even temporarily. File-backed activity must use
|
|
55
|
+
> filesystem change events rather than interval polling. Read **§10.15** in
|
|
56
|
+
> [lessons-learned](./docs/lessons-learned.md) and **§6.5** in
|
|
57
|
+
> [frontend-and-chat](./docs/frontend-and-chat.md) before adding another
|
|
58
|
+
> background or nested tool.
|
|
59
|
+
|
|
49
60
|
This guide is split into focused documents — start here for the architecture
|
|
50
61
|
map, then jump to the area you need.
|
|
51
62
|
|
|
@@ -136,6 +147,13 @@ Three key rules that **every** layer upholds:
|
|
|
136
147
|
New methods are not added ad-hoc — they are added to the interface first,
|
|
137
148
|
then implemented in **every** adapter.
|
|
138
149
|
|
|
150
|
+
For parent tools (`Agent`, `Workflow`, or a future equivalent), message
|
|
151
|
+
placement is also part of the contract: root messages carry
|
|
152
|
+
`parent.toolUseId = null`; every nested message carries the parent tool call id
|
|
153
|
+
from its first emission. The frontend must not render at root and relocate
|
|
154
|
+
later. See [adapter contract §2.3](./docs/adapter-contract.md) for the complete
|
|
155
|
+
invariants.
|
|
156
|
+
|
|
139
157
|
> ⚠️ **Before you propose new infrastructure, read this.**
|
|
140
158
|
> Two design pitfalls have repeatedly tripped people adding new adapters.
|
|
141
159
|
> Before sketching architecture, double-check:
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import { describe, expect, test } from 'bun:test';
|
|
2
|
+
import { createSdkMessageConverter, mapAssistantContent } from './message-converter';
|
|
3
|
+
|
|
4
|
+
describe('Claude workflow tools', () => {
|
|
5
|
+
test('keeps Workflow and REPL canonical', () => {
|
|
6
|
+
const blocks = mapAssistantContent([
|
|
7
|
+
{ type: 'tool_use', id: 'workflow-1', name: 'Workflow', input: { name: 'audit' } },
|
|
8
|
+
{ type: 'tool_use', id: 'repl-1', name: 'REPL', input: { code: 'return 1' } },
|
|
9
|
+
] as any);
|
|
10
|
+
|
|
11
|
+
expect(blocks.map(block => block.type === 'tool_use' ? block.name : block.type)).toEqual(['Workflow', 'REPL']);
|
|
12
|
+
});
|
|
13
|
+
|
|
14
|
+
test('threads workflow task lifecycle into the Workflow parent', () => {
|
|
15
|
+
const convert = createSdkMessageConverter();
|
|
16
|
+
const started = [...convert({
|
|
17
|
+
type: 'system', subtype: 'task_started', session_id: 'session-1', uuid: 'started-1',
|
|
18
|
+
task_id: 'task-1', tool_use_id: 'workflow-1', task_type: 'local_workflow',
|
|
19
|
+
workflow_name: 'audit', description: 'Audit repository',
|
|
20
|
+
} as any)];
|
|
21
|
+
const progress = [...convert({
|
|
22
|
+
type: 'system', subtype: 'task_progress', session_id: 'session-1', uuid: 'progress-1',
|
|
23
|
+
task_id: 'task-1', description: 'Audit repository', last_tool_name: 'Read',
|
|
24
|
+
usage: { total_tokens: 1, tool_uses: 1, duration_ms: 1 },
|
|
25
|
+
} as any)];
|
|
26
|
+
const staticHeartbeat = [...convert({
|
|
27
|
+
type: 'system', subtype: 'task_progress', session_id: 'session-1', uuid: 'progress-3',
|
|
28
|
+
task_id: 'task-1', description: 'Audit repository',
|
|
29
|
+
usage: { total_tokens: 3, tool_uses: 2, duration_ms: 3 },
|
|
30
|
+
} as any)];
|
|
31
|
+
|
|
32
|
+
expect(started[0]).toMatchObject({ type: 'assistant', parent: { toolUseId: 'workflow-1' } });
|
|
33
|
+
expect(progress).toEqual([]);
|
|
34
|
+
expect(staticHeartbeat).toEqual([]);
|
|
35
|
+
});
|
|
36
|
+
});
|
|
@@ -275,10 +275,15 @@ export function convertUserMessage(msg: SDKUserMessage): UserMessage {
|
|
|
275
275
|
export interface StreamConverterState {
|
|
276
276
|
/** index → true when the block is a thinking block */
|
|
277
277
|
reasoningBlocks: Map<number, boolean>;
|
|
278
|
+
/** Workflow background task id → originating Workflow tool_use id. */
|
|
279
|
+
workflowParents: Map<string, string>;
|
|
278
280
|
}
|
|
279
281
|
|
|
280
282
|
export function createStreamConverterState(): StreamConverterState {
|
|
281
|
-
return {
|
|
283
|
+
return {
|
|
284
|
+
reasoningBlocks: new Map(),
|
|
285
|
+
workflowParents: new Map(),
|
|
286
|
+
};
|
|
282
287
|
}
|
|
283
288
|
|
|
284
289
|
/** Convert SDKPartialAssistantMessage (stream_event) → TextDeltaEvent | StreamLifecycleEvent */
|
|
@@ -411,6 +416,24 @@ function convertTaskNotification(
|
|
|
411
416
|
};
|
|
412
417
|
}
|
|
413
418
|
|
|
419
|
+
function workflowActivityMessage(
|
|
420
|
+
msg: { session_id: string; uuid?: string },
|
|
421
|
+
parentToolUseId: string,
|
|
422
|
+
text: string,
|
|
423
|
+
): AssistantMessage {
|
|
424
|
+
return {
|
|
425
|
+
type: 'assistant',
|
|
426
|
+
createdAt: new Date().toISOString(),
|
|
427
|
+
messageId: msg.uuid || crypto.randomUUID(),
|
|
428
|
+
sessionId: msg.session_id,
|
|
429
|
+
parent: { messageId: null, sessionId: null, toolUseId: parentToolUseId },
|
|
430
|
+
engine: { type: 'claude-code', provider: 'anthropic', model: { id: '', name: '' }, account: { id: 0, name: '' } },
|
|
431
|
+
content: [{ type: 'text', text }],
|
|
432
|
+
stopReason: null,
|
|
433
|
+
usage: null,
|
|
434
|
+
};
|
|
435
|
+
}
|
|
436
|
+
|
|
414
437
|
/** Convert SDKCompactBoundaryMessage → CompactBoundaryMessage */
|
|
415
438
|
export function convertCompactBoundary(msg: SDKCompactBoundaryMessage): CompactBoundaryMessage {
|
|
416
439
|
return {
|
|
@@ -507,12 +530,25 @@ function* dispatchSdkMessage(msg: SDKMessage, state: StreamConverterState): Gene
|
|
|
507
530
|
yield convertSystemInit(msg as SDKSystemMessage);
|
|
508
531
|
} else if (subtype === 'compact_boundary') {
|
|
509
532
|
yield convertCompactBoundary(msg as SDKCompactBoundaryMessage);
|
|
533
|
+
} else if (subtype === 'task_started') {
|
|
534
|
+
const task = msg as unknown as { session_id: string; uuid?: string; task_id: string; tool_use_id?: string; task_type?: string; workflow_name?: string; description?: string };
|
|
535
|
+
if (task.task_type === 'local_workflow' && task.tool_use_id) {
|
|
536
|
+
state.workflowParents.set(task.task_id, task.tool_use_id);
|
|
537
|
+
const detail = `Workflow ${task.workflow_name || task.description || task.task_id} started.`;
|
|
538
|
+
yield workflowActivityMessage(task, task.tool_use_id, detail);
|
|
539
|
+
}
|
|
510
540
|
} else if (subtype === 'task_notification') {
|
|
511
|
-
const
|
|
541
|
+
const task = msg as unknown as { session_id: string; uuid?: string; task_id: string; tool_use_id?: string; status: string; summary?: string };
|
|
542
|
+
const parent = task.tool_use_id || state.workflowParents.get(task.task_id);
|
|
543
|
+
if (parent && state.workflowParents.has(task.task_id)) {
|
|
544
|
+
yield workflowActivityMessage(task, parent, `Workflow ${task.status}.`);
|
|
545
|
+
state.workflowParents.delete(task.task_id);
|
|
546
|
+
}
|
|
547
|
+
const note = convertTaskNotification(task);
|
|
512
548
|
if (note) yield note;
|
|
513
549
|
}
|
|
514
|
-
//
|
|
515
|
-
//
|
|
550
|
+
// task_progress is a repeated heartbeat; real child activity is replayed
|
|
551
|
+
// from Workflow-owned transcripts. task_updated has no tool_use_id.
|
|
516
552
|
break;
|
|
517
553
|
}
|
|
518
554
|
|
|
@@ -24,6 +24,7 @@ import type {
|
|
|
24
24
|
import type { EngineOutput } from '$shared/types/unified';
|
|
25
25
|
import type { StructuredGenerationOptions } from '../../types';
|
|
26
26
|
import { createSdkMessageConverter, toSdkUserMessage } from './message-converter';
|
|
27
|
+
import { WorkflowTranscriptTailer } from './workflow-transcript';
|
|
27
28
|
import { resolveOsPath } from '$backend/utils/paths';
|
|
28
29
|
import { setupEnvironmentOnce, getEngineEnv } from './environment';
|
|
29
30
|
import { handleStreamError } from './error-handler';
|
|
@@ -45,6 +46,33 @@ interface PendingUserAnswer {
|
|
|
45
46
|
input: Record<string, unknown>;
|
|
46
47
|
}
|
|
47
48
|
|
|
49
|
+
/** Merge the SDK stream with Workflow transcript polling without blocking either producer. */
|
|
50
|
+
class EventQueue<T> {
|
|
51
|
+
private buffer: T[] = [];
|
|
52
|
+
private wake: (() => void) | null = null;
|
|
53
|
+
private done = false;
|
|
54
|
+
private error: unknown = null;
|
|
55
|
+
|
|
56
|
+
push(value: T): void { this.buffer.push(value); this.signal(); }
|
|
57
|
+
close(): void { this.done = true; this.signal(); }
|
|
58
|
+
fail(error: unknown): void { this.error = error; this.done = true; this.signal(); }
|
|
59
|
+
|
|
60
|
+
private signal(): void {
|
|
61
|
+
const wake = this.wake;
|
|
62
|
+
this.wake = null;
|
|
63
|
+
wake?.();
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
async *drain(): AsyncGenerator<T, void, unknown> {
|
|
67
|
+
while (true) {
|
|
68
|
+
while (this.buffer.length) yield this.buffer.shift() as T;
|
|
69
|
+
if (this.error) throw this.error;
|
|
70
|
+
if (this.done) return;
|
|
71
|
+
await new Promise<void>(resolve => { this.wake = resolve; });
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
|
|
48
76
|
export class ClaudeCodeEngine implements AIEngine {
|
|
49
77
|
readonly name = 'claude-code' as const;
|
|
50
78
|
private _isInitialized = false;
|
|
@@ -202,6 +230,7 @@ export class ClaudeCodeEngine implements AIEngine {
|
|
|
202
230
|
...(resume && { resume }),
|
|
203
231
|
...(maxTurns && { maxTurns }),
|
|
204
232
|
...(includePartialMessages && { includePartialMessages }),
|
|
233
|
+
forwardSubagentText: true,
|
|
205
234
|
abortController: this.activeController,
|
|
206
235
|
...(Object.keys(mcpServers).length > 0 && { mcpServers }),
|
|
207
236
|
...(allowedMcpTools.length > 0 && { allowedTools: allowedMcpTools })
|
|
@@ -224,9 +253,45 @@ export class ClaudeCodeEngine implements AIEngine {
|
|
|
224
253
|
// Per-query stateful converter so block-stop reasoning tracking persists
|
|
225
254
|
// across the stream of SDK messages.
|
|
226
255
|
const convertSdkMessage = createSdkMessageConverter();
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
256
|
+
const workflowTranscripts = new WorkflowTranscriptTailer();
|
|
257
|
+
const events = new EventQueue<EngineOutput>();
|
|
258
|
+
let sdkStreamDone = false;
|
|
259
|
+
|
|
260
|
+
const sdkProducer = (async () => {
|
|
261
|
+
try {
|
|
262
|
+
for await (const sdkMessage of queryInstance) {
|
|
263
|
+
// Register Workflow launches after queueing the corresponding parent
|
|
264
|
+
// and tool result, preserving their ordering ahead of child records.
|
|
265
|
+
for (const output of convertSdkMessage(sdkMessage)) events.push(output);
|
|
266
|
+
workflowTranscripts.observe(sdkMessage);
|
|
267
|
+
}
|
|
268
|
+
} finally {
|
|
269
|
+
sdkStreamDone = true;
|
|
270
|
+
workflowTranscripts.wake();
|
|
271
|
+
}
|
|
272
|
+
})();
|
|
273
|
+
|
|
274
|
+
const transcriptProducer = (async () => {
|
|
275
|
+
while (true) {
|
|
276
|
+
const observedVersion = workflowTranscripts.changeVersion;
|
|
277
|
+
for (const output of await workflowTranscripts.drain()) events.push(output);
|
|
278
|
+
|
|
279
|
+
if (this.activeController?.signal.aborted) break;
|
|
280
|
+
if (sdkStreamDone && !await workflowTranscripts.hasActiveWorkflows()) break;
|
|
281
|
+
await workflowTranscripts.waitForChange(observedVersion, this.activeController!.signal);
|
|
282
|
+
}
|
|
283
|
+
// The terminal status event is authoritative; drain once more for writes
|
|
284
|
+
// already queued by the filesystem before closing the merged stream.
|
|
285
|
+
for (const output of await workflowTranscripts.drain()) events.push(output);
|
|
286
|
+
})();
|
|
287
|
+
|
|
288
|
+
const producers = Promise.all([sdkProducer, transcriptProducer]);
|
|
289
|
+
void producers.then(() => events.close(), error => events.fail(error));
|
|
290
|
+
try {
|
|
291
|
+
yield* events.drain();
|
|
292
|
+
await producers;
|
|
293
|
+
} finally {
|
|
294
|
+
workflowTranscripts.dispose();
|
|
230
295
|
}
|
|
231
296
|
|
|
232
297
|
} catch (error) {
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
import { afterEach, describe, expect, test } from 'bun:test';
|
|
2
|
+
import { appendFile, mkdir, mkdtemp, rm } from 'node:fs/promises';
|
|
3
|
+
import { join } from 'node:path';
|
|
4
|
+
import { tmpdir } from 'node:os';
|
|
5
|
+
import { WorkflowTranscriptTailer } from './workflow-transcript';
|
|
6
|
+
|
|
7
|
+
const temporaryDirectories: string[] = [];
|
|
8
|
+
|
|
9
|
+
afterEach(async () => {
|
|
10
|
+
await Promise.all(temporaryDirectories.splice(0).map(path => rm(path, { recursive: true, force: true })));
|
|
11
|
+
});
|
|
12
|
+
|
|
13
|
+
describe('WorkflowTranscriptTailer', () => {
|
|
14
|
+
test('replays each appended child tool call and result exactly once', async () => {
|
|
15
|
+
const root = await mkdtemp(join(tmpdir(), 'clopen-workflow-'));
|
|
16
|
+
temporaryDirectories.push(root);
|
|
17
|
+
const sessionDirectory = join(root, 'session');
|
|
18
|
+
const directory = join(sessionDirectory, 'subagents', 'workflows', 'workflow-run-1');
|
|
19
|
+
await mkdir(directory, { recursive: true });
|
|
20
|
+
await mkdir(join(sessionDirectory, 'workflows'), { recursive: true });
|
|
21
|
+
const transcript = join(directory, 'agent-a1.jsonl');
|
|
22
|
+
await Bun.write(transcript,
|
|
23
|
+
JSON.stringify({ type: 'assistant', uuid: 'assistant-1', timestamp: '2026-01-01T00:00:01Z', message: { model: 'claude', stop_reason: 'tool_use', usage: {}, content: [{ type: 'tool_use', id: 'read-1', name: 'Read', input: { file_path: '/repo/a.ts' } }] } }) + '\n'
|
|
24
|
+
);
|
|
25
|
+
|
|
26
|
+
const launch = {
|
|
27
|
+
type: 'user', session_id: 'session-1', uuid: 'launch-1', parent_tool_use_id: null,
|
|
28
|
+
message: { role: 'user', content: [{ type: 'tool_result', tool_use_id: 'workflow-1', content: `Workflow launched in background. Task ID: task-1\nTranscript dir: ${directory}\nRun ID: workflow-run-1` }] },
|
|
29
|
+
} as any;
|
|
30
|
+
const tailer = new WorkflowTranscriptTailer();
|
|
31
|
+
tailer.observe({
|
|
32
|
+
type: 'assistant', session_id: 'session-1', uuid: 'workflow-use', parent_tool_use_id: null,
|
|
33
|
+
message: { model: 'claude', stop_reason: 'tool_use', usage: {}, content: [{ type: 'tool_use', id: 'workflow-1', name: 'Workflow', input: { script: '' } }] },
|
|
34
|
+
} as any);
|
|
35
|
+
tailer.observe(launch);
|
|
36
|
+
const first = await tailer.drain();
|
|
37
|
+
const changeVersion = tailer.changeVersion;
|
|
38
|
+
const changed = tailer.waitForChange(changeVersion, new AbortController().signal);
|
|
39
|
+
await appendFile(transcript,
|
|
40
|
+
JSON.stringify({ type: 'user', uuid: 'user-1', timestamp: '2026-01-01T00:00:02Z', message: { content: [{ type: 'tool_result', tool_use_id: 'read-1', content: 'file contents' }] } }) + '\n'
|
|
41
|
+
);
|
|
42
|
+
await changed;
|
|
43
|
+
const second = await tailer.drain();
|
|
44
|
+
const third = await tailer.drain();
|
|
45
|
+
expect(await tailer.hasActiveWorkflows()).toBe(true);
|
|
46
|
+
const statusVersion = tailer.changeVersion;
|
|
47
|
+
const statusChanged = tailer.waitForChange(statusVersion, new AbortController().signal);
|
|
48
|
+
await Bun.write(join(sessionDirectory, 'workflows', 'workflow-run-1.json'), JSON.stringify({ status: 'completed' }));
|
|
49
|
+
await statusChanged;
|
|
50
|
+
expect(await tailer.hasActiveWorkflows()).toBe(false);
|
|
51
|
+
|
|
52
|
+
expect(first).toHaveLength(1);
|
|
53
|
+
expect(first[0]).toMatchObject({
|
|
54
|
+
type: 'assistant', createdAt: '2026-01-01T00:00:01Z', parent: { toolUseId: 'workflow-1' },
|
|
55
|
+
content: [{ type: 'tool_use', id: 'read-1', name: 'Read' }],
|
|
56
|
+
});
|
|
57
|
+
expect(second).toHaveLength(1);
|
|
58
|
+
expect(second[0]).toMatchObject({
|
|
59
|
+
type: 'user', createdAt: '2026-01-01T00:00:02Z', parent: { toolUseId: 'workflow-1' },
|
|
60
|
+
content: [{ type: 'tool_result', toolUseId: 'read-1', content: 'file contents' }],
|
|
61
|
+
});
|
|
62
|
+
expect(third).toEqual([]);
|
|
63
|
+
tailer.dispose();
|
|
64
|
+
});
|
|
65
|
+
});
|
|
@@ -0,0 +1,248 @@
|
|
|
1
|
+
import { open, readFile, readdir, stat } from 'node:fs/promises';
|
|
2
|
+
import { watch, type FSWatcher } from 'node:fs';
|
|
3
|
+
import { basename, dirname, join } from 'node:path';
|
|
4
|
+
import type { SDKMessage } from '@anthropic-ai/claude-agent-sdk';
|
|
5
|
+
import type { EngineOutput } from '$shared/types/unified';
|
|
6
|
+
import { convertAssistantMessage, convertUserMessage } from './message-converter';
|
|
7
|
+
|
|
8
|
+
interface WorkflowTranscript {
|
|
9
|
+
parentToolUseId: string;
|
|
10
|
+
directory: string;
|
|
11
|
+
statusPath: string;
|
|
12
|
+
sessionId: string;
|
|
13
|
+
offsets: Map<string, number>;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
interface RawTranscriptEntry {
|
|
17
|
+
type?: string;
|
|
18
|
+
uuid?: string;
|
|
19
|
+
timestamp?: string;
|
|
20
|
+
message?: {
|
|
21
|
+
content?: unknown;
|
|
22
|
+
model?: string;
|
|
23
|
+
stop_reason?: string | null;
|
|
24
|
+
usage?: unknown;
|
|
25
|
+
};
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
function workflowRegistration(msg: SDKMessage, workflowToolUseIds: Set<string>): Omit<WorkflowTranscript, 'offsets'> | null {
|
|
29
|
+
if (msg.type !== 'user' || !Array.isArray(msg.message.content)) return null;
|
|
30
|
+
|
|
31
|
+
for (const block of msg.message.content as unknown as Array<Record<string, unknown>>) {
|
|
32
|
+
if (block.type !== 'tool_result' || typeof block.content !== 'string') continue;
|
|
33
|
+
if (!block.content.startsWith('Workflow launched in background.')) continue;
|
|
34
|
+
|
|
35
|
+
const directory = block.content.match(/^Transcript dir:\s*(.+)$/m)?.[1]?.trim();
|
|
36
|
+
const runId = block.content.match(/^Run ID:\s*(.+)$/m)?.[1]?.trim();
|
|
37
|
+
const parentToolUseId = typeof block.tool_use_id === 'string' ? block.tool_use_id : '';
|
|
38
|
+
if (directory && runId && workflowToolUseIds.has(parentToolUseId)) {
|
|
39
|
+
const sessionDirectory = dirname(dirname(dirname(directory)));
|
|
40
|
+
return {
|
|
41
|
+
parentToolUseId,
|
|
42
|
+
directory,
|
|
43
|
+
statusPath: join(sessionDirectory, 'workflows', `${basename(runId)}.json`),
|
|
44
|
+
sessionId: msg.session_id || '',
|
|
45
|
+
};
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
return null;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
function convertEntry(entry: RawTranscriptEntry, workflow: WorkflowTranscript): EngineOutput[] {
|
|
53
|
+
if (!entry.message || !entry.uuid) return [];
|
|
54
|
+
const preserveTimestamp = (outputs: EngineOutput[]): EngineOutput[] => {
|
|
55
|
+
if (!entry.timestamp) return outputs;
|
|
56
|
+
return outputs.map(output => {
|
|
57
|
+
if (output.type !== 'assistant' && output.type !== 'user') return output;
|
|
58
|
+
return { ...output, createdAt: entry.timestamp as string };
|
|
59
|
+
});
|
|
60
|
+
};
|
|
61
|
+
|
|
62
|
+
if (entry.type === 'assistant' && Array.isArray(entry.message.content)) {
|
|
63
|
+
const visibleContent = entry.message.content.filter((block: unknown) => {
|
|
64
|
+
if (!block || typeof block !== 'object') return false;
|
|
65
|
+
const type = (block as { type?: string }).type;
|
|
66
|
+
return type === 'text' || type === 'tool_use';
|
|
67
|
+
});
|
|
68
|
+
if (visibleContent.length === 0) return [];
|
|
69
|
+
|
|
70
|
+
return preserveTimestamp(convertAssistantMessage({
|
|
71
|
+
type: 'assistant',
|
|
72
|
+
uuid: entry.uuid,
|
|
73
|
+
session_id: workflow.sessionId,
|
|
74
|
+
parent_tool_use_id: workflow.parentToolUseId,
|
|
75
|
+
message: { ...entry.message, content: visibleContent },
|
|
76
|
+
} as Parameters<typeof convertAssistantMessage>[0]));
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
if (entry.type === 'user' && Array.isArray(entry.message.content)) {
|
|
80
|
+
const toolResults = entry.message.content.filter((block: unknown) => (
|
|
81
|
+
Boolean(block && typeof block === 'object' && (block as { type?: string }).type === 'tool_result')
|
|
82
|
+
));
|
|
83
|
+
if (toolResults.length === 0) return [];
|
|
84
|
+
|
|
85
|
+
return preserveTimestamp([convertUserMessage({
|
|
86
|
+
type: 'user',
|
|
87
|
+
uuid: entry.uuid,
|
|
88
|
+
session_id: workflow.sessionId,
|
|
89
|
+
parent_tool_use_id: workflow.parentToolUseId,
|
|
90
|
+
message: { role: 'user', content: toolResults },
|
|
91
|
+
} as Parameters<typeof convertUserMessage>[0])]);
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
return [];
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
async function readAppendedLines(path: string, offset: number): Promise<{ lines: string[]; offset: number }> {
|
|
98
|
+
const info = await stat(path);
|
|
99
|
+
if (info.size <= offset) return { lines: [], offset };
|
|
100
|
+
|
|
101
|
+
const handle = await open(path, 'r');
|
|
102
|
+
try {
|
|
103
|
+
const buffer = Buffer.alloc(info.size - offset);
|
|
104
|
+
const { bytesRead } = await handle.read(buffer, 0, buffer.length, offset);
|
|
105
|
+
const chunk = buffer.subarray(0, bytesRead).toString('utf8');
|
|
106
|
+
const lastNewline = chunk.lastIndexOf('\n');
|
|
107
|
+
if (lastNewline < 0) return { lines: [], offset };
|
|
108
|
+
|
|
109
|
+
return {
|
|
110
|
+
lines: chunk.slice(0, lastNewline).split('\n').filter(Boolean),
|
|
111
|
+
offset: offset + Buffer.byteLength(chunk.slice(0, lastNewline + 1)),
|
|
112
|
+
};
|
|
113
|
+
} finally {
|
|
114
|
+
await handle.close();
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/** Incrementally replays Workflow-owned agent transcripts into the Workflow parent. */
|
|
119
|
+
export class WorkflowTranscriptTailer {
|
|
120
|
+
private workflows = new Map<string, WorkflowTranscript>();
|
|
121
|
+
private workflowToolUseIds = new Set<string>();
|
|
122
|
+
private watchers = new Map<string, FSWatcher>();
|
|
123
|
+
private waiters = new Set<() => void>();
|
|
124
|
+
private version = 0;
|
|
125
|
+
|
|
126
|
+
get changeVersion(): number {
|
|
127
|
+
return this.version;
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
private signalChange(): void {
|
|
131
|
+
this.version += 1;
|
|
132
|
+
const waiters = [...this.waiters];
|
|
133
|
+
this.waiters.clear();
|
|
134
|
+
for (const resolve of waiters) resolve();
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
private watchPath(path: string): void {
|
|
138
|
+
if (this.watchers.has(path)) return;
|
|
139
|
+
try {
|
|
140
|
+
const watcher = watch(path, { persistent: false }, () => this.signalChange());
|
|
141
|
+
watcher.on('error', () => {
|
|
142
|
+
watcher.close();
|
|
143
|
+
this.watchers.delete(path);
|
|
144
|
+
this.signalChange();
|
|
145
|
+
});
|
|
146
|
+
this.watchers.set(path, watcher);
|
|
147
|
+
} catch {
|
|
148
|
+
// A final drain still captures files created before the watcher attaches.
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
wake(): void {
|
|
153
|
+
this.signalChange();
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
async waitForChange(afterVersion: number, signal: AbortSignal): Promise<void> {
|
|
157
|
+
if (this.version !== afterVersion || signal.aborted) return;
|
|
158
|
+
await new Promise<void>(resolve => {
|
|
159
|
+
const finish = () => {
|
|
160
|
+
this.waiters.delete(finish);
|
|
161
|
+
signal.removeEventListener('abort', finish);
|
|
162
|
+
resolve();
|
|
163
|
+
};
|
|
164
|
+
this.waiters.add(finish);
|
|
165
|
+
signal.addEventListener('abort', finish, { once: true });
|
|
166
|
+
// Close the race between the version check and waiter registration.
|
|
167
|
+
if (this.version !== afterVersion) finish();
|
|
168
|
+
});
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
observe(msg: SDKMessage): void {
|
|
172
|
+
if (msg.type === 'assistant' && Array.isArray(msg.message.content)) {
|
|
173
|
+
for (const block of msg.message.content) {
|
|
174
|
+
if (block.type === 'tool_use' && block.name === 'Workflow') {
|
|
175
|
+
this.workflowToolUseIds.add(block.id);
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
const registration = workflowRegistration(msg, this.workflowToolUseIds);
|
|
181
|
+
if (registration && !this.workflows.has(registration.parentToolUseId)) {
|
|
182
|
+
this.workflows.set(registration.parentToolUseId, { ...registration, offsets: new Map() });
|
|
183
|
+
this.watchPath(registration.directory);
|
|
184
|
+
this.watchPath(dirname(registration.statusPath));
|
|
185
|
+
this.signalChange();
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
async drain(): Promise<EngineOutput[]> {
|
|
190
|
+
const entries: Array<{ entry: RawTranscriptEntry; workflow: WorkflowTranscript }> = [];
|
|
191
|
+
for (const workflow of this.workflows.values()) {
|
|
192
|
+
let files: string[];
|
|
193
|
+
try {
|
|
194
|
+
files = (await readdir(workflow.directory))
|
|
195
|
+
.filter(name => name.startsWith('agent-') && name.endsWith('.jsonl'))
|
|
196
|
+
.sort();
|
|
197
|
+
} catch {
|
|
198
|
+
continue;
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
for (const file of files) {
|
|
202
|
+
const path = `${workflow.directory}/${file}`;
|
|
203
|
+
const previousOffset = workflow.offsets.get(path) || 0;
|
|
204
|
+
try {
|
|
205
|
+
const appended = await readAppendedLines(path, previousOffset);
|
|
206
|
+
workflow.offsets.set(path, appended.offset);
|
|
207
|
+
for (const line of appended.lines) {
|
|
208
|
+
try {
|
|
209
|
+
entries.push({ entry: JSON.parse(line) as RawTranscriptEntry, workflow });
|
|
210
|
+
} catch {
|
|
211
|
+
// A malformed transcript record must not interrupt the chat stream.
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
} catch {
|
|
215
|
+
// Agent files are created and appended concurrently by Claude Code.
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
entries.sort((a, b) => (a.entry.timestamp || '').localeCompare(b.entry.timestamp || ''));
|
|
221
|
+
return entries.flatMap(({ entry, workflow }) => convertEntry(entry, workflow));
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
async hasActiveWorkflows(): Promise<boolean> {
|
|
225
|
+
for (const workflow of this.workflows.values()) {
|
|
226
|
+
try {
|
|
227
|
+
const state = JSON.parse(await readFile(workflow.statusPath, 'utf8')) as { status?: string };
|
|
228
|
+
const terminal = new Set(['complete', 'completed', 'success', 'failed', 'error', 'killed', 'cancelled']);
|
|
229
|
+
if (!state.status || !terminal.has(state.status.toLowerCase())) return true;
|
|
230
|
+
} catch {
|
|
231
|
+
// The run status file is written when the background Workflow settles.
|
|
232
|
+
return true;
|
|
233
|
+
}
|
|
234
|
+
}
|
|
235
|
+
return false;
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
async capture(msg: SDKMessage): Promise<EngineOutput[]> {
|
|
239
|
+
this.observe(msg);
|
|
240
|
+
return this.drain();
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
dispose(): void {
|
|
244
|
+
for (const watcher of this.watchers.values()) watcher.close();
|
|
245
|
+
this.watchers.clear();
|
|
246
|
+
this.signalChange();
|
|
247
|
+
}
|
|
248
|
+
}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import { describe, expect, test } from 'bun:test';
|
|
2
|
+
import { mapCopilotToolName } from './copilot/message-converter';
|
|
3
|
+
import { canonicaliseToolName as mapQwenToolName } from './qwen/message-converter';
|
|
4
|
+
|
|
5
|
+
describe('multi-agent coordination tool mappings', () => {
|
|
6
|
+
test('maps Qwen send_message', () => {
|
|
7
|
+
expect(mapQwenToolName('send_message')).toBe('SendMessage');
|
|
8
|
+
});
|
|
9
|
+
|
|
10
|
+
test('maps Copilot coordination tools', () => {
|
|
11
|
+
expect(mapCopilotToolName('write_agent')).toBe('SendMessage');
|
|
12
|
+
expect(mapCopilotToolName('list_agents')).toBe('ListAgents');
|
|
13
|
+
expect(mapCopilotToolName('read_agent')).toBe('ReadAgent');
|
|
14
|
+
expect(mapCopilotToolName('send_inbox')).toBe('SendInbox');
|
|
15
|
+
expect(mapCopilotToolName('context_board')).toBe('ContextBoard');
|
|
16
|
+
});
|
|
17
|
+
});
|