@myrialabs/clopen 0.4.14 → 0.4.16

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 (130) hide show
  1. package/backend/artifacts/matrix.ts +8 -0
  2. package/backend/artifacts/types.ts +2 -2
  3. package/backend/auth/permissions.ts +16 -0
  4. package/backend/chat/stream-manager.ts +5 -5
  5. package/backend/commands/detect.ts +1 -1
  6. package/backend/commands/sync.ts +1 -1
  7. package/backend/database/migrations/056_support_mssql_driver.ts +137 -0
  8. package/backend/database/migrations/057_seed_pi_provider.ts +25 -0
  9. package/backend/database/migrations/058_seed_cline_provider.ts +25 -0
  10. package/backend/database/migrations/059_seed_cursor_provider.ts +25 -0
  11. package/backend/database/migrations/index.ts +28 -0
  12. package/backend/database/queries/engine-queries.ts +13 -0
  13. package/backend/database/queries/message-queries.ts +43 -1
  14. package/backend/db-client/connection-manager.ts +8 -2
  15. package/backend/db-client/drivers/mssql.ts +829 -0
  16. package/backend/db-client/drivers/mysql.ts +33 -4
  17. package/backend/db-client/drivers/postgres.ts +55 -5
  18. package/backend/db-client/drivers/sql-builders.test.ts +70 -0
  19. package/backend/db-client/drivers/sql-builders.ts +9 -2
  20. package/backend/db-client/pool-config.ts +32 -0
  21. package/backend/db-client/query-executor.test.ts +42 -0
  22. package/backend/db-client/query-executor.ts +47 -3
  23. package/backend/engine/README.md +36 -13
  24. package/backend/engine/adapters/cline/agent-tool.ts +64 -0
  25. package/backend/engine/adapters/cline/ask-question-tool.ts +105 -0
  26. package/backend/engine/adapters/cline/credential.ts +166 -0
  27. package/backend/engine/adapters/cline/error-handler.ts +49 -0
  28. package/backend/engine/adapters/cline/index.ts +1 -0
  29. package/backend/engine/adapters/cline/mcp-tools.ts +119 -0
  30. package/backend/engine/adapters/cline/message-converter.ts +396 -0
  31. package/backend/engine/adapters/cline/models.ts +73 -0
  32. package/backend/engine/adapters/cline/presets.ts +128 -0
  33. package/backend/engine/adapters/cline/stream.ts +413 -0
  34. package/backend/engine/adapters/codex/credential.ts +1 -1
  35. package/backend/engine/adapters/codex/message-converter.ts +4 -4
  36. package/backend/engine/adapters/codex/session-fork.ts +1 -1
  37. package/backend/engine/adapters/codex/stream.ts +3 -3
  38. package/backend/engine/adapters/copilot/stream.ts +1 -1
  39. package/backend/engine/adapters/cursor/ask-question-tool.ts +98 -0
  40. package/backend/engine/adapters/cursor/credential.ts +68 -0
  41. package/backend/engine/adapters/cursor/environment.ts +32 -0
  42. package/backend/engine/adapters/cursor/error-handler.ts +60 -0
  43. package/backend/engine/adapters/cursor/index.ts +1 -0
  44. package/backend/engine/adapters/cursor/message-converter.ts +615 -0
  45. package/backend/engine/adapters/cursor/models.ts +68 -0
  46. package/backend/engine/adapters/cursor/session-fork.ts +68 -0
  47. package/backend/engine/adapters/cursor/stream.ts +341 -0
  48. package/backend/engine/adapters/opencode/config.ts +9 -0
  49. package/backend/engine/adapters/opencode/models.ts +10 -1
  50. package/backend/engine/adapters/opencode/server.ts +110 -2
  51. package/backend/engine/adapters/pi/agent-tool.ts +62 -0
  52. package/backend/engine/adapters/pi/ask-question-tool.ts +93 -0
  53. package/backend/engine/adapters/pi/credential.ts +137 -0
  54. package/backend/engine/adapters/pi/environment.ts +33 -0
  55. package/backend/engine/adapters/pi/error-handler.ts +46 -0
  56. package/backend/engine/adapters/pi/index.ts +1 -0
  57. package/backend/engine/adapters/pi/mcp-tools.ts +131 -0
  58. package/backend/engine/adapters/pi/message-converter.ts +446 -0
  59. package/backend/engine/adapters/pi/models.ts +53 -0
  60. package/backend/engine/adapters/pi/presets.ts +133 -0
  61. package/backend/engine/adapters/pi/session-fork.ts +46 -0
  62. package/backend/engine/adapters/pi/stream.ts +427 -0
  63. package/backend/engine/adapters/qwen/message-converter.ts +5 -5
  64. package/backend/engine/adapters/qwen/stream.ts +2 -2
  65. package/backend/engine/docs/adapter-contract.md +7 -2
  66. package/backend/engine/docs/adding-an-engine.md +70 -12
  67. package/backend/engine/docs/artifacts.md +124 -0
  68. package/backend/engine/docs/database.md +4 -4
  69. package/backend/engine/docs/frontend-and-chat.md +22 -4
  70. package/backend/engine/docs/lessons-learned.md +219 -32
  71. package/backend/engine/docs/quick-reference.md +18 -7
  72. package/backend/engine/docs/websocket-routes.md +2 -2
  73. package/backend/engine/index.ts +9 -0
  74. package/backend/index.ts +6 -0
  75. package/backend/mcp/README.md +3 -3
  76. package/backend/mcp/external/config.ts +11 -0
  77. package/backend/mcp/index.ts +8 -0
  78. package/backend/mcp/internal/config.ts +33 -1
  79. package/backend/permissions/service.ts +5 -2
  80. package/backend/preview/browser/browser-preview-service.ts +15 -6
  81. package/backend/preview/browser/browser-video-capture.ts +232 -100
  82. package/backend/preview/browser/scripts/video-stream.ts +216 -56
  83. package/backend/preview/browser/types.ts +24 -12
  84. package/backend/skills/sync.ts +1 -1
  85. package/backend/subagents/detect.ts +1 -1
  86. package/backend/subagents/sync.ts +1 -1
  87. package/backend/ws/chat/stream.ts +13 -5
  88. package/backend/ws/db-client/connections.ts +2 -1
  89. package/backend/ws/db-client/query.ts +41 -4
  90. package/backend/ws/db-client/schema.ts +45 -1
  91. package/backend/ws/engine/claude/accounts.ts +37 -13
  92. package/backend/ws/engine/cline/accounts.ts +317 -0
  93. package/backend/ws/engine/cline/index.ts +15 -0
  94. package/backend/ws/engine/cline/presets.ts +36 -0
  95. package/backend/ws/engine/cline/status.ts +49 -0
  96. package/backend/ws/engine/codex/accounts.ts +37 -5
  97. package/backend/ws/engine/copilot/accounts.ts +12 -0
  98. package/backend/ws/engine/cursor/accounts.ts +162 -0
  99. package/backend/ws/engine/cursor/index.ts +13 -0
  100. package/backend/ws/engine/cursor/status.ts +55 -0
  101. package/backend/ws/engine/index.ts +6 -0
  102. package/backend/ws/engine/opencode/providers.ts +72 -1
  103. package/backend/ws/engine/pi/accounts.ts +319 -0
  104. package/backend/ws/engine/pi/index.ts +15 -0
  105. package/backend/ws/engine/pi/presets.ts +34 -0
  106. package/backend/ws/engine/pi/status.ts +50 -0
  107. package/backend/ws/engine/qwen/accounts.ts +22 -0
  108. package/backend/ws/messages/crud.ts +13 -0
  109. package/backend/ws/preview/browser/interact.ts +10 -8
  110. package/backend/ws/preview/browser/webcodecs.ts +26 -2
  111. package/backend/ws/sessions/crud.ts +2 -2
  112. package/backend/ws/settings/crud.ts +2 -2
  113. package/dist/assets/{index-CDZf6lfv.js → index-BPvctwJ2.js} +1 -1
  114. package/dist/assets/{index-BWf-DDJN.js → index-vLKZpWQH.js} +1 -1
  115. package/dist/assets/{main-C15mQTCW.js → main-BtBZvCwv.js} +428 -386
  116. package/dist/assets/main-D7ATW8pp.css +1 -0
  117. package/dist/index.html +2 -2
  118. package/package.json +11 -1
  119. package/shared/constants/engine-tools.ts +16 -2
  120. package/shared/constants/engines.ts +27 -0
  121. package/shared/types/db-client/connection.ts +1 -1
  122. package/shared/types/db-client/query.ts +4 -1
  123. package/shared/types/unified/common.ts +1 -1
  124. package/shared/types/unified/engine.ts +82 -1
  125. package/shared/types/unified/index.ts +6 -0
  126. package/shared/types/unified/message.ts +1 -1
  127. package/shared/utils/db-client/split-sql.test.ts +13 -0
  128. package/shared/utils/db-client/split-sql.ts +38 -1
  129. package/shared/utils/subagent-wire-trim.ts +87 -0
  130. package/dist/assets/main-Ba5ZGlY4.css +0 -1
@@ -1,12 +1,12 @@
1
1
  [← Engine adapter guide](../README.md)
2
2
 
3
- ## 9. Lessons learned — pitfalls when authoring a new adapter
3
+ ## 10. Lessons learned — pitfalls when authoring a new adapter
4
4
 
5
5
  These notes come from building the `copilot` adapter. Each item has been
6
6
  gotten wrong at least once — keep this mental checklist in your head when
7
7
  writing the next adapter.
8
8
 
9
- ### 9.1 Both tool name **and** tool input must be canonicalised
9
+ ### 10.1 Both tool name **and** tool input must be canonicalised
10
10
 
11
11
  `toCanonicalToolName()` only guarantees the tool name does not become
12
12
  `Unknown:*`. That is **not enough**: tool UI components (`Bash`, `Read`,
@@ -37,7 +37,7 @@ If only the name mapping is done, the UI still picks the right component
37
37
  but the fields are `undefined` → the user sees an empty block. Always
38
38
  install **both** layers.
39
39
 
40
- ### 9.2 Filter the SDK's "harness tools"
40
+ ### 10.2 Filter the SDK's "harness tools"
41
41
 
42
42
  Some SDKs emit internal tools used for model↔harness coordination that
43
43
  **must not** appear in chat (intent reporting, task-completion markers,
@@ -51,7 +51,7 @@ Strategy: filter at the adapter boundary, do not render `Unknown:*`. See
51
51
  `convertToolComplete`) — if you only drop one side, the UI either gets an
52
52
  orphan result without a tool or an orphan tool without a result.
53
53
 
54
- ### 9.3 One `tool_use` per `AssistantMessage`
54
+ ### 10.3 One `tool_use` per `AssistantMessage`
55
55
 
56
56
  The convention used by Claude and OpenCode: each assistant message that
57
57
  reaches the frontend has **at most one** `tool_use` block. SDKs like
@@ -75,7 +75,7 @@ const messages = blocks.map((block, idx) => ({
75
75
  If violated, the frontend `message-grouper` still works but Compact mode
76
76
  and the tool layout do not stitch correctly.
77
77
 
78
- ### 9.4 Buffer messages until the usage event arrives
78
+ ### 10.4 Buffer messages until the usage event arrives
79
79
 
80
80
  In many SDKs (Copilot included), `assistant.usage` is a **separate** event
81
81
  that arrives **after** `assistant.message` for the same turn iteration.
@@ -110,7 +110,7 @@ The `lastUsage` state is also kept around to build the aggregate
110
110
  `ResultEvent` at `session.idle` — that is the **per-stream** usage, not
111
111
  per-message.
112
112
 
113
- ### 9.5 `tool_use.result: null` is **expected** before render
113
+ ### 10.5 `tool_use.result: null` is **expected** before render
114
114
 
115
115
  When inspecting raw adapter output (e.g. logs or DB rows before render),
116
116
  `tool_use` blocks always carry `result: null`. That is **correct**: the
@@ -146,7 +146,7 @@ Only set `parent.toolUseId` when the message is genuinely a child of an
146
146
  `parentToolUseId` through `convertToolResultOnly`). For raw
147
147
  `tool.execution_complete` events at the top of the loop, leave it null.
148
148
 
149
- ### 9.6 Enable the SDK's streaming flag explicitly
149
+ ### 10.6 Enable the SDK's streaming flag explicitly
150
150
 
151
151
  Some SDKs default to emitting only the final message. For delta/partial
152
152
  streaming you must set the SDK-specific flag:
@@ -160,7 +160,7 @@ Without the flag, the UI shows text "all at once" — the symptom is
160
160
  identical to an adapter that forgot to emit `StreamLifecycleEvent` /
161
161
  `TextDeltaEvent`, so check the flag first before debugging the converter.
162
162
 
163
- ### 9.7 Pair `start`/`stop` lifecycle for reasoning
163
+ ### 10.7 Pair `start`/`stop` lifecycle for reasoning
164
164
 
165
165
  The frontend stream-manager renders reasoning in a separate bubble
166
166
  **only** while `StreamLifecycleEvent { reasoning: true, event: 'start' }`
@@ -169,7 +169,7 @@ begins — the two are mutually exclusive in the UI). See
169
169
  `copilot/message-converter.ts::convertReasoningDelta`, which flushes the
170
170
  text stream before opening the reasoning stream.
171
171
 
172
- ### 9.8 Event-order debug workflow
172
+ ### 10.8 Event-order debug workflow
173
173
 
174
174
  If chat output looks weird, log the raw `SessionEvent` per stream before
175
175
  the converter. The canonical Copilot order is:
@@ -191,7 +191,7 @@ wrong. If you see orphan tool_results, the ignored-tools filter is not
191
191
  consistent on both sides. If text appears all at once, the SDK streaming
192
192
  flag is off.
193
193
 
194
- ### 9.9 Per-stream account override when the SDK takes the credential at construction
194
+ ### 10.9 Per-stream account override when the SDK takes the credential at construction
195
195
 
196
196
  Most SDKs accept env vars per-call (Claude) or read them from the
197
197
  subprocess environment (OpenCode). The Copilot SDK is different: the
@@ -236,7 +236,7 @@ If you forget the per-stream override path, the chat input appears to
236
236
  honour the account picker but the engine actually streams against the
237
237
  last initialised credential — silently using the wrong PAT/quota.
238
238
 
239
- ### 9.10 Fork session — native API vs. on-disk workaround
239
+ ### 10.10 Fork session — native API vs. on-disk workaround
240
240
 
241
241
  The multi-branch checkpoints feature requires that **every** resume
242
242
  spawn a fresh session id, so the engine continues from that point
@@ -251,6 +251,8 @@ resume.
251
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
252
  | Codex | **No native API yet** — fork by copying the rollout JSONL FILE on every resume. |
253
253
  | Qwen Code | **No native API yet** — fork by copying the chat JSONL FILE on every resume. |
254
+ | Pi | `SessionManager.forkFrom()` on the on-disk JSONL tree (in Clopen's isolated sessions dir) — native, on every resume. |
255
+ | Cline | **No session store at all** (stateless `Agent`) — the adapter reconstructs branch history in memory and forks by copy. See "In-process, session-less SDKs" below. |
254
256
 
255
257
  > **Sharp edge — fork is NOT gated on `EngineQueryOptions.forkSession`.**
256
258
  > The `forkSession` field exists on the type but the stream-manager
@@ -274,7 +276,7 @@ the filename, not a directory name:
274
276
  <CODEX_HOME>/sessions/<YYYY>/<MM>/<DD>/rollout-<TIMESTAMP>-<thread_id>.jsonl
275
277
  ```
276
278
 
277
- where `<CODEX_HOME>` is Clopen's isolated `{clopenDir}/engine/codex/user/` (§9.19),
279
+ where `<CODEX_HOME>` is Clopen's isolated `{clopenDir}/engine/codex/user/` (§10.19),
278
280
  **not** `~/.codex` — the helper reads it via `getCodexHomeDir()`, so it
279
281
  tracks the isolated dir automatically.
280
282
 
@@ -297,7 +299,7 @@ project's cwd via the SDK's `sanitizeCwd()`
297
299
  ```
298
300
 
299
301
  where `<QWEN_RUNTIME_DIR>` is Clopen's isolated `{clopenDir}/engine/qwen/user/`
300
- (§9.19), **not** `~/.qwen` — both the env var and the fork helper
302
+ (§10.19), **not** `~/.qwen` — both the env var and the fork helper
301
303
  (`getQwenRuntimeDir()`) resolve to the same base, so they stay in sync.
302
304
 
303
305
  Every record line carries a `sessionId` field equal to the file's
@@ -332,13 +334,46 @@ turn 3 user → assistant sessionId: C (forked from B)
332
334
  Every assistant message carries its **own** session id. Reusing the
333
335
  same id across turns is the symptom that forking is gated or skipped.
334
336
 
337
+ **In-process, session-less SDKs (Cline) — copy-on-branch in memory.**
338
+ Some SDKs expose only a stateless run loop (`@cline/sdk`'s `Agent`) with
339
+ **no** host-owned session store — nothing on disk, nothing keyed by a
340
+ session id. The adapter reconstructs branch history itself, and the fork
341
+ contract is unchanged: **every turn mints a fresh session id and stores its
342
+ resulting transcript under that new id; a resumed turn restores the parent
343
+ id's transcript and NEVER overwrites it.** Because each conversation node
344
+ then owns a unique id, `resume` (= the branch point's `parent.sessionId`,
345
+ derived by the stream-manager) selects exactly one ancestor, so sibling
346
+ forks (A→B→C vs A→B1→C1) stay isolated.
347
+
348
+ ```ts
349
+ // cline/stream.ts — resume path
350
+ const priorMessages = resume ? this.sessions.get(resume) : undefined;
351
+ const sessionId = crypto.randomUUID(); // ALWAYS new — never reuse `resume`
352
+ // … agent.restore(priorMessages) + agent.continue(userMsg), or agent.run() when fresh …
353
+ this.sessions.set(sessionId, [...result.messages]); // store under the NEW id; do NOT mutate the parent entry
354
+ ```
355
+
356
+ The trap that produced the classic checkpoint bug during Cline bring-up:
357
+ keying the transcript by an id that's **reused** across turns
358
+ (`sessionId = resume ?? uuid`, then `sessions.set(resume, …)`) overwrites
359
+ the one shared entry — so after an undo+continue the forked branch restores
360
+ the **sibling** branch's tail and answers with the wrong history. The tell
361
+ is identical to the on-disk case: **every persisted assistant message shares
362
+ one session id.** Bound the map (FIFO) so a long-lived project engine can't
363
+ grow unbounded — evicting an old entry only degrades a *very* old fork to
364
+ "no context", the same graceful fallback as a cross-restart resume (the
365
+ in-memory map is empty after a restart, so `resume` misses and the turn
366
+ starts fresh). This is the one real limitation of the session-less approach,
367
+ and it's unavoidable: adapters **must not** read the message DB themselves
368
+ (§2.5), so cross-restart branch context can't be rebuilt.
369
+
335
370
  When an SDK eventually adds a native `forkSession` (or equivalent), the
336
371
  migration is a one-liner: delete that adapter's `session-fork.ts`, drop
337
372
  the fork block in `stream.ts`, and pass the SDK flag the same way
338
373
  Claude, OpenCode, and Copilot already do. The `// TODO` comment at the
339
374
  top of each `session-fork.ts` pins the migration target.
340
375
 
341
- ### 9.11 Reset `currentAccountId` in `dispose()`
376
+ ### 10.11 Reset `currentAccountId` in `dispose()`
342
377
 
343
378
  Whenever you track per-init state on the engine (e.g.
344
379
  `currentAccountId`, cached models, the SDK client itself), reset every
@@ -358,7 +393,7 @@ async dispose(): Promise<void> {
358
393
  }
359
394
  ```
360
395
 
361
- ### 9.12 Reuse the existing MCP HTTP infrastructure — never build a new bridge
396
+ ### 10.12 Reuse the existing MCP HTTP infrastructure — never build a new bridge
362
397
 
363
398
  `backend/mcp/internal/remote-server.ts` already mounts every server registered via
364
399
  `defineServer()` as a **Streamable HTTP MCP** endpoint at
@@ -452,11 +487,11 @@ What you must NOT do:
452
487
  - ❌ A local type alias when the SDK exports the type (Open Code,
453
488
  Copilot). Import `McpRemoteConfig` / `MCPHTTPServerConfig` directly.
454
489
 
455
- ### 9.13 Auth-blob swap into a shared CLI dotfile (vs. **per-account** isolated dirs)
490
+ ### 10.13 Auth-blob swap into a shared CLI dotfile (vs. **per-account** isolated dirs)
456
491
 
457
492
  > **Scope:** this section is about multiple accounts *within* Clopen. The
458
493
  > orthogonal question — keeping Clopen's whole footprint out of the user's
459
- > global `~/.codex` / `~/.copilot` — is **§9.19**, and there the answer is
494
+ > global `~/.codex` / `~/.copilot` — is **§10.19**, and there the answer is
460
495
  > the opposite: we DO override the home env var, but with **one dir per
461
496
  > engine shared by all accounts**, not one per account.
462
497
 
@@ -474,7 +509,7 @@ isolated home directory and override the CLI's home env var
474
509
  under account A's dir don't reach account B.
475
510
 
476
511
  Instead, all Clopen accounts for an engine share the **single** isolated
477
- home from §9.19, and multi-account is handled by swapping the one dotfile
512
+ home from §10.19, and multi-account is handled by swapping the one dotfile
478
513
  inside it to/from the DB:
479
514
 
480
515
  | Step | Behavior |
@@ -496,7 +531,7 @@ dotfile (Codex's `codex login` does), serialize the login flows with a
496
531
  backend-wide mutex so two simultaneous "Add Account" attempts can't
497
532
  clobber each other.
498
533
 
499
- ### 9.14 Long-lived server engines need a "Restart Server" UX
534
+ ### 10.14 Long-lived server engines need a "Restart Server" UX
500
535
 
501
536
  If your engine boots a process or constructs an SDK client that **caches
502
537
  credentials** beyond a single stream (OpenCode's `opencode serve`
@@ -524,16 +559,16 @@ Engines that **do not** need this:
524
559
  - Subprocess-per-turn engines (Claude Code's `query()`, Codex's
525
560
  `codex exec`) re-read credentials at every turn — there is nothing
526
561
  cached to invalidate.
527
- - Engines using the auth-blob swap pattern (§9.13) — the swap happens
562
+ - Engines using the auth-blob swap pattern (§10.13) — the swap happens
528
563
  inside `accounts-switch`, and the next turn's subprocess picks up the
529
564
  new dotfile without a restart event.
530
565
 
531
566
  If you are tempted to add a `*-server-restart` event for an engine that
532
567
  spawns a fresh subprocess per turn, you almost certainly want the
533
- auth-blob swap (§9.13) instead — adding the restart event ships dead
568
+ auth-blob swap (§10.13) instead — adding the restart event ships dead
534
569
  code and confuses the UX (button that does nothing observable).
535
570
 
536
- ### 9.15 Sub-agent (`Task` / `Agent` tool) routing — name, input, parent id
571
+ ### 10.15 Sub-agent (`Task` / `Agent` tool) routing — name, input, parent id
537
572
 
538
573
  Every engine SDK we support exposes a "dispatch sub-agent" tool. Each
539
574
  SDK names it differently (Claude → `Task`, OpenCode → `task`, Copilot →
@@ -556,7 +591,7 @@ const name = block.name === 'Task' ? 'Agent' : block.name;
556
591
  ```
557
592
 
558
593
  Then normalise the SDK's raw input fields into `AgentInput { prompt,
559
- description, subagentType }` (see §9.1). Field names vary —
594
+ description, subagentType }` (see §10.1). Field names vary —
560
595
  `prompt`/`task`/`instruction`, `agent_type`/`subagent_type`/`agent` —
561
596
  so the normaliser must accept them all and default `subagentType` to
562
597
  `'general-purpose'`.
@@ -565,7 +600,7 @@ so the normaliser must accept them all and default `subagentType` to
565
600
  frontend grouper (`message-grouper.ts`) routes messages with
566
601
  `parent.toolUseId !== null` into `subAgentMap[parentToolId]` and
567
602
  attaches them as `subActivities` on the parent `Agent` tool block.
568
- Top-level messages must keep `parent.toolUseId = null` (see §9.5);
603
+ Top-level messages must keep `parent.toolUseId = null` (see §10.5);
569
604
  sub-agent messages must carry the **parent dispatch tool's** call id.
570
605
  Each SDK exposes that linkage differently:
571
606
 
@@ -611,7 +646,54 @@ ships, sub-agent tool calls float to the top of the chat. If only step
611
646
  missed (in an SDK that does double-emit), sub-agent text appears in
612
647
  both places.
613
648
 
614
- ### 9.16 `generateStructured` — schema strictness & part-extraction fallback
649
+ **Session-less SDKs with no native sub-agent primitive (Pi, Cline) —
650
+ synthesize the `Agent` tool yourself.** The above assumes the SDK *has* a
651
+ `Task`/`Agent` tool that emits nested messages. A bare run loop
652
+ (`@cline/sdk`'s `Agent`, Pi's `AgentSession`) has none — the "Available
653
+ Subagents" preamble is then informational only and the model has nothing
654
+ to call (the exact symptom reported on Cline: *"it never uses subagents"*).
655
+ Expose a synthetic `Agent` tool (`createTool`) whose description lists the
656
+ enabled subagents; its `execute` spawns a **fresh, bounded sub-agent** with
657
+ the chosen subagent's system prompt + the permission-filtered builtins
658
+ **ONLY** (no AskUserQuestion, no MCP, no nested `Agent` — delegation must
659
+ not recurse), runs the delegated prompt to completion, and returns the
660
+ sub-agent's `outputText` as the tool result. Three things to get right —
661
+ each was a separate round-trip during Cline bring-up:
662
+
663
+ 1. **Actually register the tool.** When subagents are enabled, push the
664
+ `Agent` tool into the tools list **and** set
665
+ `toolPolicies.Agent = { autoApprove: true }` (+ include it in the
666
+ `system_init` tool list). Missing this = the model can't delegate
667
+ because the tool isn't there. Skip the whole block when no subagents
668
+ are enabled — there's nothing to dispatch to.
669
+
670
+ 2. **Route sub-activities via a late-bound queue handle.** The dispatch
671
+ `run()` is constructed *before* the stream's `EventQueue` exists, so
672
+ hold a `{ queue: null }` box and set `.queue` right after the queue is
673
+ created. Inside `run()`, subscribe to the sub-agent, convert its
674
+ events with the same message-converter, stamp
675
+ `parent.toolUseId = context.toolCallId` (the parent `Agent` block's id)
676
+ on each message, and push into that queue. The frontend folds them under
677
+ the `Agent` block as `subActivities` (step 2 above). Miss this and
678
+ `subActivities` stays empty even though the delegation ran.
679
+
680
+ 3. **Sub-activities are a tool trail — push tool_use only.**
681
+ `processSubAgentMessages` renders both `tool_use` **and** `text`
682
+ activities, but the convention (Claude/Pi) is tool-only: the sub-agent's
683
+ prose is already the `Agent` tool's *result* (`outputText`). Push only
684
+ assistant messages that contain a `tool_use` block, plus their
685
+ `tool_result` user messages; drop text-only assistants, reasoning, and
686
+ every transient event. Miss this and the sub-agent's narration leaks in
687
+ as `text` sub-activities (the second Cline round-trip).
688
+
689
+ Because the sub-agent is a **separate instance**, its internal steps never
690
+ enter the main agent's transcript — the parent only ever sees the `Agent`
691
+ call + its returned text. So sub-agent work can't contaminate the parent
692
+ conversation, nor a later checkpoint fork of it (§10.10). See
693
+ `cline/agent-tool.ts` + the dispatch block in `cline/stream.ts` (and the
694
+ Pi equivalents) for the reference implementation.
695
+
696
+ ### 10.16 `generateStructured` — schema strictness & part-extraction fallback
615
697
 
616
698
  `generateStructured` powers the AI commit-message generator (and any
617
699
  future one-shot JSON callers). Each adapter satisfies the same
@@ -699,7 +781,7 @@ implement structured output, leave the property `undefined` and the WS
699
781
  route will surface `Engine "<name>" does not support structured
700
782
  generation` cleanly.
701
783
 
702
- ### 9.17 OpenCode SDK v1 vs v2 — events come from the binary, not the npm types
784
+ ### 10.17 OpenCode SDK v1 vs v2 — events come from the binary, not the npm types
703
785
 
704
786
  `@opencode-ai/sdk` ships **two** API surfaces: the root entry (`.` →
705
787
  `dist/index.js`, the **v1** client the adapter uses today) and a separate
@@ -727,9 +809,9 @@ event protocol. Until then, v1 is intentional.
727
809
 
728
810
  ---
729
811
 
730
- ### 9.18 External (registry) MCP servers — proxied through the bridge
812
+ ### 10.18 External (registry) MCP servers — proxied through the bridge
731
813
 
732
- §9.12 covers the **internal** `clopen-mcp` bridge. **External** servers (the
814
+ §10.12 covers the **internal** `clopen-mcp` bridge. **External** servers (the
733
815
  ones users install from the registry, stored in `mcp_servers`) used to be
734
816
  connected **directly** by each engine — a third-party URL or stdio command.
735
817
  That is no longer true: **external servers are now proxied** through a
@@ -759,7 +841,7 @@ What this means for a new adapter:
759
841
  (`getClaude/OpenCode/Codex/Copilot/QwenExternalMcpConfig`); mirror that.
760
842
 
761
843
  2. **Use the engine's real URL/header field** — same per-SDK caveats as the
762
- internal bridge (§9.12), because the shape is identical:
844
+ internal bridge (§10.12), because the shape is identical:
763
845
  - OpenCode: `url` (`type:'remote'`); Claude/Copilot: `url` (`type:'http'`).
764
846
  - Qwen: `httpUrl`.
765
847
  - **Codex: `http_headers`** (a TOML table) — **not** `bearer_token`, which is
@@ -791,7 +873,7 @@ What you must NOT do:
791
873
 
792
874
  ---
793
875
 
794
- ### 9.19 Per-engine config-dir isolation (`{clopenDir}/engine/{engine}/user/`)
876
+ ### 10.19 Per-engine config-dir isolation (`{clopenDir}/engine/{engine}/user/`)
795
877
 
796
878
  Every engine's CLI/SDK writes runtime state (credentials, session/rollout
797
879
  files, logs, caches) to a home dir. Left at the default, that dir is the
@@ -828,7 +910,7 @@ Sharp edges, each of which silently defeats isolation if missed:
828
910
  `session-fork.ts` reads `getCodexHomeDir()` and Qwen's reads
829
911
  `getQwenRuntimeDir()` — both resolve to the same isolated base the env
830
912
  var sets. If they drift, `sessionStateExists()` returns false and
831
- multi-branch checkpoints break (see §9.10).
913
+ multi-branch checkpoints break (see §10.10).
832
914
  - **Qwen isolation is partial — and that's accepted.** `QWEN_RUNTIME_DIR`
833
915
  relocates runtime output (chats/sessions, history, logs, tmp) but the
834
916
  CLI's global `settings.json` / OAuth creds still resolve to `~/.qwen`
@@ -854,7 +936,7 @@ Sharp edges, each of which silently defeats isolation if missed:
854
936
  XDG fine; a stale reused server was the culprit. Symptom to watch for: data
855
937
  still landing in `~/.local/share/opencode` after the env looks right.
856
938
 
857
- **This is orthogonal to multi-account (§9.13).** All of an engine's Clopen
939
+ **This is orthogonal to multi-account (§10.13).** All of an engine's Clopen
858
940
  accounts share this **one** isolated dir; multiple accounts inside it are
859
941
  still the auth-blob swap, **not** a dir per account.
860
942
 
@@ -878,3 +960,108 @@ still the auth-blob swap, **not** a dir per account.
878
960
  the persisted `opencode.server.{url,datadir}` so a server cached against the
879
961
  pre-move dir is re-spawned into the relocated one.
880
962
 
963
+ ---
964
+
965
+ ### 10.20 In-process SDK with a delta-stream, wrapped tools & no metadata (Cursor)
966
+
967
+ The `cursor` adapter (`@cursor/sdk`) surfaced a whole class of gotchas that recur
968
+ for any SDK whose stream is **delta-based**, whose tools are **wrapped/renamed**,
969
+ and whose model catalog is **metadata-poor**. Every point below cost a round-trip
970
+ of "user reports wrong UI → capture the real runtime shape → fix". **The meta-lesson:
971
+ never guess an SDK's runtime shapes from its `.d.ts`; capture them live** (write a
972
+ throwaway script that runs a real agent and `JSON.stringify`s each event/arg/result),
973
+ using the **same model** the user runs — different models stream differently.
974
+
975
+ **A. `run.stream()` yields per-chunk DELTAS, not snapshots.** Cursor emits a
976
+ separate `assistant`/`thinking` SDKMessage for *each* text chunk. Persisting each
977
+ as its own message produced 121 one-word rows for a "1+1=" reply and pushed the
978
+ user message off-screen. Fix: **accumulate** chunks into ONE `reasoning` + ONE
979
+ `assistant` message per block (buffers + flush at block-switch / tool-call /
980
+ turn-end), while emitting each chunk live as a transient `stream_event` delta.
981
+ Don't double-source: pick either `run.stream()` OR `onDelta`, not both, for the
982
+ same content. (§10.4 is the sibling "buffer for usage" lesson.)
983
+
984
+ **B. Tool arg field names are NOT what the `.d.ts` implies — and some payloads
985
+ live in the RESULT, not the args.** Cursor `edit` args carry only `{path}`; the
986
+ before/after is in the result's `value.diffString` (parse the unified diff into
987
+ `oldString`/`newString`). `glob`→`{globPattern}`, `write`→`{fileText}` (not
988
+ `content`). Getting these wrong = empty tool inputs in the UI. **Capture real args
989
+ at runtime.** When the payload arrives only at completion, DEFER that tool's
990
+ `tool_use` emission to the terminal event (like `edit`, `create_plan`).
991
+
992
+ **C. MCP servers AND in-process custom tools may be delivered through ONE wrapper
993
+ tool.** Cursor routes both through a tool literally named `mcp`, args
994
+ `{providerIdentifier, toolName, args}` (`clopen-mcp` for real MCP,
995
+ `custom-user-tools` for `local.customTools`). Unwrap it: `resolveOpenCodeToolName(toolName)`
996
+ → `mcp__server__tool` (passthrough args) for real MCP, else `toCanonicalToolName(toolName)`
997
+ + normalise for custom (e.g. AskUserQuestion). Without unwrap everything renders
998
+ as `Unknown:mcp`.
999
+
1000
+ **D. Interactive tool (AskUserQuestion) args must come from the tool's `execute`,
1001
+ not the stream.** The stream's `tool_call` args can arrive empty/partial for large
1002
+ inputs (→ `questions:[]`). The custom-tool `execute` always receives complete
1003
+ args, so emit the tool_use FROM `execute` (with the full questions) through a push
1004
+ queue that merges with `run.stream()`, and have the converter SKIP the stream's
1005
+ copy. `context.toolCallId` === the `tool_call` `call_id`, so `resolveUserAnswer`
1006
+ still matches, and the `running` event fires while `execute` blocks (dialog shows
1007
+ live, no deadlock). See §10.15 for the parent-routing half.
1008
+
1009
+ **E. Sub-agent activity may be nowhere in `run.stream()`.** Cursor runs the
1010
+ `task` sub-agent internally: its steps ride `onDelta` `tool-call-delta` events
1011
+ whose `taskUpdate` field is the sub-agent's inner InteractionUpdate; the outer
1012
+ `callId` === the `task` `call_id` === the Agent tool_use id. Stream each
1013
+ `taskUpdate.type==='tool-call-completed'` as a child tool_use+tool_result
1014
+ (`parent.toolUseId`), and keep the full transcript in the `task` RESULT
1015
+ (`value.conversationSteps[]`) as a FALLBACK. `subagentType` can be an OBJECT
1016
+ (`{kind,name}`) — extract the string, or the UI shows "Using [object Object] agent".
1017
+ Make the synthesised Agent tool's `description` param **required** (Pi/Cline) so
1018
+ the model fills it; and in `AgentTool.svelte`, hide the description line when empty.
1019
+
1020
+ **F. Some capabilities emit NO tool event at all.** Cursor's web search / web
1021
+ fetch run server-side — no `tool_call` in `run.stream()` or `onDelta`. They simply
1022
+ cannot be rendered as tools. Enumerate the SDK's real tool-type set before
1023
+ assuming a tool is "missing".
1024
+
1025
+ **G. Tool RESULT shapes vary and may hide huge binaries.** Cursor wraps results as
1026
+ `{status, value:{content:[{text:{text}}]}}` (top-level) or `{success:{content}}`
1027
+ (sub-agent); images arrive as raw `Buffer` bytes. `extractResultText` must unwrap
1028
+ `value`/`success`, handle the nested `{text:{text}}` shape, and map images to a
1029
+ `[image]` placeholder (else you serialise a 500 KB PNG buffer into the row).
1030
+
1031
+ **H. Mutable arg references corrupt persisted snapshots.** Cursor mutates some arg
1032
+ objects in place across a tool's lifecycle (notably `update_todos` — statuses flip
1033
+ to completed as work proceeds). Persisting a live reference makes a just-created
1034
+ todo render as done. **`structuredClone` the args at emit time.** Also map the
1035
+ SDK's status enum to the unified one (`inProgress`→`in_progress`, `cancelled`→
1036
+ `completed`) — a value mismatch renders in-progress as pending.
1037
+
1038
+ **I. Usage that arrives once per turn needs backfill.** Cursor (like Codex) emits
1039
+ `usage` once after all messages, so assistant rows persist `usage:null`. Add the
1040
+ engine to `stream-manager.ts::backfillUsageForStream`'s gate so the turn's
1041
+ aggregate is written to every assistant row (survives refresh).
1042
+
1043
+ **J. Don't fabricate a context window.** If `models.list()` reports no max context
1044
+ (`limit.input:0`), do NOT hard-code one. `getContextUsage` returns `unknown:true`
1045
+ and `ContextIndicator.svelte` shows "?" + an explanation instead of a bogus 100%.
1046
+
1047
+ **K. A "plan" tool is a user-facing checkpoint, not internal plumbing.** Cursor's
1048
+ `create_plan` proposes a plan for the user to read, then ENDS the turn (approval
1049
+ gate, like Claude's ExitPlanMode). Render its `plan` text as a normal assistant
1050
+ markdown message, not a tool card; the user replies to continue.
1051
+
1052
+ **L. Runtime compatibility is a first-class risk (Bun).** `@cursor/sdk` uses
1053
+ `@connectrpc/connect` over a Node transport that works under Bun with a valid
1054
+ **paid** key. A free-tier/exhausted key returns `plan_required` (403) and
1055
+ rate-limited keys surface as "socket connection closed / API key exchange
1056
+ endpoint" NetworkErrors — do NOT misread these as a Bun incompatibility. The SDK's
1057
+ fetch transport is gated behind a `globalThis.Deno` check; **faking that global is
1058
+ UNSAFE** — 45+ files (`@anthropic-ai/sdk`, `openai`, `elysia`, `mongodb`,
1059
+ `@google/genai`) platform-detect on `Deno` and would break. Map `plan_required`
1060
+ and socket errors to clear user messages in `error-handler.ts`.
1061
+
1062
+ > **Global fixes that came out of this** (apply to ALL engines, not just Cursor):
1063
+ > the List tool renders its directory listing with `CodeBlock` (monospace), not
1064
+ > `TextMessage` (markdown); `AgentTool.svelte` hides an empty description line;
1065
+ > `ContextIndicator.svelte` handles an unknown max context. When an engine's data
1066
+ > exposes a UI bug, fix it in the shared component, not the adapter.
1067
+
@@ -1,6 +1,6 @@
1
1
  [← Engine adapter guide](../README.md)
2
2
 
3
- ## 10. Quick reference table
3
+ ## 11. Quick reference table
4
4
 
5
5
  | Need | File |
6
6
  |---------------------------------------------|-----------------------------------------------------------|
@@ -11,22 +11,33 @@
11
11
  | Stateful per-stream converter | `claude/message-converter.ts::createSdkMessageConverter` |
12
12
  | Split one SDK message → N `EngineOutput` | `opencode/message-converter.ts::convertAssistantMessages`, `copilot/message-converter.ts::convertAssistantMessage` |
13
13
  | Buffer until usage event arrives | `copilot/message-converter.ts::flushPending` + `captureUsage` |
14
+ | Accumulate per-chunk delta stream → 1 msg | `cursor/message-converter.ts` (`appendText`/`appendReasoning`/`flushAll` — deltas, not snapshots; see §10.20-A) |
15
+ | Unwrap a wrapper tool (MCP + custom tools) | `cursor/message-converter.ts::canonicalCursorTool`/`cursorToolInput` (`mcp` wrapper → `mcp__server__tool` / AskUserQuestion; §10.20-C) |
16
+ | Interactive tool args from `execute`, not stream | `cursor/ask-question-tool.ts` (`emit`) + `cursor/message-converter.ts::emitAskUserQuestion` (push queue; §10.20-D) |
17
+ | Sub-agent streamed live via delta taskUpdate | `cursor/stream.ts` (`onDelta` `tool-call-delta.taskUpdate`) + `cursor/message-converter.ts::emitSubagentActivity`/`replaySubagent` (§10.20-E) |
18
+ | Freeze mutable tool args before persist | `cursor/message-converter.ts::cloneArgs` (`structuredClone`; §10.20-H) |
19
+ | Usage backfill (once-per-turn engines) | `backend/chat/stream-manager.ts::backfillUsageForStream` (Codex + Cursor; §10.20-I) |
20
+ | Context window unknown → "?" not 100% | `frontend/utils/context-manager.ts` (`unknown`) + `frontend/components/chat/widgets/ContextIndicator.svelte` (§10.20-J) |
14
21
  | Reasoning stream lifecycle | `opencode/stream.ts::flushReasoning`, `copilot/message-converter.ts::convertReasoningDelta` |
15
22
  | Cancel-before-RPC ordering | `opencode/stream.ts::cancel`, `claude/stream.ts::cancel`, `copilot/stream.ts::cancel` |
16
- | Fork session (native vs. on-disk workaround) | `claude/stream.ts` (`forkSession: true`), `opencode/stream.ts` (`client.session.fork`), `copilot/stream.ts` (`client.rpc.sessions.fork`), `codex/session-fork.ts` + `qwen/session-fork.ts` (copy disk state) |
17
- | Sub-agent (`Task`/`Agent`) routing | `claude/message-converter.ts` (`parent_tool_use_id`), `opencode/message-converter.ts::convertSubtaskToolUseOnly`, `copilot/message-converter.ts::resolveParentToolUseId` + `agentParentMap` (see §9.15) |
23
+ | Fork session (native vs. on-disk vs. in-memory) | `claude/stream.ts` (`forkSession: true`), `opencode/stream.ts` (`client.session.fork`), `copilot/stream.ts` (`client.rpc.sessions.fork`), `codex/session-fork.ts` + `qwen/session-fork.ts` (copy disk state), `pi/session-fork.ts` (`SessionManager.forkFrom`), `cline/stream.ts` (**session-less** — fresh id per turn + in-memory copy-on-branch; see §10.10) |
24
+ | Sub-agent (`Task`/`Agent`) routing | `claude/message-converter.ts` (`parent_tool_use_id`), `opencode/message-converter.ts::convertSubtaskToolUseOnly`, `copilot/message-converter.ts::resolveParentToolUseId` + `agentParentMap`; **synthesized** `Agent` tool for bare-loop SDKs in `cline/agent-tool.ts` + `pi/agent-tool.ts` (see §10.15) |
18
25
  | AskUserQuestion event + HTTP fallback | `opencode/stream.ts::resolveUserAnswer`, `claude/stream.ts::canUseTool` |
19
26
  | MCP servers exposed over HTTP (single source) | `backend/mcp/internal/remote-server.ts`, `backend/mcp/internal/config.ts::getOpenCodeMcpConfig` (and future `getXxxMcpConfig`) |
20
- | Auth-blob swap into shared CLI dotfile | Pattern only (no implementation yet); see §3.3 callout + §9.13 |
21
- | Restart-Server pattern (long-lived engines) | `backend/ws/engine/opencode/providers.ts::engine:opencode-server-restart`, `frontend/components/chat/input/components/EngineModelPicker.svelte::restartOCServer`, `AIEnginesSettings.svelte::handleRestartServer`/`forceRestartServer` |
22
- | `generateStructured` (no tools, JSON) | `claude/stream.ts::generateStructured` (native `outputFormat`), `codex/stream.ts::generateStructured` (native `outputSchema`), `opencode/stream.ts::generateStructured` + `copilot/stream.ts::generateStructured` + `qwen/stream.ts::generateStructured` (prompt-engineered via `backend/engine/structured-helpers.ts`). See §9.16 for the strict-schema + part-fallback gotchas. |
27
+ | Materialize an artifact per engine (matrix) | `backend/artifacts/matrix.ts::resolveArtifact`, generic writer `backend/artifacts/sync.ts`, scanner `backend/artifacts/detect.ts` (see §8.2) |
28
+ | Per-stream artifact sync (Commands/Subagents/Instructions) | `backend/engine/artifact-sync.ts::syncEngineArtifacts` + `buildArtifactsPromptContext` — called from each `stream.ts` after `syncSkills` (see §8.3) |
29
+ | Profile scoping (narrow active artifacts) | `backend/profiles/service.ts::resolveActiveProfileId` + `artifactFilter` (see §8.4) |
30
+ | Permission enforcement (runtime hook) | `backend/permissions/service.ts::resolvePermissionsFromDb` + `isToolAllowed` (see §8.4) |
31
+ | Auth-blob swap into shared CLI dotfile | Pattern only (no implementation yet); see §3.3 callout + §10.13 |
32
+ | Restart-Server pattern (long-lived engines) | `backend/ws/engine/opencode/providers.ts::engine:opencode-server-restart`, `frontend/components/chat/input/components/EngineModelPicker.svelte::restartOCServer`, `engines/panels/OpenCodePanel.svelte::handleRestartServer`/`forceRestartServer` |
33
+ | `generateStructured` (no tools, JSON) | `claude/stream.ts::generateStructured` (native `outputFormat`), `codex/stream.ts::generateStructured` (native `outputSchema`), `opencode/stream.ts::generateStructured` + `copilot/stream.ts::generateStructured` + `qwen/stream.ts::generateStructured` (prompt-engineered via `backend/engine/structured-helpers.ts`). See §10.16 for the strict-schema + part-fallback gotchas. |
23
34
  | Error normalisation | `claude/error-handler.ts`, `copilot/error-handler.ts`, `opencode/error-handler.ts`, `qwen/error-handler.ts`, `codex/error-handler.ts` |
24
35
  | DB provider/account access | `backend/database/queries/engine-queries.ts` |
25
36
  | Per-platform install recipe | `backend/engine/install-recipes.ts` |
26
37
  | Streaming install logs | `backend/engine/install-runner.ts` |
27
38
  | Frontend account/provider stores | `frontend/stores/features/{claude-accounts,copilot-accounts,opencode-providers}.svelte.ts` |
28
39
  | Frontend chat-model state | `frontend/stores/ui/chat-model.svelte.ts` |
29
- | Settings UI (Engines) | `frontend/components/settings/engines/AIEnginesSettings.svelte` |
40
+ | Settings UI (Engines) | `frontend/components/settings/engines/AIEnginesSettings.svelte` (shell + grid) + `engines/panels/*Panel.svelte` (one per engine) |
30
41
  | Settings UI (System Tools) | `frontend/components/settings/system-tools/{SystemToolsSettings,ToolInstallCard}.svelte` |
31
42
  | Chat picker (engine + model + account) | `frontend/components/chat/input/components/EngineModelPicker.svelte` |
32
43
  | Chat send → backend | `frontend/services/chat/chat.service.ts` (`ws.emit('chat:stream', …)`), `backend/ws/chat/stream.ts` |
@@ -77,7 +77,7 @@ a `*-server-restart` event; the UI surfaces this to the user as a
77
77
 
78
78
  1. **Settings → Engines** card — shown whenever the user has just changed
79
79
  provider/account state (add / remove / switch). See
80
- `AIEnginesSettings.svelte::handleRestartServer` (with the
80
+ `engines/panels/OpenCodePanel.svelte::handleRestartServer` (with the
81
81
  `needsConfirmation` confirm-dialog flow) and
82
82
  `forceRestartServer`.
83
83
  2. **Chat Input → next to the model/account picker** — shown when the
@@ -104,7 +104,7 @@ change with the credential.
104
104
  `query()`), the credential is re-read at every turn and there is nothing
105
105
  to "restart". Such engines do not implement `*-server-restart`. The
106
106
  appropriate analog for shared-CLI-dotfile engines like Codex is the
107
- auth-blob swap (§9.13) — performed inside `accounts-switch`, not via a
107
+ auth-blob swap (§10.13) — performed inside `accounts-switch`, not via a
108
108
  separate restart event.
109
109
 
110
110
  ### 4.3 Copilot — `engine:copilot-*`
@@ -20,6 +20,9 @@ import { OpenCodeEngine, disposeOpenCodeClient } from './adapters/opencode';
20
20
  import { CopilotEngine } from './adapters/copilot';
21
21
  import { CodexEngine } from './adapters/codex';
22
22
  import { QwenEngine } from './adapters/qwen';
23
+ import { PiEngine } from './adapters/pi';
24
+ import { ClineEngine } from './adapters/cline';
25
+ import { CursorEngine } from './adapters/cursor';
23
26
  import { debug } from '$shared/utils/logger';
24
27
 
25
28
  // ============================================================================
@@ -38,6 +41,12 @@ function createEngine(type: EngineType): AIEngine {
38
41
  return new CodexEngine();
39
42
  case 'qwen':
40
43
  return new QwenEngine();
44
+ case 'pi':
45
+ return new PiEngine();
46
+ case 'cline':
47
+ return new ClineEngine();
48
+ case 'cursor':
49
+ return new CursorEngine();
41
50
  default:
42
51
  throw new Error(`Unknown engine type: ${type}`);
43
52
  }
package/backend/index.ts CHANGED
@@ -25,6 +25,7 @@ import { loggerMiddleware } from './middleware/logger';
25
25
  import { initializeDatabase, closeDatabase } from './database';
26
26
  import { syncInternalServers } from './mcp';
27
27
  import { disposeAllEngines } from './engine';
28
+ import { connectionManager } from './db-client/connection-manager';
28
29
  import { refreshProcessPath } from './utils/path-enrich';
29
30
  import { debug } from '$shared/utils/logger';
30
31
  import { networkInterfaces } from 'os';
@@ -260,6 +261,11 @@ async function gracefulShutdown() {
260
261
  try {
261
262
  // Stop accepting new connections first — release the port ASAP
262
263
  app.stop();
264
+ // Release DB Client pools up front so remote server sessions are freed
265
+ // immediately on restart (dev `bun --watch`), before the slower engine
266
+ // and browser teardown below — otherwise the old process keeps those
267
+ // sockets open long enough to overlap the new process ("too many clients").
268
+ await connectionManager.closeAll();
263
269
  // Dispose rate limiter timer
264
270
  authRateLimiter.dispose();
265
271
  // Dispose expired session cleanup timer
@@ -633,7 +633,7 @@ getCopilotMcpConfig();
633
633
 
634
634
  When adding a new engine that consumes streamable-HTTP MCP, add a sibling
635
635
  `getXxxMcpConfig()` here — do **not** introduce a new HTTP listener or a
636
- new namespace key. See `backend/engine/README.md` §9.12 for the full
636
+ new namespace key. See `backend/engine/README.md` §10.12 for the full
637
637
  checklist (variable naming, type imports, auto-approval surface, etc.).
638
638
 
639
639
  ### Helper Functions
@@ -1195,7 +1195,7 @@ automatically available to **every** engine:
1195
1195
  ### Adding a New Engine
1196
1196
 
1197
1197
  If your engine's CLI/SDK accepts a streamable-HTTP MCP URL, follow the
1198
- checklist in `backend/engine/README.md` §9.12. The summary:
1198
+ checklist in `backend/engine/README.md` §10.12. The summary:
1199
1199
 
1200
1200
  1. Add a sibling `getXxxMcpConfig()` next to the existing helpers in
1201
1201
  `config.ts`. Reuse the `'clopen-mcp'` namespace key. Use the SDK's
@@ -1215,7 +1215,7 @@ checklist in `backend/engine/README.md` §9.12. The summary:
1215
1215
  credential handling (the proxy injects it). Codex still uses
1216
1216
  `http_headers`, **not** `bearer_token`. See
1217
1217
  [External Servers, OAuth & Connection Status](#external-servers-oauth--connection-status)
1218
- and `backend/engine/docs/lessons-learned.md` §9.18.
1218
+ and `backend/engine/docs/lessons-learned.md` §10.18.
1219
1219
 
1220
1220
  ### File Locations
1221
1221
 
@@ -23,6 +23,7 @@ import type { McpServerConfig } from '@anthropic-ai/claude-agent-sdk';
23
23
  import type { McpRemoteConfig } from '@opencode-ai/sdk';
24
24
  import type { MCPHTTPServerConfig as CopilotMcpServerConfig } from '@github/copilot-sdk';
25
25
  import type { CLIMcpServerConfig as QwenMcpServerConfig } from '@qwen-code/sdk';
26
+ import type { McpServerConfig as CursorMcpServerConfig } from '@cursor/sdk';
26
27
  import { debug } from '$shared/utils/logger';
27
28
  import { mcpServerQueries } from '$backend/database/queries';
28
29
  import { externalNamespace, MCP_TOOL_CALL_TIMEOUT_MS } from '../shared/constants';
@@ -208,6 +209,16 @@ export function getCopilotExternalMcpConfig(profileFilter?: Set<string>): Record
208
209
  }
209
210
 
210
211
  /** Qwen Code: `CLIMcpServerConfig` Streamable-HTTP (`httpUrl`) at the bridge proxy. */
212
+ /** Cursor: `McpServerConfig` (http variant) pointing at the bridge proxy. */
213
+ export function getCursorExternalMcpConfig(profileFilter?: Set<string>): Record<string, CursorMcpServerConfig> {
214
+ const out: Record<string, CursorMcpServerConfig> = {};
215
+ for (const s of getEnabledExternalServers(profileFilter)) {
216
+ out[s.namespace] = { type: 'http', url: bridgeUrl(s.slug, 'cursor'), headers: serviceAuthHeaders() };
217
+ }
218
+ logBuilt('Cursor', out);
219
+ return out;
220
+ }
221
+
211
222
  export function getQwenExternalMcpConfig(profileFilter?: Set<string>): Record<string, QwenMcpServerConfig> {
212
223
  const out: Record<string, QwenMcpServerConfig> = {};
213
224
  for (const s of getEnabledExternalServers(profileFilter)) {