@myrialabs/clopen 0.1.2 → 0.1.4

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 (63) hide show
  1. package/CONTRIBUTING.md +40 -355
  2. package/README.md +46 -113
  3. package/backend/lib/engine/adapters/opencode/message-converter.ts +53 -2
  4. package/backend/lib/engine/adapters/opencode/stream.ts +89 -5
  5. package/backend/lib/mcp/config.ts +7 -3
  6. package/backend/lib/mcp/servers/helper.ts +25 -14
  7. package/backend/lib/mcp/servers/index.ts +7 -2
  8. package/backend/lib/project/status-manager.ts +221 -181
  9. package/frontend/lib/components/chat/ChatInterface.svelte +7 -0
  10. package/frontend/lib/components/chat/input/components/EngineModelPicker.svelte +16 -9
  11. package/frontend/lib/components/chat/message/ChatMessages.svelte +16 -4
  12. package/frontend/lib/components/chat/tools/AgentTool.svelte +12 -11
  13. package/frontend/lib/components/chat/tools/BashOutputTool.svelte +3 -3
  14. package/frontend/lib/components/chat/tools/BashTool.svelte +4 -4
  15. package/frontend/lib/components/chat/tools/CustomMcpTool.svelte +3 -1
  16. package/frontend/lib/components/chat/tools/EditTool.svelte +6 -6
  17. package/frontend/lib/components/chat/tools/ExitPlanModeTool.svelte +1 -1
  18. package/frontend/lib/components/chat/tools/GlobTool.svelte +12 -12
  19. package/frontend/lib/components/chat/tools/GrepTool.svelte +5 -5
  20. package/frontend/lib/components/chat/tools/ListMcpResourcesTool.svelte +1 -1
  21. package/frontend/lib/components/chat/tools/NotebookEditTool.svelte +6 -6
  22. package/frontend/lib/components/chat/tools/ReadMcpResourceTool.svelte +2 -2
  23. package/frontend/lib/components/chat/tools/ReadTool.svelte +4 -4
  24. package/frontend/lib/components/chat/tools/TaskStopTool.svelte +1 -1
  25. package/frontend/lib/components/chat/tools/TaskTool.svelte +1 -1
  26. package/frontend/lib/components/chat/tools/TodoWriteTool.svelte +4 -4
  27. package/frontend/lib/components/chat/tools/WebSearchTool.svelte +1 -1
  28. package/frontend/lib/components/chat/tools/WriteTool.svelte +3 -3
  29. package/frontend/lib/components/chat/tools/components/CodeBlock.svelte +3 -3
  30. package/frontend/lib/components/chat/tools/components/DiffBlock.svelte +2 -2
  31. package/frontend/lib/components/chat/tools/components/FileHeader.svelte +1 -1
  32. package/frontend/lib/components/chat/tools/components/InfoLine.svelte +2 -2
  33. package/frontend/lib/components/chat/tools/components/StatsBadges.svelte +1 -1
  34. package/frontend/lib/components/chat/tools/components/TerminalCommand.svelte +5 -5
  35. package/frontend/lib/components/common/Button.svelte +1 -1
  36. package/frontend/lib/components/common/Card.svelte +3 -3
  37. package/frontend/lib/components/common/Input.svelte +3 -3
  38. package/frontend/lib/components/common/LoadingSpinner.svelte +1 -1
  39. package/frontend/lib/components/common/Select.svelte +6 -6
  40. package/frontend/lib/components/common/Textarea.svelte +3 -3
  41. package/frontend/lib/components/files/FileViewer.svelte +1 -1
  42. package/frontend/lib/components/git/ChangesSection.svelte +2 -4
  43. package/frontend/lib/components/preview/browser/BrowserPreview.svelte +9 -29
  44. package/frontend/lib/components/preview/browser/components/Container.svelte +17 -0
  45. package/frontend/lib/components/preview/browser/components/VirtualCursor.svelte +2 -2
  46. package/frontend/lib/components/settings/appearance/AppearanceSettings.svelte +0 -6
  47. package/frontend/lib/components/settings/appearance/LayoutPresetSettings.svelte +15 -15
  48. package/frontend/lib/components/settings/appearance/LayoutPreview.svelte +2 -2
  49. package/frontend/lib/components/settings/engines/AIEnginesSettings.svelte +1 -1
  50. package/frontend/lib/components/workspace/DesktopNavigator.svelte +380 -383
  51. package/frontend/lib/components/workspace/MobileNavigator.svelte +391 -395
  52. package/frontend/lib/components/workspace/PanelHeader.svelte +623 -505
  53. package/frontend/lib/components/workspace/ViewMenu.svelte +9 -25
  54. package/frontend/lib/components/workspace/layout/split-pane/Layout.svelte +29 -4
  55. package/frontend/lib/components/workspace/panels/ChatPanel.svelte +3 -2
  56. package/frontend/lib/services/notification/global-stream-monitor.ts +77 -86
  57. package/frontend/lib/services/project/status.service.ts +160 -159
  58. package/frontend/lib/stores/ui/workspace.svelte.ts +326 -283
  59. package/package.json +1 -1
  60. package/scripts/pre-publish-check.sh +0 -142
  61. package/scripts/setup-hooks.sh +0 -134
  62. package/scripts/validate-branch-name.sh +0 -47
  63. package/scripts/validate-commit-msg.sh +0 -42
package/README.md CHANGED
@@ -1,6 +1,4 @@
1
- # 🎯 Clopen
2
-
3
- > All-in-one web workspace for Claude Code & OpenCode
1
+ # Clopen
4
2
 
5
3
  [![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](LICENSE)
6
4
  [![Built with Bun](https://img.shields.io/badge/Built%20with-Bun-black)](https://bun.sh)
@@ -9,27 +7,28 @@
9
7
 
10
8
  ---
11
9
 
12
- ## Features
13
-
14
- - 👤 **Multi-Account Claude Code** - Manage multiple accounts (personal, work, team) and switch instantly per session, isolated under `~/.clopen/claude/user/` without touching system-level Claude config
15
- - 🔀 **Multi-Engine Support** - Switch between Claude Code and OpenCode
16
- - 💬 **AI Chat Interface** - Streaming responses with tool use visualization
17
- - 🔄 **Background Processing** - Chat, terminal, and other processes continue running even when you close the browser — come back later and pick up where you left off
18
- - 🌿 **Git-like Checkpoints** - Multi-branch undo/redo system with file and folder snapshots
19
- - 🌐 **Real Browser Preview** - Puppeteer-based Chromium rendering with WebCodecs streaming (80-90% bandwidth reduction), full click/type/scroll/drag interaction
20
- - 💻 **Integrated Terminal** - Multi-tab terminal with full PTY control
21
- - 📁 **File Management** - Directory browsing, live editing, and real-time file watching
22
- - 🗂️ **Git Management** - Full source control: staging, commits, branches, push/pull, stash, log, conflict resolution
23
- - 👥 **Real-time Collaboration** - Multiple users can work on the same project simultaneously
24
- - 🚇 **Built-in Cloudflare Tunnel** - Expose local projects publicly for testing and sharing
10
+ ## Features
11
+
12
+ - **Multi-Account Claude Code** - Manage multiple accounts (personal, work, team) and switch instantly per session, isolated under `~/.clopen/claude/user/` without touching system-level Claude config
13
+ - **Multi-Engine Support** - Switch between Claude Code and OpenCode
14
+ - **AI Chat Interface** - Streaming responses with tool use visualization
15
+ - **Background Processing** - Chat, terminal, and other processes continue running even when you close the browser — come back later and pick up where you left off
16
+ - **Git-like Checkpoints** - Multi-branch undo/redo system with file and folder snapshots
17
+ - **Real Browser Preview** - Puppeteer-based Chromium rendering with WebCodecs streaming (80-90% bandwidth reduction), full click/type/scroll/drag interaction
18
+ - **Integrated Terminal** - Multi-tab terminal with full PTY control
19
+ - **File Management** - Directory browsing, live editing, and real-time file watching
20
+ - **Git Management** - Full source control: staging, commits, branches, push/pull, stash, log, conflict resolution
21
+ - **Real-time Collaboration** - Multiple users can work on the same project simultaneously
22
+ - **Built-in Cloudflare Tunnel** - Expose local projects publicly for testing and sharing
23
+
25
24
  ---
26
25
 
27
- ## 🚀 Quick Start
26
+ ## Quick Start
28
27
 
29
28
  ### Prerequisites
30
29
 
31
- - [Bun](https://bun.sh/) v1.2.12 or higher
32
- - [Claude Code](https://github.com/anthropics/claude-code) and/or [OpenCode](https://opencode.ai) — required for AI chat functionality
30
+ - [Bun](https://bun.sh/) v1.2.12+
31
+ - [Claude Code](https://github.com/anthropics/claude-code) and/or [OpenCode](https://github.com/anomalyco/opencode) — required for AI chat functionality
33
32
 
34
33
  ### Installation
35
34
 
@@ -37,25 +36,25 @@
37
36
  bun add -g @myrialabs/clopen
38
37
  ```
39
38
 
40
- This installs dependencies, builds the frontend, and makes the `clopen` command available globally.
41
-
42
- ### Usage
39
+ ### Update
43
40
 
44
41
  ```bash
45
- clopen
42
+ bun add -g @myrialabs/clopen
46
43
  ```
47
44
 
48
- On first run, Clopen creates `.env` from `.env.example`, verifies the build, and starts the server on `http://localhost:9141`.
45
+ Same command as installation Bun will update to the latest version.
46
+
47
+ ### Usage
49
48
 
50
- **Configuration** — edit `.env` to customize:
51
49
  ```bash
52
- PORT=9141 # Server port
53
- NODE_ENV=production # Environment mode
50
+ clopen
54
51
  ```
55
52
 
53
+ Starts the server on `http://localhost:9141`.
54
+
56
55
  ---
57
56
 
58
- ## 🛠️ Development
57
+ ## Development
59
58
 
60
59
  ```bash
61
60
  git clone https://github.com/myrialabs/clopen.git
@@ -67,7 +66,7 @@ bun run check # Type checking
67
66
 
68
67
  ---
69
68
 
70
- ## 📚 Architecture
69
+ ## Architecture
71
70
 
72
71
  | Layer | Technology |
73
72
  |-------|-----------|
@@ -79,58 +78,22 @@ bun run check # Type checking
79
78
  | Terminal | bun-pty |
80
79
  | AI Engines | Claude Code + OpenCode |
81
80
 
82
- ### Engine Architecture
83
-
84
- Clopen uses an engine-agnostic adapter pattern — the frontend and stream manager are not tied to any specific AI tool:
85
-
86
- ```
87
- ┌─────────────────────────────────────────┐
88
- │ Stream Manager │
89
- └──────────────┬──────────────────────────┘
90
-
91
- ┌───────┴───────┐
92
- ▼ ▼
93
- ClaudeCodeEngine OpenCodeEngine
94
- ```
95
-
96
- Both engines normalize output to Claude SDK message format, ensuring a consistent experience regardless of which engine is selected.
81
+ Clopen uses an engine-agnostic adapter pattern — both engines normalize output to Claude SDK message format, ensuring a consistent experience regardless of which engine is selected.
97
82
 
98
83
  ---
99
84
 
100
- ## 🛣️ Planned Features
101
-
102
- - [ ] **Configurable MCP Servers** - Add, remove, enable, and disable Model Context Protocol servers through the UI
103
- - [ ] **Built-in Database Management** - Adminer/TablePlus-like interface
104
- - [ ] **Additional Preview Platforms** - Android, iOS, and Desktop app preview
105
- - [ ] **Enhanced Collaboration** - User authentication and permissions
106
- - [ ] **Plugin System** - Extensible architecture for community plugins
107
-
108
- ---
109
-
110
- ## 📖 Documentation
85
+ ## Documentation
111
86
 
112
87
  - [Technical Decisions](DECISIONS.md) - Architectural and technical decision log
88
+ - [Contributing](CONTRIBUTING.md) - How to contribute to this project
113
89
  - [Development Guidelines](CLAUDE.md) - Guidelines for working with Claude Code on this project
114
90
 
115
91
  ---
116
92
 
117
- ## 🤝 Contributing
118
-
119
- 1. Fork the repository
120
- 2. Create a feature branch (`git checkout -b feature/amazing-feature`)
121
- 3. Make your changes
122
- 4. Run `bun run check` to ensure code quality
123
- 5. Commit your changes (`git commit -m 'Add amazing feature'`)
124
- 6. Push to the branch (`git push origin feature/amazing-feature`)
125
- 7. Open a Pull Request
126
-
127
- ---
128
-
129
- ## 🐛 Troubleshooting
93
+ ## Troubleshooting
130
94
 
131
95
  ### Port 9141 Already in Use
132
96
 
133
- Use a different port:
134
97
  ```bash
135
98
  clopen --port 9150
136
99
  ```
@@ -145,65 +108,35 @@ netstat -ano | findstr :9141
145
108
  taskkill /PID <PID> /F
146
109
  ```
147
110
 
148
- ### Claude Code Not Found
149
-
150
- ```bash
151
- # macOS / Linux / WSL
152
- curl -fsSL https://claude.ai/install.sh | bash
153
-
154
- # Windows PowerShell
155
- irm https://claude.ai/install.ps1 | iex
156
-
157
- # Verify
158
- claude --version
159
- ```
160
-
161
- For complete installation instructions, visit the [official setup guide](https://code.claude.com/docs/en/quickstart).
162
-
163
- ### OpenCode Not Found
164
-
165
- ```bash
166
- # macOS / Linux / WSL
167
- curl -fsSL https://opencode.ai/install | bash
168
-
169
- # Bun
170
- bun add -g opencode-ai
171
-
172
- # Verify
173
- opencode --version
174
- ```
175
-
176
- For complete installation instructions, visit the [official documentation](https://opencode.ai/docs).
177
-
178
- ### Browser Preview Issues
179
-
180
- Browser sessions are automatically managed via Puppeteer's APIs and cleaned up when the preview is closed, the application exits, or the session times out.
181
-
182
111
  ---
183
112
 
184
- ## 📄 License
113
+ ## License
185
114
 
186
115
  MIT License - see [LICENSE](LICENSE) for details.
187
116
 
188
117
  ---
189
118
 
190
- ## 🙏 Acknowledgments
119
+ ## Acknowledgments
191
120
 
192
121
  - [Claude Code](https://github.com/anthropics/claude-code) by Anthropic
193
- - [OpenCode](https://opencode.ai) by SST
122
+ - [OpenCode](https://opencode.ai) by Anomaly
194
123
  - [Bun](https://bun.sh/) runtime
195
124
  - [Svelte](https://svelte.dev/) framework
196
125
 
197
126
  ---
198
127
 
199
- ## 🔗 Links
128
+ ## Support
129
+
130
+ If Clopen is useful to you, consider supporting its development:
200
131
 
201
- - **Repository:** [github.com/myrialabs/clopen](https://github.com/myrialabs/clopen)
202
- - **Organization:** [MyriaLabs](https://github.com/myrialabs)
203
- - **Issues:** [Report a bug or request a feature](https://github.com/myrialabs/clopen/issues)
132
+ | Method | Address / Link |
133
+ |--------|----------------|
134
+ | Bitcoin (BTC) | `bc1qd9fyx4r84cce2a9hkjksetah802knadw5msls3` |
135
+ | Solana (SOL) | `Ev3P4KLF1PNC5C9rZYP8M3DdssyBQAQAiNJkvNmPQPVs` |
136
+ | Ethereum (ERC-20) | `0x61D826e5b666AA5345302EEEd485Acca39b1AFCF` |
137
+ | USDT (TRC-20) | `TLH49i3EoVKhFyLb6u2JUXZWScK7uzksdC` |
138
+ | Saweria | [saweria.co/myrialabs](https://saweria.co/myrialabs) |
204
139
 
205
140
  ---
206
141
 
207
- <div align="center">
208
- <sub>Built with ❤️ by MyriaLabs</sub>
209
- </div>
142
+ **Repository:** [github.com/myrialabs/clopen](https://github.com/myrialabs/clopen) · **Issues:** [Report a bug or request a feature](https://github.com/myrialabs/clopen/issues)
@@ -127,6 +127,8 @@ const TOOL_NAME_MAP: Record<string, string> = {
127
127
  'todo_write': 'TodoWrite',
128
128
  'todowrite': 'TodoWrite',
129
129
  'todoread': 'TodoWrite',
130
+ // Agent / sub-agent
131
+ 'task': 'Agent',
130
132
  // User interaction
131
133
  'question': 'AskUserQuestion',
132
134
  // Code intelligence & utilities
@@ -385,6 +387,7 @@ interface AssistantMessageParams {
385
387
  sessionId: string;
386
388
  stopReason: string | null;
387
389
  uuid: string;
390
+ parentToolUseId?: string | null;
388
391
  }
389
392
 
390
393
  /** Build a single SDKAssistantMessage from content blocks */
@@ -402,7 +405,7 @@ function buildAssistantSDKMessage(params: AssistantMessageParams): SDKMessage {
402
405
  ...(params.usage && { usage: params.usage }),
403
406
  context_management: null
404
407
  },
405
- parent_tool_use_id: null,
408
+ parent_tool_use_id: params.parentToolUseId ?? null,
406
409
  session_id: params.sessionId,
407
410
  uuid: params.uuid
408
411
  } as unknown as SDKMessage;
@@ -495,6 +498,20 @@ export function convertAssistantMessages(
495
498
 
496
499
  allBlocks.push(block);
497
500
  }
501
+ else if (part.type === 'subtask') {
502
+ // Subtask = Agent/sub-agent invocation
503
+ const subtaskPart = part as any;
504
+ allBlocks.push({
505
+ type: 'tool_use',
506
+ id: subtaskPart.id || crypto.randomUUID(),
507
+ name: 'Agent',
508
+ input: {
509
+ prompt: subtaskPart.prompt || '',
510
+ description: subtaskPart.description || '',
511
+ subagent_type: subtaskPart.agent || 'general-purpose',
512
+ } as NormalizedToolInput,
513
+ });
514
+ }
498
515
  // Skip: reasoning, step-start, step-finish, snapshot, patch, agent, retry, compaction
499
516
  }
500
517
 
@@ -682,6 +699,7 @@ export function convertToolUseOnly(
682
699
  toolPart: ToolPart,
683
700
  ocMessage: OCMessage,
684
701
  sessionId: string,
702
+ parentToolUseId: string | null = null,
685
703
  ): SDKMessage {
686
704
  const claudeName = mapToolName(toolPart.tool || 'unknown');
687
705
  const resolvedInput = getToolInput(toolPart);
@@ -703,6 +721,7 @@ export function convertToolUseOnly(
703
721
  sessionId,
704
722
  stopReason: 'tool_use',
705
723
  uuid: crypto.randomUUID(),
724
+ parentToolUseId,
706
725
  });
707
726
  }
708
727
 
@@ -783,6 +802,37 @@ export function convertReasoningStreamStop(sessionId: string): EngineSDKMessage
783
802
  } as unknown as EngineSDKMessage;
784
803
  }
785
804
 
805
+ /**
806
+ * Convert a subtask part → assistant message with Agent tool_use.
807
+ * Used for progressive rendering when OpenCode emits subtask parts.
808
+ */
809
+ export function convertSubtaskToolUseOnly(
810
+ subtaskPart: { id: string; prompt: string; description: string; agent: string },
811
+ ocMessage: OCMessage,
812
+ sessionId: string,
813
+ ): SDKMessage {
814
+ const assistantMsg = ocMessage.role === 'assistant' ? ocMessage as AssistantMessage : null;
815
+ const modelId = assistantMsg ? `${assistantMsg.providerID}/${assistantMsg.modelID}` : '';
816
+
817
+ return buildAssistantSDKMessage({
818
+ content: [{
819
+ type: 'tool_use',
820
+ id: subtaskPart.id || crypto.randomUUID(),
821
+ name: 'Agent',
822
+ input: {
823
+ prompt: subtaskPart.prompt || '',
824
+ description: subtaskPart.description || '',
825
+ subagent_type: subtaskPart.agent || 'general-purpose',
826
+ } as NormalizedToolInput,
827
+ }],
828
+ ocMessage,
829
+ modelId,
830
+ sessionId,
831
+ stopReason: 'tool_use',
832
+ uuid: crypto.randomUUID(),
833
+ });
834
+ }
835
+
786
836
  /**
787
837
  * Convert a completed/errored tool part → user message with tool_result.
788
838
  * Sent after the tool finishes executing, matching Claude Code's pattern
@@ -791,6 +841,7 @@ export function convertReasoningStreamStop(sessionId: string): EngineSDKMessage
791
841
  export function convertToolResultOnly(
792
842
  toolPart: ToolPart,
793
843
  sessionId: string,
844
+ parentToolUseId: string | null = null,
794
845
  ): SDKMessage {
795
846
  const toolUseId = toolPart.callID || toolPart.id || crypto.randomUUID();
796
847
 
@@ -807,7 +858,7 @@ export function convertToolResultOnly(
807
858
  type: 'user',
808
859
  uuid: crypto.randomUUID(),
809
860
  session_id: sessionId,
810
- parent_tool_use_id: null,
861
+ parent_tool_use_id: parentToolUseId,
811
862
  message: {
812
863
  role: 'user',
813
864
  content: [{
@@ -37,6 +37,7 @@ import {
37
37
  convertPartialReasoningDelta,
38
38
  convertReasoningStreamStart,
39
39
  convertReasoningStreamStop,
40
+ convertSubtaskToolUseOnly,
40
41
  getToolInput,
41
42
  } from './message-converter';
42
43
  import { ensureClient, getClient } from './server';
@@ -236,6 +237,13 @@ export class OpenCodeEngine implements AIEngine {
236
237
  let reasoningStreamActive = false; // Whether reasoning is currently streaming
237
238
  let reasoningText = ''; // Accumulated reasoning text
238
239
 
240
+ // Child session tracking (for Agent tool sub-messages)
241
+ const childSessionToAgentTool = new Map<string, string>(); // child sessionID → agent tool callID
242
+ const childAssistantMessages = new Map<string, OCMessage>(); // child msgID → message
243
+ const childEmittedToolParts = new Set<string>();
244
+ const childCompletedToolParts = new Set<string>();
245
+ let lastAgentToolCallId: string | null = null;
246
+
239
247
  /**
240
248
  * Flush active reasoning stream: stop reasoning stream, emit final reasoning message.
241
249
  */
@@ -266,9 +274,10 @@ export class OpenCodeEngine implements AIEngine {
266
274
  yield convertStreamStop(sessionId);
267
275
 
268
276
  const parts = messageParts.get(msgId) || [];
269
- // Filter out tool parts and reasoning parts already emitted
277
+ // Filter out tool parts, subtask parts, and reasoning parts already emitted
270
278
  const remainingParts = parts.filter(p => {
271
279
  if (p.type === 'tool') return !emittedToolParts.has(p.id);
280
+ if (p.type === 'subtask') return !emittedToolParts.has(p.id);
272
281
  if (p.type === 'reasoning') return false; // Already emitted as reasoning message
273
282
  return true;
274
283
  });
@@ -312,6 +321,15 @@ export class OpenCodeEngine implements AIEngine {
312
321
  }
313
322
  currentAssistantId = info.id;
314
323
  }
324
+
325
+ // Track child session assistant messages (for Agent tool sub-messages)
326
+ if (info.role === 'assistant' && info.sessionID !== sessionId && lastAgentToolCallId) {
327
+ if (!childSessionToAgentTool.has(info.sessionID)) {
328
+ childSessionToAgentTool.set(info.sessionID, lastAgentToolCallId);
329
+ debug.log('engine', `[OC] child session detected: ${info.sessionID} → agent tool ${lastAgentToolCallId}`);
330
+ }
331
+ childAssistantMessages.set(info.id, info);
332
+ }
315
333
  break;
316
334
  }
317
335
 
@@ -321,8 +339,36 @@ export class OpenCodeEngine implements AIEngine {
321
339
 
322
340
  debug.log('engine', `[OC] part.updated: type=${part.type}, partId=${part.id}, msgId=${part.messageID}, session=${part.sessionID === sessionId ? 'match' : 'skip'}`);
323
341
 
324
- // Only process parts belonging to our session
325
- if (part.sessionID !== sessionId) break;
342
+ // Handle child session parts (sub-agent tool activities)
343
+ if (part.sessionID !== sessionId) {
344
+ const agentCallId = childSessionToAgentTool.get(part.sessionID);
345
+ if (agentCallId && childAssistantMessages.has(part.messageID)) {
346
+ const childMsg = childAssistantMessages.get(part.messageID)!;
347
+
348
+ if (part.type === 'tool') {
349
+ const childToolPart = part as ToolPart;
350
+ if (!childEmittedToolParts.has(part.id)) {
351
+ const resolvedInput = getToolInput(childToolPart);
352
+ const hasInput = Object.keys(resolvedInput).length > 0
353
+ || childToolPart.state.status !== 'pending';
354
+ if (hasInput) {
355
+ childEmittedToolParts.add(part.id);
356
+ yield convertToolUseOnly(childToolPart, childMsg, sessionId, agentCallId);
357
+ if (childToolPart.state.status === 'completed' || childToolPart.state.status === 'error') {
358
+ childCompletedToolParts.add(part.id);
359
+ yield convertToolResultOnly(childToolPart, sessionId, agentCallId);
360
+ }
361
+ }
362
+ } else if (!childCompletedToolParts.has(part.id)) {
363
+ if (childToolPart.state.status === 'completed' || childToolPart.state.status === 'error') {
364
+ childCompletedToolParts.add(part.id);
365
+ yield convertToolResultOnly(childToolPart, sessionId, agentCallId);
366
+ }
367
+ }
368
+ }
369
+ }
370
+ break;
371
+ }
326
372
 
327
373
  // Only process parts for tracked assistant messages (skip user message parts)
328
374
  if (!assistantMessages.has(part.messageID)) {
@@ -364,6 +410,11 @@ export class OpenCodeEngine implements AIEngine {
364
410
  if (hasInput) {
365
411
  emittedToolParts.add(part.id);
366
412
 
413
+ // Track agent tool callID for child session linking
414
+ if (toolPart.tool === 'task') {
415
+ lastAgentToolCallId = toolPart.callID || toolPart.id;
416
+ }
417
+
367
418
  yield convertStreamStop(sessionId);
368
419
  yield convertToolUseOnly(toolPart, msg, sessionId);
369
420
 
@@ -412,6 +463,25 @@ export class OpenCodeEngine implements AIEngine {
412
463
  }
413
464
  }
414
465
 
466
+ // Handle subtask parts — convert to Agent tool_use for progressive rendering
467
+ if (part.type === 'subtask') {
468
+ const subtaskPart = part as any;
469
+ const msg = assistantMessages.get(msgId);
470
+ if (msg && !emittedToolParts.has(part.id)) {
471
+ emittedToolParts.add(part.id);
472
+ // Track for child session linking
473
+ lastAgentToolCallId = part.id;
474
+ if (reasoningStreamActive) {
475
+ yield* flushReasoning(msg);
476
+ }
477
+ yield convertStreamStop(sessionId);
478
+ yield convertSubtaskToolUseOnly(subtaskPart, msg, sessionId);
479
+ yield convertStreamStart(sessionId);
480
+ streamingText = '';
481
+ }
482
+ break;
483
+ }
484
+
415
485
  // Skip non-text/non-reasoning parts (step-start, step-finish, etc.)
416
486
  if (part.type !== 'text') {
417
487
  debug.log('engine', `[OC] part.updated: skipped non-text type=${part.type}`);
@@ -455,6 +525,12 @@ export class OpenCodeEngine implements AIEngine {
455
525
  }
456
526
 
457
527
  case 'session.idle': {
528
+ // Only handle idle for our session (sub-agent sessions have different IDs)
529
+ const idleProps = (event as EventSessionIdle).properties;
530
+ if (idleProps.sessionID !== sessionId) {
531
+ debug.log('engine', `[OC] session.idle: ignored (session=${idleProps.sessionID}, ours=${sessionId})`);
532
+ break;
533
+ }
458
534
  // Session finished — flush reasoning and emit the last assistant message
459
535
  if (currentAssistantId && !emittedMessageIds.has(currentAssistantId)) {
460
536
  const msg = assistantMessages.get(currentAssistantId);
@@ -468,6 +544,7 @@ export class OpenCodeEngine implements AIEngine {
468
544
  // Filter out tool parts and reasoning parts already emitted
469
545
  const remainingParts = parts.filter(p => {
470
546
  if (p.type === 'tool') return !emittedToolParts.has(p.id);
547
+ if (p.type === 'subtask') return !emittedToolParts.has(p.id);
471
548
  if (p.type === 'reasoning') return false;
472
549
  return true;
473
550
  });
@@ -495,7 +572,10 @@ export class OpenCodeEngine implements AIEngine {
495
572
  }
496
573
 
497
574
  case 'session.status': {
498
- const { status } = (event as EventSessionStatus).properties;
575
+ const statusProps = (event as EventSessionStatus).properties;
576
+ // Only handle status for our session (sub-agent sessions have different IDs)
577
+ if (statusProps.sessionID !== sessionId) break;
578
+ const { status } = statusProps;
499
579
  if (status.type === 'idle') {
500
580
  // Same as session.idle
501
581
  if (currentAssistantId && !emittedMessageIds.has(currentAssistantId)) {
@@ -508,6 +588,7 @@ export class OpenCodeEngine implements AIEngine {
508
588
  const parts = messageParts.get(currentAssistantId) || [];
509
589
  const remainingParts = parts.filter(p => {
510
590
  if (p.type === 'tool') return !emittedToolParts.has(p.id);
591
+ if (p.type === 'subtask') return !emittedToolParts.has(p.id);
511
592
  if (p.type === 'reasoning') return false;
512
593
  return true;
513
594
  });
@@ -584,7 +665,10 @@ export class OpenCodeEngine implements AIEngine {
584
665
  }
585
666
 
586
667
  case 'session.error': {
587
- const { error } = (event as EventSessionError).properties;
668
+ const errorProps = (event as EventSessionError).properties;
669
+ // Only handle errors for our session (sessionID is optional on errors)
670
+ if (errorProps.sessionID && errorProps.sessionID !== sessionId) break;
671
+ const { error } = errorProps;
588
672
  // Extract a human-readable error message.
589
673
  // OpenCode SDK errors follow: { name: string, data: { message, statusCode?, providerID?, responseBody? } }
590
674
  // Don't prepend error class names (e.g. "APIError") — those are SDK
@@ -8,7 +8,7 @@
8
8
  import type { McpSdkServerConfigWithInstance, McpServerConfig } from "@anthropic-ai/claude-agent-sdk";
9
9
  import type { McpLocalConfig } from '@opencode-ai/sdk';
10
10
  import type { ServerConfig, ParsedMcpToolName, ServerName } from './types';
11
- import { serverRegistry } from './servers';
11
+ import { serverRegistry, serverFactories } from './servers';
12
12
  import { debug } from '$shared/utils/logger';
13
13
  import { resolve } from 'path';
14
14
  import { SERVER_ENV } from '../shared/env';
@@ -84,14 +84,18 @@ export const mcpServers: Record<string, ServerConfig & { instance: McpSdkServerC
84
84
  // ============================================================================
85
85
 
86
86
  /**
87
- * Get all enabled MCP servers for Claude SDK
87
+ * Get all enabled MCP servers for Claude SDK.
88
+ *
89
+ * Creates FRESH server instances each call so that concurrent streams
90
+ * each get their own Protocol — avoids "Already connected to a transport" errors.
88
91
  */
89
92
  export function getEnabledMcpServers(): Record<string, McpServerConfig> {
90
93
  const enabledServers: Record<string, McpServerConfig> = {};
91
94
 
92
95
  Object.entries(mcpServers).forEach(([serverName, serverConfig]) => {
93
96
  if (serverConfig.enabled) {
94
- enabledServers[serverName] = serverConfig.instance;
97
+ const factory = serverFactories[serverName as ServerName];
98
+ enabledServers[serverName] = factory ? factory() : serverConfig.instance;
95
99
  debug.log('mcp', `✓ Enabled MCP server: ${serverName}`);
96
100
  } else {
97
101
  debug.log('mcp', `✗ Disabled MCP server: ${serverName}`);
@@ -52,6 +52,8 @@ interface ServerWithMeta<
52
52
  TToolNames extends readonly string[]
53
53
  > {
54
54
  server: ReturnType<typeof createSdkMcpServer>;
55
+ /** Factory that creates a fresh SDK server instance (new Protocol, safe for concurrent use) */
56
+ createInstance: () => ReturnType<typeof createSdkMcpServer>;
55
57
  meta: {
56
58
  readonly name: TName;
57
59
  readonly tools: TToolNames;
@@ -84,32 +86,36 @@ export function defineServer<
84
86
  // Build raw tool definitions (engine-agnostic)
85
87
  const toolDefs: Record<string, RawToolDef> = {};
86
88
 
87
- // Convert tools object to SDK format (array of tools)
88
- const sdkTools = toolNames.map((toolName) => {
89
+ // Build raw tool definitions (engine-agnostic) and store for reuse
90
+ toolNames.forEach((toolName) => {
89
91
  const toolDef = config.tools[toolName] as any;
90
- // If schema is not provided, use empty object
91
92
  const schema = toolDef.schema || {};
92
93
 
93
- // Store raw definition for reuse
94
94
  toolDefs[toolName as string] = {
95
95
  description: toolDef.description,
96
96
  schema,
97
97
  handler: toolDef.handler,
98
98
  };
99
-
100
- return tool(toolName as string, toolDef.description, schema, toolDef.handler);
101
99
  });
102
100
 
103
- // Create SDK server
104
- const server = createSdkMcpServer({
105
- name: config.name,
106
- version: config.version,
107
- tools: sdkTools
108
- });
101
+ // Factory: creates a fresh SDK server instance with new Protocol (safe for concurrent use)
102
+ const createInstance = () => {
103
+ const sdkTools = toolNames.map((toolName) => {
104
+ const def = toolDefs[toolName as string];
105
+ return tool(toolName as string, def.description, def.schema, def.handler as any);
106
+ });
107
+
108
+ return createSdkMcpServer({
109
+ name: config.name,
110
+ version: config.version,
111
+ tools: sdkTools
112
+ });
113
+ };
109
114
 
110
- // Return server with metadata
115
+ // Return server with metadata and factory
111
116
  return {
112
- server,
117
+ server: createInstance(),
118
+ createInstance,
113
119
  meta: {
114
120
  name: config.name,
115
121
  tools: toolNames as any,
@@ -126,10 +132,12 @@ export function buildServerRegistries<
126
132
  >(servers: T) {
127
133
  const metadata = {} as any;
128
134
  const registry = {} as any;
135
+ const factories = {} as any;
129
136
 
130
137
  for (const server of servers) {
131
138
  metadata[server.meta.name] = server.meta;
132
139
  registry[server.meta.name] = server.server;
140
+ factories[server.meta.name] = server.createInstance;
133
141
  }
134
142
 
135
143
  return {
@@ -138,6 +146,9 @@ export function buildServerRegistries<
138
146
  },
139
147
  registry: registry as {
140
148
  [K in T[number]['meta']['name']]: Extract<T[number], { meta: { name: K } }>['server']
149
+ },
150
+ factories: factories as {
151
+ [K in T[number]['meta']['name']]: () => Extract<T[number], { meta: { name: K } }>['server']
141
152
  }
142
153
  };
143
154
  }
@@ -32,7 +32,7 @@ const allServers = [
32
32
  /**
33
33
  * Auto-build registries from server array
34
34
  */
35
- const { metadata, registry } = buildServerRegistries(allServers);
35
+ const { metadata, registry, factories } = buildServerRegistries(allServers);
36
36
 
37
37
  /**
38
38
  * Server Metadata Registry - Defines available servers and their tools
@@ -42,4 +42,9 @@ export const serverMetadata = metadata;
42
42
  /**
43
43
  * Server Instance Registry - Maps server names to SDK instances
44
44
  */
45
- export const serverRegistry = registry;
45
+ export const serverRegistry = registry;
46
+
47
+ /**
48
+ * Server Factory Registry - Creates fresh SDK instances (safe for concurrent streams)
49
+ */
50
+ export const serverFactories = factories;