@myrialabs/clopen 0.3.12 → 0.3.14

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 (55) hide show
  1. package/backend/auth/session-invalidation.test.ts +45 -1
  2. package/backend/auth/session-invalidation.ts +35 -1
  3. package/backend/chat/stream-manager.ts +15 -0
  4. package/backend/database/migrations/037_repair_auth_audit_log_schema.ts +38 -0
  5. package/backend/database/migrations/index.ts +7 -0
  6. package/backend/engine/README.md +16 -1597
  7. package/backend/engine/adapters/claude/message-converter.ts +34 -7
  8. package/backend/engine/adapters/claude/models.ts +174 -2
  9. package/backend/engine/adapters/codex/stream.ts +54 -1
  10. package/backend/engine/adapters/copilot/stream.ts +79 -19
  11. package/backend/engine/adapters/opencode/stream.ts +23 -23
  12. package/backend/engine/adapters/qwen/stream.ts +83 -1
  13. package/backend/engine/docs/adapter-contract.md +183 -0
  14. package/backend/engine/docs/adding-an-engine.md +150 -0
  15. package/backend/engine/docs/database.md +123 -0
  16. package/backend/engine/docs/frontend-and-chat.md +176 -0
  17. package/backend/engine/docs/lessons-learned.md +715 -0
  18. package/backend/engine/docs/quick-reference.md +36 -0
  19. package/backend/engine/docs/system-tools.md +82 -0
  20. package/backend/engine/docs/websocket-routes.md +240 -0
  21. package/backend/engine/structured-helpers.ts +59 -0
  22. package/backend/files/file-archive.test.ts +131 -0
  23. package/backend/files/file-archive.ts +252 -0
  24. package/backend/files/file-operations.ts +39 -66
  25. package/backend/files/file-size-limit.test.ts +71 -15
  26. package/backend/files/file-size-limit.ts +36 -8
  27. package/backend/files/file-watcher.ts +117 -3
  28. package/backend/http/files-upload.ts +168 -0
  29. package/backend/index.ts +8 -0
  30. package/backend/mcp/servers/helper.ts +5 -1
  31. package/backend/projects/project-cleanup.ts +1 -1
  32. package/backend/terminal/pty-session-manager.ts +3 -0
  33. package/backend/terminal/stream-manager.ts +1 -1
  34. package/backend/utils/ws.ts +9 -0
  35. package/backend/ws/auth/users.ts +1 -1
  36. package/backend/ws/chat/stream.ts +46 -38
  37. package/backend/ws/files/path-access.test.ts +166 -0
  38. package/backend/ws/files/path-access.ts +56 -22
  39. package/backend/ws/files/read.ts +5 -5
  40. package/backend/ws/files/watch.ts +48 -19
  41. package/backend/ws/files/write.ts +53 -27
  42. package/backend/ws/git/commit-message.ts +12 -5
  43. package/backend/ws/terminal/session.ts +1 -0
  44. package/dist/assets/main-BqiSLc8F.css +1 -0
  45. package/dist/assets/{main-HIDO3ugS.js → main-C37-Y8f-.js} +230 -229
  46. package/dist/index.html +2 -2
  47. package/package.json +8 -7
  48. package/shared/types/git.ts +4 -2
  49. package/shared/types/stores/settings.ts +2 -0
  50. package/shared/types/unified/index.ts +6 -0
  51. package/shared/types/unified/stream.ts +15 -1
  52. package/shared/types/unified/tool.ts +41 -1
  53. package/shared/utils/ws-server.ts +6 -0
  54. package/backend/engine/adapters/copilot/session-fork.ts +0 -111
  55. package/dist/assets/main-C2JiGYnx.css +0 -1
@@ -0,0 +1,715 @@
1
+ [← Engine adapter guide](../README.md)
2
+
3
+ ## 9. Lessons learned — pitfalls when authoring a new adapter
4
+
5
+ These notes come from building the `copilot` adapter. Each item has been
6
+ gotten wrong at least once — keep this mental checklist in your head when
7
+ writing the next adapter.
8
+
9
+ ### 9.1 Both tool name **and** tool input must be canonicalised
10
+
11
+ `toCanonicalToolName()` only guarantees the tool name does not become
12
+ `Unknown:*`. That is **not enough**: tool UI components (`Bash`, `Read`,
13
+ `Edit`, …) read specific fields (`command`, `filePath`, `oldString`, …).
14
+ Other SDKs use `snake_case` (`file_path`, `old_str`) or even bundle
15
+ multiple subcommands under a single name (e.g. Copilot's
16
+ `str_replace_editor` → split into `view`/`create`/`str_replace`/`edit`/`insert`).
17
+
18
+ The pattern used in `copilot/message-converter.ts`:
19
+
20
+ ```ts
21
+ // 1. Map raw name → canonical UI name (snake → PascalCase + dispatch subcommand).
22
+ const COPILOT_TOOL_NAME_MAP: Record<string, string> = { 'bash': 'Bash', ... };
23
+ function mapCopilotToolName(rawName, mcpServerName) { ... }
24
+
25
+ // 2. Per-tool normaliser: takes Record<string, unknown>, returns canonical shape.
26
+ function normalizeReadInput(raw): ReadInput {
27
+ // path → filePath, view_range:[s,e] → offset/limit, etc.
28
+ }
29
+
30
+ // 3. Dispatcher called from buildToolUseBlock.
31
+ function normalizeCopilotToolInput(canonical, raw) {
32
+ switch (canonical) { case 'Read': return normalizeReadInput(raw); ... }
33
+ }
34
+ ```
35
+
36
+ If only the name mapping is done, the UI still picks the right component
37
+ but the fields are `undefined` → the user sees an empty block. Always
38
+ install **both** layers.
39
+
40
+ ### 9.2 Filter the SDK's "harness tools"
41
+
42
+ Some SDKs emit internal tools used for model↔harness coordination that
43
+ **must not** appear in chat (intent reporting, task-completion markers,
44
+ internal documentation). Examples from Copilot CLI: `report_intent`,
45
+ `task_complete`, `propose_work`, `fetch_copilot_cli_documentation`.
46
+
47
+ Strategy: filter at the adapter boundary, do not render `Unknown:*`. See
48
+ `copilot/message-converter.ts::IGNORED_COPILOT_TOOLS` +
49
+ `isIgnoredCopilotTool()`. Drop **both sides**: the tool_use (in
50
+ `convertAssistantMessage`) **and** the tool_result that arrives later (in
51
+ `convertToolComplete`) — if you only drop one side, the UI either gets an
52
+ orphan result without a tool or an orphan tool without a result.
53
+
54
+ ### 9.3 One `tool_use` per `AssistantMessage`
55
+
56
+ The convention used by Claude and OpenCode: each assistant message that
57
+ reaches the frontend has **at most one** `tool_use` block. SDKs like
58
+ Copilot CLI may send a single `assistant.message` with many `toolRequests`
59
+ — the adapter must split it.
60
+
61
+ Pattern:
62
+ ```ts
63
+ const blocks: AssistantContentBlock[] = [];
64
+ if (data.content) blocks.push({ type: 'text', text: data.content });
65
+ for (const req of visibleToolRequests) blocks.push(buildToolUseBlock(req));
66
+
67
+ const messages = blocks.map((block, idx) => ({
68
+ type: 'assistant',
69
+ messageId: blocks.length === 1 ? baseId : `${baseId}:${idx}`,
70
+ content: [block], // one block per message
71
+ ...
72
+ }));
73
+ ```
74
+
75
+ If violated, the frontend `message-grouper` still works but Compact mode
76
+ and the tool layout do not stitch correctly.
77
+
78
+ ### 9.4 Buffer messages until the usage event arrives
79
+
80
+ In many SDKs (Copilot included), `assistant.usage` is a **separate** event
81
+ that arrives **after** `assistant.message` for the same turn iteration.
82
+ If the adapter yields the message immediately, the `usage` field is
83
+ always `null` in the DB and in the token-cost dashboard.
84
+
85
+ Buffering pattern in `copilot/message-converter.ts`:
86
+
87
+ ```ts
88
+ // State:
89
+ pendingMessages: UnifiedAssistantMessage[];
90
+ lastUsage: AssistantUsageData | null;
91
+
92
+ // convertAssistantMessage: push to pending, return what was already flushed.
93
+ state.pendingMessages.push(...messages);
94
+ return flushPending(state); // flush old queue, leave the new ones waiting
95
+
96
+ // captureUsage: attach to the last pending, then flush.
97
+ state.pendingMessages.at(-1)!.usage = mapUsage(data);
98
+ return flushPending(state);
99
+
100
+ // flushPending also has a fallback: if a pending message still has
101
+ // usage == null but state.lastUsage is set, fill it in. This covers
102
+ // turns where the SDK emits assistant.message after assistant.usage,
103
+ // or tool-only iterations whose usage event landed earlier.
104
+ //
105
+ // Defensive flush at tool.execution_complete, turn_end, session.idle —
106
+ // preserve ordering even when the SDK sends events out of order.
107
+ ```
108
+
109
+ The `lastUsage` state is also kept around to build the aggregate
110
+ `ResultEvent` at `session.idle` — that is the **per-stream** usage, not
111
+ per-message.
112
+
113
+ ### 9.5 `tool_use.result: null` is **expected** before render
114
+
115
+ When inspecting raw adapter output (e.g. logs or DB rows before render),
116
+ `tool_use` blocks always carry `result: null`. That is **correct**: the
117
+ tool_result arrives as a synthetic `UserMessage` with `toolUseId`. The
118
+ frontend `message-grouper.ts` (via `processToolMessage` + `toolUseMap`)
119
+ attaches it at display time.
120
+
121
+ Do not try to perform that stitching in the adapter — if you do, the
122
+ `stream-manager` loses the chance to persist the tool_result as its own
123
+ DB row, and resume-session breaks.
124
+
125
+ **Sharp edge — `parent.toolUseId` MUST be null on the synthetic
126
+ UserMessage.** The toolCallId belongs only on the inner `tool_result`
127
+ block, never on the message-level `parent.toolUseId`. The frontend
128
+ grouper interprets any user message with `parent.toolUseId !== null` as
129
+ a **sub-agent message** (i.e. one emitted from inside an `Agent` /
130
+ `Task` tool execution): if the parent id matches an Agent tool it goes
131
+ into the sub-agent activity bucket, otherwise it is silently dropped.
132
+ Setting `parent.toolUseId = data.toolCallId` therefore makes the
133
+ tool_result invisible to the UI and `tool_use.result` stays null after
134
+ render.
135
+
136
+ ```ts
137
+ // ✅ correct — top-level tool_result (Claude, OpenCode, Copilot)
138
+ parent: { messageId: null, sessionId: null, toolUseId: null }
139
+
140
+ // ❌ wrong — frontend grouper drops this as a "sub-agent" message
141
+ parent: { messageId: null, sessionId: null, toolUseId: data.toolCallId }
142
+ ```
143
+
144
+ Only set `parent.toolUseId` when the message is genuinely a child of an
145
+ `Agent` / `Task` tool execution (e.g. the OpenCode Task adapter passes
146
+ `parentToolUseId` through `convertToolResultOnly`). For raw
147
+ `tool.execution_complete` events at the top of the loop, leave it null.
148
+
149
+ ### 9.6 Enable the SDK's streaming flag explicitly
150
+
151
+ Some SDKs default to emitting only the final message. For delta/partial
152
+ streaming you must set the SDK-specific flag:
153
+
154
+ - Copilot: `streaming: true` in `SessionConfig` & `ResumeSessionConfig`.
155
+ - OpenCode: `partial: true` in chat options.
156
+ - Claude: `includePartialMessages: true` (already on by default in
157
+ `ClaudeCodeEngine.streamQuery`).
158
+
159
+ Without the flag, the UI shows text "all at once" — the symptom is
160
+ identical to an adapter that forgot to emit `StreamLifecycleEvent` /
161
+ `TextDeltaEvent`, so check the flag first before debugging the converter.
162
+
163
+ ### 9.7 Pair `start`/`stop` lifecycle for reasoning
164
+
165
+ The frontend stream-manager renders reasoning in a separate bubble
166
+ **only** while `StreamLifecycleEvent { reasoning: true, event: 'start' }`
167
+ is open. Always emit `stop` when reasoning ends (or when assistant text
168
+ begins — the two are mutually exclusive in the UI). See
169
+ `copilot/message-converter.ts::convertReasoningDelta`, which flushes the
170
+ text stream before opening the reasoning stream.
171
+
172
+ ### 9.8 Event-order debug workflow
173
+
174
+ If chat output looks weird, log the raw `SessionEvent` per stream before
175
+ the converter. The canonical Copilot order is:
176
+
177
+ ```
178
+ session.start
179
+ assistant.turn_start
180
+ [assistant.reasoning_delta...] assistant.reasoning
181
+ [assistant.message_delta...] assistant.message assistant.usage
182
+ tool.execution_start
183
+ tool.execution_complete
184
+ [loop back to reasoning/message for the next turn iteration]
185
+ assistant.turn_end
186
+ session.idle
187
+ ```
188
+
189
+ From here it is easy to trace: if `usage` is always null, buffering is
190
+ wrong. If you see orphan tool_results, the ignored-tools filter is not
191
+ consistent on both sides. If text appears all at once, the SDK streaming
192
+ flag is off.
193
+
194
+ ### 9.9 Per-stream account override when the SDK takes the credential at construction
195
+
196
+ Most SDKs accept env vars per-call (Claude) or read them from the
197
+ subprocess environment (OpenCode). The Copilot SDK is different: the
198
+ GitHub token is passed to `new CopilotClient({ gitHubToken })` at
199
+ construction time and cannot be swapped on the fly.
200
+
201
+ Pattern in `copilot/stream.ts`:
202
+
203
+ ```ts
204
+ private currentAccountId: number | null = null;
205
+
206
+ async initialize(accountId?: number): Promise<void> {
207
+ if (this._isInitialized && (accountId == null || accountId === this.currentAccountId)) {
208
+ return; // already initialised with this account → no-op
209
+ }
210
+ const account = accountId != null
211
+ ? engineQueries.getAccount(accountId)
212
+ : engineQueries.getActiveAccountForEngine('copilot');
213
+ this.client = new CopilotClient({ gitHubToken: account.credential, ... });
214
+ this.currentAccountId = account.id;
215
+ ...
216
+ }
217
+
218
+ async *streamQuery(options) {
219
+ // Per-stream account override: dispose + re-init when it differs.
220
+ if (this._isInitialized && options.accountId != null
221
+ && options.accountId !== this.currentAccountId) {
222
+ await this.dispose();
223
+ }
224
+ if (!this._isInitialized) await this.initialize(options.accountId);
225
+ ...
226
+ }
227
+ ```
228
+
229
+ The frontend wiring is shared with Claude (single-account-list engines —
230
+ see §6.2): both stores expose the same API, so `EngineModelPicker.svelte`
231
+ uses one derived `accountsForEngine` and one dropdown. To add a fourth
232
+ adapter that follows this same pattern, just add a branch in the four
233
+ derived values and the `$effect` blocks; do not duplicate the dropdown.
234
+
235
+ If you forget the per-stream override path, the chat input appears to
236
+ honour the account picker but the engine actually streams against the
237
+ last initialised credential — silently using the wrong PAT/quota.
238
+
239
+ ### 9.10 Fork session — native API vs. on-disk workaround
240
+
241
+ The multi-branch checkpoints feature requires that **every** resume
242
+ spawn a fresh session id, so the engine continues from that point
243
+ **without** mutating the original session's history. Each adapter wires
244
+ it differently, but the contract is the same: fork unconditionally on
245
+ resume.
246
+
247
+ | Adapter | How |
248
+ |-----------|----------------------------------------------------------------------------------------------|
249
+ | Claude | Pass `forkSession: true` in the SDK options on every call — native. |
250
+ | OpenCode | Call `client.session.fork({ path: { id: resume } })` on every resume — native. |
251
+ | Copilot | Call `client.rpc.sessions.fork({ sessionId: resume })` on every resume — native (`@experimental`, added in `@github/copilot-sdk` 1.0.0-beta.4). |
252
+ | Codex | **No native API yet** — fork by copying the rollout JSONL FILE on every resume. |
253
+ | Qwen Code | **No native API yet** — fork by copying the chat JSONL FILE on every resume. |
254
+
255
+ > **Sharp edge — fork is NOT gated on `EngineQueryOptions.forkSession`.**
256
+ > The `forkSession` field exists on the type but the stream-manager
257
+ > never sets it; Claude/OpenCode hard-code their fork call. Every other
258
+ > adapter must do the same. If you only fork "when forkSession is true"
259
+ > the same session id is reused across every turn (visible in persisted
260
+ > assistant messages) and downstream branch logic breaks.
261
+
262
+ The two remaining on-disk workarounds (Codex and Qwen) follow the same
263
+ shape — copy the state, replace the source id with a fresh one, then
264
+ resume against the fork — but the SDKs lay state out differently. Get
265
+ the layout wrong and `sessionStateExists()` silently returns false on
266
+ every turn, the fork block is skipped, and the engine resumes the
267
+ original session — exactly the symptom multi-branch checkpoints
268
+ surface as.
269
+
270
+ **Codex — single rollout JSONL in a date-tree.** The thread id is in
271
+ the filename, not a directory name:
272
+
273
+ ```
274
+ ~/.codex/sessions/<YYYY>/<MM>/<DD>/rollout-<TIMESTAMP>-<thread_id>.jsonl
275
+ ```
276
+
277
+ The fork helper walks the date-tree to find the source by
278
+ `-<thread_id>.jsonl` suffix, copies it into TODAY's `YYYY/MM/DD` dir
279
+ under a new `rollout-<now>-<forkId>.jsonl` filename, and replaces every
280
+ occurrence of the source id (UUIDs don't collide with other content in
281
+ the file). Earlier versions of `codex/session-fork.ts` mistakenly
282
+ assumed a directory layout (`~/.codex/sessions/<thread_id>/`) — the
283
+ result was a permanently-broken fork because `sessionStateExists()`
284
+ never matched. If you change the helper, watch for that regression.
285
+
286
+ **Qwen Code — single chat JSONL keyed by sanitised cwd.** The chat id
287
+ is the filename basename; the parent directory is derived from the
288
+ project's cwd via the SDK's `sanitizeCwd()`
289
+ (`cwd.replace(/[^a-zA-Z0-9]/g, '-')`, lowercased on win32):
290
+
291
+ ```
292
+ ~/.qwen/projects/<sanitized-cwd>/chats/<sessionId>.jsonl
293
+ ```
294
+
295
+ Every record line carries a `sessionId` field equal to the file's
296
+ basename. The fork helper copies the file to
297
+ `<chats>/<forkId>.jsonl` in the same project directory and replaces
298
+ the source id throughout. The Qwen `session-fork.ts` therefore takes
299
+ `projectPath` as an extra argument — Codex and Copilot are
300
+ cwd-agnostic because their layouts aren't keyed on it.
301
+
302
+ ```ts
303
+ // stream.ts (resume path) — fork on EVERY resume; pattern is identical
304
+ // across copilot/codex/qwen, only the helper signature differs.
305
+ let resumeId = resume;
306
+ if (resume && sessionStateExists(/* projectPath if qwen, */ resume)) {
307
+ const forkId = crypto.randomUUID();
308
+ if (forkXxxSessionState(/* projectPath if qwen, */ resume, forkId)) {
309
+ resumeId = forkId;
310
+ }
311
+ }
312
+ // then pass resumeId to the SDK's resume entry point.
313
+ ```
314
+
315
+ The expected effect, observable by logging the session/thread id per
316
+ turn:
317
+
318
+ ```
319
+ turn 1 user → assistant sessionId: A
320
+ turn 2 user → assistant sessionId: B (forked from A)
321
+ turn 3 user → assistant sessionId: C (forked from B)
322
+ ```
323
+
324
+ Every assistant message carries its **own** session id. Reusing the
325
+ same id across turns is the symptom that forking is gated or skipped.
326
+
327
+ When an SDK eventually adds a native `forkSession` (or equivalent), the
328
+ migration is a one-liner: delete that adapter's `session-fork.ts`, drop
329
+ the fork block in `stream.ts`, and pass the SDK flag the same way
330
+ Claude, OpenCode, and Copilot already do. The `// TODO` comment at the
331
+ top of each `session-fork.ts` pins the migration target.
332
+
333
+ ### 9.11 Reset `currentAccountId` in `dispose()`
334
+
335
+ Whenever you track per-init state on the engine (e.g.
336
+ `currentAccountId`, cached models, the SDK client itself), reset every
337
+ field in `dispose()`. A half-disposed engine that still reports
338
+ `isInitialized = false` but holds a stale `currentAccountId` will short-
339
+ circuit the next `initialize(accountId)` call and reuse the wrong
340
+ credential.
341
+
342
+ ```ts
343
+ async dispose(): Promise<void> {
344
+ await this.cancel();
345
+ if (this.client) await this.client.stop();
346
+ this.client = null;
347
+ this.modelsCache = null;
348
+ this.currentAccountId = null; // ← do not forget
349
+ this._isInitialized = false;
350
+ }
351
+ ```
352
+
353
+ ### 9.12 Reuse the existing MCP HTTP infrastructure — never build a new bridge
354
+
355
+ `backend/mcp/remote-server.ts` already mounts every server registered via
356
+ `defineServer()` as a **Streamable HTTP MCP** endpoint at
357
+ `http://localhost:<port>/mcp`. OpenCode consumes it via
358
+ `getOpenCodeMcpConfig()`. Tool handlers run **in-process** in the Clopen
359
+ backend — there is no subprocess, no per-engine HTTP listener, no
360
+ per-stream MCP path. Project context propagates via
361
+ `projectContextService` (AsyncLocalStorage with a `mostRecentActiveStream`
362
+ fallback when the transport doesn't preserve the context).
363
+
364
+ When you add an engine whose CLI/SDK accepts a streamable-http MCP URL
365
+ (e.g. Codex, Copilot):
366
+
367
+ 1. Add a sibling helper next to `getOpenCodeMcpConfig()` —
368
+ `getXxxMcpConfig()` — that returns the **same** URL in the engine's
369
+ expected shape (Codex format: `{ '<server-name>': { url: '...' } }`;
370
+ Copilot format: `{ '<server-name>': { type: 'http', url: '...', tools: [...] } }`).
371
+ The engine sees every enabled MCP server (`browser-automation`,
372
+ `weather-service`, …) as one logical MCP server namespace exposing all
373
+ the tools.
374
+
375
+ **Naming conventions for the helper** (mirror the existing two so the
376
+ reviewer doesn't ping you twice):
377
+ - Use the SDK's **exported type** for the return shape if one exists
378
+ — e.g. Open Code's `McpRemoteConfig` from `@opencode-ai/sdk`,
379
+ Copilot's `MCPHTTPServerConfig` from `@github/copilot-sdk`. Only
380
+ define a local type alias when the SDK doesn't export one (Codex).
381
+ - Reuse the `'clopen-mcp'` namespace key. Don't invent a new one
382
+ per engine — the tool-name resolver below depends on it.
383
+ - In the adapter, name the local variable holding the helper's return
384
+ value **`mcpConfig`**, not `mcpServers`. The latter shadows both the
385
+ SDK's config field name AND the registry exported from
386
+ `backend/mcp/config.ts`, and reads as a bug at the call site.
387
+
388
+ 2. Use `resolveOpenCodeToolName()` (in `backend/mcp/config.ts`) on
389
+ incoming tool names; it strips the `clopen-mcp_` / `clopen-mcp-`
390
+ prefix and reverse-maps to `mcp__<server>__<tool>`. The same helper
391
+ works for any engine that uses the same naming convention.
392
+
393
+ **Engines DO NOT agree on the prefix separator.** Open Code joins the
394
+ server-config key to the tool name with `_` (`clopen-mcp_open_new_tab`);
395
+ Copilot joins with `-` (`clopen-mcp-open_new_tab`); Codex emits a bare
396
+ tool name and carries the server name separately on the event payload.
397
+ `resolveOpenCodeToolName()` strips **both** `clopen-mcp_` and
398
+ `clopen-mcp-` prefixes for this reason. If a new engine introduces yet
399
+ another separator, extend the prefix list in that helper — do **not**
400
+ add a parallel resolver in the adapter.
401
+
402
+ The symptom of skipping this step is a tool that renders in the UI
403
+ with the doubled-up name `mcp__clopen-mcp__clopen-mcp-<tool>` instead
404
+ of `mcp__<server>__<tool>` — the prefix didn't strip and the registry
405
+ lookup fell through to the `mcp__<mcpServerName>__<rawName>` fallback.
406
+
407
+ 3. If your engine has **no callback hook** for AskUserQuestion (Codex's
408
+ SDK is the canonical example), AskUserQuestion stays unsupported for
409
+ that engine until the upstream SDK exposes a native primitive. The
410
+ previous engine-agnostic MCP fallback (`ask-user-question` tool +
411
+ stream-keyed pending registry) was removed once the carrying cost —
412
+ AsyncLocalStorage plumbing, dual resolve paths in
413
+ `backend/ws/chat/stream.ts`, manual cancel-aborts — outweighed the
414
+ benefit. Wire the engine's native hook to `resolveUserAnswer` when it
415
+ ships; do not reintroduce a parallel MCP path.
416
+
417
+ 4. Auto-approval of MCP tool calls is **per-engine**, not centralised.
418
+ Each SDK exposes its own approval surface and they are not
419
+ interchangeable:
420
+ - Claude Code: `canUseTool` returns `{ behavior: 'allow' }` for all
421
+ non-AskUserQuestion tools (already handled by the adapter).
422
+ - Open Code: replies `'once'` to `permission.asked` events at runtime
423
+ via `autoApprovePermission()`.
424
+ - Codex: enumerates every enabled tool with `approval_mode: 'approve'`
425
+ in the per-server config — `codex exec` is non-interactive and has
426
+ no runtime approval channel, so the decision must be baked in
427
+ up-front.
428
+ - Copilot: `onPermissionRequest: approveAll` covers MCP tools
429
+ too — no per-tool enumeration needed.
430
+
431
+ Wire whichever path exists; do not assume Codex-style enumeration is
432
+ required when a runtime hook is available, and do not assume runtime
433
+ approval works when only static config is offered.
434
+
435
+ What you must NOT do:
436
+ - ❌ A second HTTP listener (e.g. "MCP HTTP bridge for Codex"). Reuse `/mcp`.
437
+ - ❌ Per-engine MCP servers in `backend/mcp/servers/` (e.g. one folder
438
+ per engine). All MCP servers are engine-agnostic and registered via
439
+ `defineServer()` once.
440
+ - ❌ Per-stream bearer tokens or unique URLs. Authorization piggy-backs
441
+ on `projectContextService` exactly like the Claude in-process path.
442
+ - ❌ A new namespace key in `getXxxMcpConfig()` (e.g. `'copilot-mcp'`).
443
+ Always use `'clopen-mcp'` — `resolveOpenCodeToolName()` keys off it.
444
+ - ❌ A local type alias when the SDK exports the type (Open Code,
445
+ Copilot). Import `McpRemoteConfig` / `MCPHTTPServerConfig` directly.
446
+
447
+ ### 9.13 Auth-blob swap into a shared CLI dotfile (vs. per-account isolated dirs)
448
+
449
+ When a CLI hard-codes its credential location (Codex reads
450
+ `~/.codex/auth.json`; Gemini CLI reads `~/.gemini/oauth_creds.json`;
451
+ etc.), the naïve approach is to give each Clopen account its own
452
+ isolated home directory and override the CLI's home env var
453
+ (`CODEX_HOME`, `GEMINI_HOME`). **Don't.** That approach has bitten us:
454
+
455
+ - Session/thread state lives in the same dir tree (`~/.codex/sessions/`,
456
+ `~/.codex/projects/`), so isolating the dir splits session memory,
457
+ breaks fork-by-copy, and loses the user's `config.toml` overrides.
458
+ - Token refresh happens in-place in the dotfile — refreshes performed
459
+ inside an isolated dir do not propagate back to the user's "real"
460
+ home unless we add a watcher.
461
+ - The CLI's other features (e.g. project trust, `.agents` allowlist)
462
+ expect the dir to be the user's normal one.
463
+
464
+ **Use the shared-location-with-DB-swap pattern instead:**
465
+
466
+ | Step | Behavior |
467
+ |---|---|
468
+ | **Login** | Spawn the CLI's login command (`codex login`, etc.) which writes the user's normal dotfile. On success, **read the dotfile content** and persist it to `engine_accounts.credential` as a JSON wrapper, e.g. `{ kind: 'chatgpt', authJson: '<file content>' }`. |
469
+ | **Switch account** | `accounts-switch` handler reads the chosen account's `credential`, parses the wrapper, writes `authJson` **back to the shared dotfile** with an atomic replace (`write to .tmp` + `rename`). |
470
+ | **Stream-start** | Adapter ensures the dotfile reflects the right blob (re-write if drift detected; cheap idempotent op). |
471
+ | **Stream-end** | Read the dotfile back and snapshot it into the active account's `credential` so any token refresh the CLI performed during the turn survives across switches. |
472
+
473
+ Trade-off: only **one** Codex/CLI account is "active" on disk at a
474
+ time. Concurrent streams from two different accounts will race; UI must
475
+ surface only one active account per engine and document the limitation.
476
+ For Clopen, that matches existing UI assumptions. If a future engine
477
+ genuinely needs concurrent multi-account streams, escalate the trade-off
478
+ explicitly — do **not** silently switch to per-account home dirs.
479
+
480
+ Concurrency caveat: if the login command itself writes to the shared
481
+ dotfile (Codex's `codex login` does), serialize the login flows with a
482
+ backend-wide mutex so two simultaneous "Add Account" attempts can't
483
+ clobber each other.
484
+
485
+ ### 9.14 Long-lived server engines need a "Restart Server" UX
486
+
487
+ If your engine boots a process or constructs an SDK client that **caches
488
+ credentials** beyond a single stream (OpenCode's `opencode serve`
489
+ subprocess, Copilot's `CopilotClient` constructor), then add / remove /
490
+ switch account does NOT take effect until that cached state is rebuilt.
491
+ The fix is the **Restart-Server pattern** documented in §4.2:
492
+
493
+ 1. Add a `*-server-restart` WS event with the standard contract: check
494
+ active streams, return `{ needsConfirmation, activeChats }` when not
495
+ forced; on `force === true`, cancel streams + dispose engine + drop
496
+ any cached subprocess/client; the next `streamQuery` lazy-inits fresh.
497
+ 2. Surface a **"Restart Server"** button in **two** UI places:
498
+ - **Settings → Engines** — visible after add/remove/switch in the
499
+ engines settings panel itself. Confirmation dialog for non-forced.
500
+ - **Chat Input** — visible next to the model/account picker when the
501
+ user has switched account mid-session. Uses `force: true` so the
502
+ send-flow stays inline. See `EngineModelPicker.svelte::ocNeedsRestart`
503
+ for the flag and `restartOCServer` for the handler.
504
+ 3. After a successful restart, refresh the model catalog
505
+ (`modelStore.refreshModels(engineType)`) since model availability can
506
+ depend on credential state.
507
+
508
+ Engines that **do not** need this:
509
+
510
+ - Subprocess-per-turn engines (Claude Code's `query()`, Codex's
511
+ `codex exec`) re-read credentials at every turn — there is nothing
512
+ cached to invalidate.
513
+ - Engines using the auth-blob swap pattern (§9.13) — the swap happens
514
+ inside `accounts-switch`, and the next turn's subprocess picks up the
515
+ new dotfile without a restart event.
516
+
517
+ If you are tempted to add a `*-server-restart` event for an engine that
518
+ spawns a fresh subprocess per turn, you almost certainly want the
519
+ auth-blob swap (§9.13) instead — adding the restart event ships dead
520
+ code and confuses the UX (button that does nothing observable).
521
+
522
+ ### 9.15 Sub-agent (`Task` / `Agent` tool) routing — name, input, parent id
523
+
524
+ Every engine SDK we support exposes a "dispatch sub-agent" tool. Each
525
+ SDK names it differently (Claude → `Task`, OpenCode → `task`, Copilot →
526
+ `task`) and emits the sub-agent's tool calls / messages on the **same
527
+ event stream** as the main turn. Without explicit routing those nested
528
+ messages render as orphan top-level rows in the UI, and the dispatch
529
+ tool itself appears as `Unknown:task`. There are three independent
530
+ fixes — miss any one and the symptom shows up in the UI.
531
+
532
+ **1. Canonicalise the dispatch tool name to `Agent`.** Every adapter
533
+ must map its native name into the unified `Agent` block so the frontend
534
+ tool renderer (`handleAgentTool`) and `subAgentMap` lookups work:
535
+
536
+ ```ts
537
+ // claude/message-converter.ts
538
+ const name = block.name === 'Task' ? 'Agent' : block.name;
539
+
540
+ // opencode + copilot tool-name maps
541
+ 'task': 'Agent',
542
+ ```
543
+
544
+ Then normalise the SDK's raw input fields into `AgentInput { prompt,
545
+ description, subagentType }` (see §9.1). Field names vary —
546
+ `prompt`/`task`/`instruction`, `agent_type`/`subagent_type`/`agent` —
547
+ so the normaliser must accept them all and default `subagentType` to
548
+ `'general-purpose'`.
549
+
550
+ **2. Stamp `parent.toolUseId` on every sub-agent message.** The
551
+ frontend grouper (`message-grouper.ts`) routes messages with
552
+ `parent.toolUseId !== null` into `subAgentMap[parentToolId]` and
553
+ attaches them as `subActivities` on the parent `Agent` tool block.
554
+ Top-level messages must keep `parent.toolUseId = null` (see §9.5);
555
+ sub-agent messages must carry the **parent dispatch tool's** call id.
556
+ Each SDK exposes that linkage differently:
557
+
558
+ | Engine | How the parent id is discovered |
559
+ |----------|------------------------------------------------------------------|
560
+ | Claude | `msg.parent_tool_use_id` is on every nested SDK message |
561
+ | OpenCode | `convertToolUseOnly` / `convertToolResultOnly` / `convertSubtaskToolUseOnly` take a `parentToolUseId` parameter; the caller threads it through when iterating the subtask part |
562
+ | Copilot | `subagent.started` event carries `data.toolCallId` (parent) and `agentId` (child instance). The converter records `agentParentMap[agentId] = data.toolCallId` and `resolveParentToolUseId(event, state)` resolves later events: `data.parentToolCallId` first (deprecated direct hint), else map lookup by `agentId` |
563
+
564
+ The converter functions for assistant messages, reasoning messages and
565
+ `tool.execution_complete` then accept an optional `parentToolUseId` and
566
+ stamp it onto `parent: { ..., toolUseId: parentToolUseId ?? null }`.
567
+ On `subagent.completed` / `subagent.failed`, delete the map entry so
568
+ the next sub-agent dispatch re-registers cleanly.
569
+
570
+ **3. Suppress the SDK's sub-agent streaming deltas.** Some SDKs
571
+ double-emit sub-agent activity: once as live text/reasoning deltas
572
+ inside the main stream, and again as final non-streaming
573
+ `assistant.message` / `assistant.reasoning` / `tool.execution_complete`
574
+ events scoped to the sub-agent. The deltas have no clean parent
575
+ linkage and would leak into the main chat bubble. The fix is to disable
576
+ streaming for sub-agents at the SDK config level so only the final
577
+ bundled events arrive — those carry `agentId` and route correctly via
578
+ step 2 above:
579
+
580
+ ```ts
581
+ // copilot/stream.ts — baseConfig
582
+ includeSubAgentStreamingEvents: false,
583
+ ```
584
+
585
+ If your SDK has no equivalent flag, the fallback is client-side: in the
586
+ event switch, `if (parentToolUseId) break` for any
587
+ `assistant.turn_start` / text-delta / reasoning-delta lifecycle event,
588
+ since those lifecycles belong to the sub-agent and would corrupt the
589
+ main turn's stream state.
590
+
591
+ **Cross-engine consistency.** Once all three fixes are in place, the
592
+ frontend treats the three engines identically: the `Agent` block in the
593
+ main timeline carries `subActivities`, no orphan top-level messages
594
+ appear, and the dispatch tool's name renders as `Agent`. If only step 1
595
+ ships, sub-agent tool calls float to the top of the chat. If only step
596
+ 2 ships, the dispatch tool still says `Unknown:task`. If only step 3 is
597
+ missed (in an SDK that does double-emit), sub-agent text appears in
598
+ both places.
599
+
600
+ ### 9.16 `generateStructured` — schema strictness & part-extraction fallback
601
+
602
+ `generateStructured` powers the AI commit-message generator (and any
603
+ future one-shot JSON callers). Each adapter satisfies the same
604
+ `StructuredGenerationOptions → Promise<T>` contract, but the SDKs split
605
+ sharply on whether they accept a schema natively:
606
+
607
+ | Engine | Strategy | Mechanism |
608
+ |--------------|-----------------|--------------------------------------------------------------|
609
+ | Claude | Native | `outputFormat: { type: 'json_schema', schema }` on `query()` |
610
+ | Codex | Native (strict) | `Thread.run(prompt, { outputSchema })` → `Turn.finalResponse`|
611
+ | OpenCode | Prompt | `client.session.prompt({ tools: {}, … })`, parse text/reasoning parts |
612
+ | Copilot | Prompt | `createSession({ availableTools: [], streaming: false })` + `sendAndWait` |
613
+ | Qwen | Prompt | `query({ coreTools: [], maxSessionTurns: 1 })`, read `SDKResultMessageSuccess.result` |
614
+
615
+ **Two cross-cutting gotchas you will hit.**
616
+
617
+ **1. OpenAI strict mode demands a fully-closed schema.** Codex (via the
618
+ Responses API) rejects any object that omits `additionalProperties:
619
+ false` (`invalid_request_error / invalid_json_schema`) and requires
620
+ every property to appear in `required`. Optional fields must be
621
+ expressed as nullable type unions, not absent from `required`:
622
+
623
+ ```ts
624
+ // backend/ws/git/commit-message.ts — shape that satisfies Codex.
625
+ {
626
+ type: 'object',
627
+ additionalProperties: false,
628
+ required: ['type', 'scope', 'subject', 'body'],
629
+ properties: {
630
+ type: { type: 'string', enum: [...] },
631
+ scope: { type: ['string', 'null'] }, // was just 'string'
632
+ subject: { type: 'string' },
633
+ body: { type: ['string', 'null'] },
634
+ },
635
+ }
636
+ ```
637
+
638
+ This is the **lowest common denominator** — Claude, OpenCode, Copilot,
639
+ and Qwen all accept the same shape, so authoring all
640
+ `generateStructured` schemas to Codex's rules keeps the call site
641
+ engine-agnostic. Don't lift constraints into the adapter; lift the
642
+ schema in the caller.
643
+
644
+ The consumer of the parsed JSON must then handle `null` for any field
645
+ that used to be "absent" — the existing falsy guards in
646
+ `commit-message.ts` (`result.scope ? …`, `result.body ? …`) already do
647
+ that. The corresponding TS type in `shared/types/git.ts` mirrors this
648
+ (`scope: string | null`).
649
+
650
+ **2. Prompt-engineered engines can return empty `text` parts.** OpenCode
651
+ in particular emits `reasoning` parts in addition to `text` parts, and
652
+ on some thinking-heavy models the JSON answer lands in the reasoning
653
+ stream while `text` is empty. The early implementation that filtered
654
+ only `p.type === 'text'` raised "OpenCode returned no text content" in
655
+ that case.
656
+
657
+ Two defences, both in `backend/engine/structured-helpers.ts` and the
658
+ OpenCode adapter:
659
+
660
+ - **Fall back across part types.** `text` first, then `reasoning`.
661
+ Filter out `ignored`/`synthetic` parts so the SDK's own scratch text
662
+ doesn't leak into the JSON parser. Log the part-type breakdown in the
663
+ error message so the next failure is diagnosable.
664
+ - **Extract JSON tolerantly.** `extractJson()` tries, in order: a
665
+ ` ```json ` fenced block, the first balanced `{ … }`, then the raw
666
+ trimmed text. Models routinely ignore the "no markdown fences"
667
+ instruction; the parser should not.
668
+
669
+ The native engines (Claude, Codex) skip these — Claude exposes
670
+ `structured_output` on the `result` message and Codex's
671
+ `Turn.finalResponse` is already the JSON string. They only fall through
672
+ to `extractJson` defensively against the (rare) `finalResponse` arriving
673
+ fenced.
674
+
675
+ **Cancellation.** Every adapter accepts `options.abortController` and
676
+ hands its `signal` to whatever the SDK exposes (Codex
677
+ `TurnOptions.signal`, Claude `Options.abortController`, OpenCode `prompt
678
+ { signal }`, Copilot `session.abort()`, Qwen `QueryOptions.abortController`).
679
+ The contract is the same as `streamQuery`: aborting cancels the in-flight
680
+ request, not just the await.
681
+
682
+ **Engine-not-implemented errors.** `backend/ws/git/commit-message.ts`
683
+ guards on `engine.generateStructured` — if you add an engine that can't
684
+ implement structured output, leave the property `undefined` and the WS
685
+ route will surface `Engine "<name>" does not support structured
686
+ generation` cleanly.
687
+
688
+ ### 9.17 OpenCode SDK v1 vs v2 — events come from the binary, not the npm types
689
+
690
+ `@opencode-ai/sdk` ships **two** API surfaces: the root entry (`.` →
691
+ `dist/index.js`, the **v1** client the adapter uses today) and a separate
692
+ **v2** entry (`@opencode-ai/sdk/v2`). Across the 1.4 → 1.15 jump the v1
693
+ *typed* `Event` union was trimmed — `question.asked`, `message.part.delta`,
694
+ and `permission.asked` no longer appear in `dist/gen/types.gen.d.ts`; the
695
+ typed equivalents (`EventQuestionAsked`, the `session.next*` streaming
696
+ events, etc.) now live only under `dist/v2/`.
697
+
698
+ **This is a typing change, not a protocol change.** The running `opencode
699
+ serve` binary (1.15.x) still emits those legacy events on the v1 `/event`
700
+ SSE stream and still serves `/question`, `/question/{id}/reply`,
701
+ `/permission/{id}/reply` — verify with `curl http://<server>/doc`. The
702
+ adapter casts events to `{ type: string; properties }` (untyped), so it
703
+ keeps receiving them and AskUserQuestion + reasoning streaming keep
704
+ working. **Do not conclude a feature is "removed" from the SDK npm types
705
+ alone — confirm against the binary's OpenAPI doc.**
706
+
707
+ Consequence: the `question.asked` / `message.part.delta` / `permission.asked`
708
+ handlers in `opencode/stream.ts` are correct at runtime but **not**
709
+ type-checked against the SDK (the cast hides them). The future-proofing
710
+ move — should the binary ever drop the legacy v1 stream in favour of
711
+ `session.next*` — is to migrate the adapter onto the typed `@opencode-ai/sdk/v2`
712
+ event protocol. Until then, v1 is intentional.
713
+
714
+ ---
715
+