@myrialabs/clopen 0.3.7 → 0.3.9
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/backend/auth/permissions.ts +41 -2
- package/backend/chat/stream-manager.ts +71 -0
- package/backend/database/migrations/030_add_files_panel_state_to_user_projects.ts +34 -0
- package/backend/database/migrations/031_create_db_client_tables.ts +74 -0
- package/backend/database/migrations/032_seed_copilot_provider.ts +19 -0
- package/backend/database/migrations/033_seed_codex_provider.ts +19 -0
- package/backend/database/migrations/034_seed_qwen_provider.ts +119 -0
- package/backend/database/migrations/035_add_owner_to_db_client_connections.ts +34 -0
- package/backend/database/migrations/index.ts +43 -1
- package/backend/database/queries/db-client-connection-queries.ts +343 -0
- package/backend/database/queries/db-client-query-history-queries.ts +113 -0
- package/backend/database/queries/engine-queries.ts +12 -0
- package/backend/database/queries/index.ts +3 -1
- package/backend/database/queries/project-queries.ts +28 -0
- package/backend/db-client/connection-manager.ts +257 -0
- package/backend/db-client/drivers/bun-sql-helpers.ts +41 -0
- package/backend/db-client/drivers/mongodb.ts +358 -0
- package/backend/db-client/drivers/mysql.ts +385 -0
- package/backend/db-client/drivers/postgres.ts +446 -0
- package/backend/db-client/drivers/redis.ts +267 -0
- package/backend/db-client/drivers/sql-builders.ts +215 -0
- package/backend/db-client/drivers/sqlite.ts +346 -0
- package/backend/db-client/drivers/types.ts +92 -0
- package/backend/db-client/query-executor.ts +126 -0
- package/backend/db-client/ssh-tunnel.ts +122 -0
- package/backend/engine/README.md +1702 -0
- package/backend/engine/adapters/claude/models.ts +141 -0
- package/backend/engine/adapters/claude/stream.ts +1 -1
- package/backend/engine/adapters/codex/credential.ts +179 -0
- package/backend/engine/adapters/codex/error-handler.ts +65 -0
- package/backend/engine/adapters/codex/index.ts +1 -0
- package/backend/engine/adapters/codex/message-converter.ts +646 -0
- package/backend/engine/adapters/codex/models.ts +105 -0
- package/backend/engine/adapters/codex/patch-rollout.ts +169 -0
- package/backend/engine/adapters/codex/session-fork.ts +149 -0
- package/backend/engine/adapters/codex/stream.ts +310 -0
- package/backend/engine/adapters/codex/usage-rollout.ts +145 -0
- package/backend/engine/adapters/copilot/error-handler.ts +94 -0
- package/backend/engine/adapters/copilot/index.ts +1 -0
- package/backend/engine/adapters/copilot/message-converter.ts +973 -0
- package/backend/engine/adapters/copilot/models.ts +92 -0
- package/backend/engine/adapters/copilot/session-fork.ts +111 -0
- package/backend/engine/adapters/copilot/stream.ts +573 -0
- package/backend/engine/adapters/opencode/config.ts +56 -104
- package/backend/engine/adapters/opencode/error-handler.ts +71 -0
- package/backend/engine/adapters/opencode/models.ts +79 -0
- package/backend/engine/adapters/opencode/presets.ts +91 -0
- package/backend/engine/adapters/opencode/stream.ts +5 -115
- package/backend/engine/adapters/qwen/credential.ts +78 -0
- package/backend/engine/adapters/qwen/environment.ts +84 -0
- package/backend/engine/adapters/qwen/error-handler.ts +71 -0
- package/backend/engine/adapters/qwen/index.ts +1 -0
- package/backend/engine/adapters/qwen/message-converter.ts +1055 -0
- package/backend/engine/adapters/qwen/models.ts +81 -0
- package/backend/engine/adapters/qwen/presets.ts +51 -0
- package/backend/engine/adapters/qwen/session-fork.ts +97 -0
- package/backend/engine/adapters/qwen/stream.ts +380 -0
- package/backend/engine/index.ts +35 -0
- package/backend/engine/install-recipes.ts +80 -1
- package/backend/engine/install-runner.ts +4 -0
- package/backend/git/git-service.ts +12 -0
- package/backend/mcp/README.md +84 -14
- package/backend/mcp/config.ts +218 -17
- package/backend/mcp/index.ts +2 -0
- package/backend/mcp/project-context.ts +55 -0
- package/backend/mcp/servers/browser-automation/actions.ts +6 -1
- package/backend/mcp/servers/helper.ts +13 -0
- package/backend/middleware/error-handler.ts +16 -2
- package/backend/preview/browser/browser-preview-service.ts +4 -4
- package/backend/preview/browser/scripts/video-stream.ts +9 -3
- package/backend/ws/README.md +128 -3
- package/backend/ws/access.ts +56 -0
- package/backend/ws/chat/stream.ts +36 -12
- package/backend/ws/db-client/access.ts +19 -0
- package/backend/ws/db-client/connections.ts +194 -0
- package/backend/ws/db-client/index.ts +17 -0
- package/backend/ws/db-client/io.ts +456 -0
- package/backend/ws/db-client/query.ts +214 -0
- package/backend/ws/db-client/schema.ts +81 -0
- package/backend/ws/db-client/structure.ts +230 -0
- package/backend/ws/engine/access.ts +39 -0
- package/backend/ws/engine/claude/accounts.ts +15 -10
- package/backend/ws/engine/codex/accounts.ts +516 -0
- package/backend/ws/engine/codex/index.ts +14 -0
- package/backend/ws/engine/codex/status.ts +87 -0
- package/backend/ws/engine/copilot/accounts.ts +122 -0
- package/backend/ws/engine/copilot/index.ts +13 -0
- package/backend/ws/engine/copilot/status.ts +54 -0
- package/backend/ws/engine/index.ts +7 -1
- package/backend/ws/engine/opencode/providers.ts +1 -1
- package/backend/ws/engine/qwen/accounts.ts +137 -0
- package/backend/ws/engine/qwen/index.ts +15 -0
- package/backend/ws/engine/qwen/presets.ts +40 -0
- package/backend/ws/engine/qwen/status.ts +54 -0
- package/backend/ws/files/index.ts +5 -1
- package/backend/ws/files/read.ts +34 -0
- package/backend/ws/files/state.ts +42 -0
- package/backend/ws/files/watch.ts +7 -1
- package/backend/ws/git/branch.ts +13 -19
- package/backend/ws/git/commit-message.ts +3 -4
- package/backend/ws/git/commit.ts +5 -7
- package/backend/ws/git/conflict.ts +7 -10
- package/backend/ws/git/diff.ts +7 -10
- package/backend/ws/git/log.ts +3 -4
- package/backend/ws/git/remote.ts +30 -43
- package/backend/ws/git/staging.ts +13 -19
- package/backend/ws/git/status.ts +7 -11
- package/backend/ws/index.ts +5 -1
- package/backend/ws/messages/crud.ts +7 -13
- package/backend/ws/preview/access.ts +45 -0
- package/backend/ws/preview/browser/cleanup.ts +3 -11
- package/backend/ws/preview/browser/console.ts +5 -40
- package/backend/ws/preview/browser/interact.ts +2 -6
- package/backend/ws/preview/browser/native-ui.ts +5 -18
- package/backend/ws/preview/browser/stats.ts +2 -12
- package/backend/ws/preview/browser/tab-info.ts +4 -20
- package/backend/ws/preview/browser/tab.ts +4 -27
- package/backend/ws/preview/browser/webcodecs.ts +6 -47
- package/backend/ws/projects/crud.ts +4 -10
- package/backend/ws/projects/status.ts +2 -0
- package/backend/ws/sessions/crud.ts +22 -33
- package/backend/ws/settings/crud.ts +13 -13
- package/backend/ws/snapshot/restore.ts +5 -2
- package/backend/ws/snapshot/timeline.ts +3 -1
- package/backend/ws/system-tools/access.ts +28 -0
- package/backend/ws/system-tools/install.ts +13 -4
- package/backend/ws/system-tools/status.ts +5 -2
- package/backend/ws/terminal/access.ts +56 -0
- package/backend/ws/terminal/persistence.ts +12 -6
- package/backend/ws/terminal/session.ts +35 -14
- package/backend/ws/terminal/stream.ts +4 -1
- package/dist/assets/{index-C86jwBxR.js → index-D8V2wj9B.js} +2 -2
- package/dist/assets/{main-DhLx8wD1.js → main-C9nYVmnw.js} +222 -195
- package/dist/assets/main-hspyFOoK.css +1 -0
- package/dist/index.html +2 -2
- package/package.json +7 -1
- package/shared/constants/engines.ts +45 -140
- package/shared/types/database/schema.ts +49 -1
- package/shared/types/db-client/connection.ts +60 -0
- package/shared/types/db-client/index.ts +6 -0
- package/shared/types/db-client/query.ts +77 -0
- package/shared/types/unified/common.ts +1 -1
- package/shared/types/unified/engine.ts +29 -1
- package/shared/types/unified/index.ts +2 -0
- package/shared/types/unified/message.ts +1 -1
- package/shared/types/unified/tool.ts +17 -2
- package/shared/utils/logger.ts +1 -0
- package/shared/utils/ws-server.ts +14 -0
- package/dist/assets/main-jTnmAoXS.css +0 -1
|
@@ -0,0 +1,1702 @@
|
|
|
1
|
+
# `backend/engine/` — End-to-End Adapter Guide
|
|
2
|
+
|
|
3
|
+
This folder is the **boundary** between Clopen and the AI SDKs that drive
|
|
4
|
+
streaming chat. Today there are three adapters: **`claude`**
|
|
5
|
+
(`@anthropic-ai/claude-agent-sdk`), **`opencode`** (`@opencode-ai/sdk`), and
|
|
6
|
+
**`copilot`** (`@github/copilot-sdk`). Every adapter follows the same shape so
|
|
7
|
+
that the rest of the system outside this folder — `stream-manager`, MCP, DB,
|
|
8
|
+
WebSocket, frontend chat, settings UI — stays **agnostic** to the underlying
|
|
9
|
+
SDK.
|
|
10
|
+
|
|
11
|
+
This document covers **end to end**:
|
|
12
|
+
|
|
13
|
+
1. Full architecture map
|
|
14
|
+
2. The `backend/engine/` layer (adapter contract)
|
|
15
|
+
3. The `engine_providers` + `engine_accounts` DB tables
|
|
16
|
+
4. WebSocket routes — `engine:*`, `system-tools:*`, `chat:stream`, `models:list`
|
|
17
|
+
5. Frontend stores & components (Settings → Engines, Settings → System Tools)
|
|
18
|
+
6. Chat-input integration (model picker, stream)
|
|
19
|
+
7. Registering a binary in **Settings → System Tools**
|
|
20
|
+
8. **End-to-end checklist** for adding a new adapter
|
|
21
|
+
9. Lessons learned — pitfalls when authoring a new adapter
|
|
22
|
+
|
|
23
|
+
---
|
|
24
|
+
|
|
25
|
+
## 1. Architecture map
|
|
26
|
+
|
|
27
|
+
```
|
|
28
|
+
┌──────────────────── FRONTEND (Svelte 5 + runes) ─────────────────────┐
|
|
29
|
+
│ │
|
|
30
|
+
│ Settings → Engines Settings → System Tools Chat Input │
|
|
31
|
+
│ ───────────────────── ────────────────────── ────────────── │
|
|
32
|
+
│ AIEnginesSettings.svelte SystemToolsSettings… EngineModel… │
|
|
33
|
+
│ │ │ │ │
|
|
34
|
+
│ ├─ claudeAccountsStore └─ ws.http( ├─ model │
|
|
35
|
+
│ ├─ copilotAccountsStore 'system-tools:…') │ Store │
|
|
36
|
+
│ ├─ opencodeProvidersStore └─ chat │
|
|
37
|
+
│ └─ modelStore ModelState│
|
|
38
|
+
│ │ │ │ │ │ │
|
|
39
|
+
│ ▼ ▼ ▼ ▼ ▼ │
|
|
40
|
+
│ ws.http('engine:*') ws.http('system-tools:*') ws.emit('chat:…') │
|
|
41
|
+
└──────────────────────────────┬────────────────────────────────────────┘
|
|
42
|
+
│ WebSocket (ws-server router)
|
|
43
|
+
┌──────────────────────────────▼────────────────────────────────────────┐
|
|
44
|
+
│ BACKEND ROUTERS │
|
|
45
|
+
│ │
|
|
46
|
+
│ backend/ws/engine/claude/ backend/ws/engine/opencode/ │
|
|
47
|
+
│ status.ts, accounts.ts status.ts, providers.ts │
|
|
48
|
+
│ backend/ws/engine/copilot/ │
|
|
49
|
+
│ status.ts, accounts.ts │
|
|
50
|
+
│ backend/ws/system-tools/ backend/ws/chat/stream.ts │
|
|
51
|
+
│ status.ts, install.ts backend/ws/settings/crud.ts │
|
|
52
|
+
│ │ │ │
|
|
53
|
+
│ ▼ ▼ │
|
|
54
|
+
│ ┌──────────────────────────────────────────────────────────────────┐ │
|
|
55
|
+
│ │ backend/engine/ ← THE LAYER THIS README DOCUMENTS │ │
|
|
56
|
+
│ │ ────────────────── │ │
|
|
57
|
+
│ │ index.ts registry: getEngine / getProjectEngine│ │
|
|
58
|
+
│ │ types.ts contract: AIEngine │ │
|
|
59
|
+
│ │ install-recipes.ts per-platform install commands │ │
|
|
60
|
+
│ │ install-runner.ts spawns recipe, streams logs over WS │ │
|
|
61
|
+
│ │ adapters/<name>/ │ │
|
|
62
|
+
│ │ index.ts public surface (re-exports only) │ │
|
|
63
|
+
│ │ stream.ts class implements AIEngine │ │
|
|
64
|
+
│ │ message-converter.ts SDK message → EngineOutput │ │
|
|
65
|
+
│ │ models.ts static array OR dynamic fetcher │ │
|
|
66
|
+
│ │ error-handler.ts SDK error → user-facing string │ │
|
|
67
|
+
│ │ credential.ts? credential parsing / auth-blob swap │ │
|
|
68
|
+
│ │ environment.ts? env-var / dotfile setup │ │
|
|
69
|
+
│ │ server.ts? subprocess + client (opencode only) │ │
|
|
70
|
+
│ │ config.ts? runtime config builder (opencode only)│ │
|
|
71
|
+
│ │ presets.ts? provider/region preset catalog │ │
|
|
72
|
+
│ └──────────────────────────────────────────────────────────────────┘ │
|
|
73
|
+
│ │ │ │
|
|
74
|
+
│ ▼ ▼ │
|
|
75
|
+
│ backend/database/queries/ backend/chat/stream-manager.ts │
|
|
76
|
+
│ engine-queries.ts routes EngineOutput → DB + WS │
|
|
77
|
+
│ engine_providers + engine_accounts │
|
|
78
|
+
└───────────────────────────────────────────────────────────────────────┘
|
|
79
|
+
```
|
|
80
|
+
|
|
81
|
+
Three key rules that **every** layer upholds:
|
|
82
|
+
|
|
83
|
+
- **`EngineOutput`** (in `shared/types/unified/stream.ts`) is the only data
|
|
84
|
+
shape that crosses the adapter → stream-manager boundary. No other type
|
|
85
|
+
may leak out of an adapter.
|
|
86
|
+
- **`engine_providers` + `engine_accounts`** are the only source of
|
|
87
|
+
credentials. An adapter never reads arbitrary env vars; it reads from
|
|
88
|
+
the DB via `engineQueries`.
|
|
89
|
+
- **`AIEngine`** (in `types.ts`) is the only class the stream-manager calls.
|
|
90
|
+
New methods are not added ad-hoc — they are added to the interface first,
|
|
91
|
+
then implemented in **every** adapter.
|
|
92
|
+
|
|
93
|
+
> ⚠️ **Before you propose new infrastructure, read this.**
|
|
94
|
+
> Two design pitfalls have repeatedly tripped people adding new adapters.
|
|
95
|
+
> Before sketching architecture, double-check:
|
|
96
|
+
>
|
|
97
|
+
> 1. **MCP over HTTP already exists.** `backend/mcp/remote-server.ts` mounts
|
|
98
|
+
> every `defineServer()`-registered MCP server as a Streamable HTTP
|
|
99
|
+
> endpoint at `http://localhost:<port>/mcp`. OpenCode consumes it via
|
|
100
|
+
> `getOpenCodeMcpConfig()`. Any engine whose CLI/SDK accepts a
|
|
101
|
+
> `streamable-http` MCP URL (Codex, future engines) reuses **the same
|
|
102
|
+
> URL** by adding a sibling `getXxxMcpConfig()` helper in
|
|
103
|
+
> `backend/mcp/config.ts`. Do **NOT** propose a "new MCP bridge",
|
|
104
|
+
> "per-engine MCP server", or "per-stream MCP path". See §9.12.
|
|
105
|
+
> 2. **Shared CLI dotfiles are swapped from DB, not isolated.** When a CLI
|
|
106
|
+
> stores its credentials in a known location (e.g. `~/.codex/auth.json`),
|
|
107
|
+
> the multi-account approach is to snapshot that file into the DB on
|
|
108
|
+
> login and write the chosen account's snapshot back on switch. Do
|
|
109
|
+
> **NOT** propose per-account isolated home directories
|
|
110
|
+
> (`CODEX_HOME=/foo/account-1/`); that path complicates session-state
|
|
111
|
+
> sharing, token refresh persistence, and user-level config inheritance.
|
|
112
|
+
> See §9.13.
|
|
113
|
+
|
|
114
|
+
---
|
|
115
|
+
|
|
116
|
+
## 2. The `backend/engine/` layer — core contract
|
|
117
|
+
|
|
118
|
+
### 2.1 `types.ts` — the `AIEngine` interface
|
|
119
|
+
|
|
120
|
+
```ts
|
|
121
|
+
export interface AIEngine {
|
|
122
|
+
readonly name: EngineType; // 'claude-code' | 'opencode' | 'copilot'
|
|
123
|
+
readonly isInitialized: boolean;
|
|
124
|
+
readonly isActive: boolean;
|
|
125
|
+
|
|
126
|
+
initialize(accountId?: number): Promise<void>; // lazy; idempotent
|
|
127
|
+
dispose(): Promise<void>; // called per-project & on shutdown
|
|
128
|
+
cancel(): Promise<void>; // hard cancel
|
|
129
|
+
interrupt(): Promise<void>; // soft stop
|
|
130
|
+
|
|
131
|
+
streamQuery(options: EngineQueryOptions):
|
|
132
|
+
AsyncGenerator<EngineOutput, void, unknown>;
|
|
133
|
+
|
|
134
|
+
getAvailableModels(): Promise<EngineModel[]>;
|
|
135
|
+
|
|
136
|
+
// Optional
|
|
137
|
+
resolveUserAnswer?(toolUseId: string, answers: Record<string,string>): boolean;
|
|
138
|
+
generateStructured?<T>(options: StructuredGenerationOptions): Promise<T>;
|
|
139
|
+
}
|
|
140
|
+
```
|
|
141
|
+
|
|
142
|
+
Three invariants:
|
|
143
|
+
|
|
144
|
+
1. **`streamQuery` is the only streaming output path.** It is an
|
|
145
|
+
`AsyncGenerator<EngineOutput>`. The adapter translates SDK events into
|
|
146
|
+
`EngineOutput` — that is all.
|
|
147
|
+
2. **Streaming state lives on the instance.** Because `getProjectEngine`
|
|
148
|
+
returns one instance per `(projectId, engineType)`, the abort controller,
|
|
149
|
+
active query, `pendingUserAnswers`, and session ID are automatically
|
|
150
|
+
isolated per-project.
|
|
151
|
+
3. **Init is lazy & concurrency-safe.** The first `streamQuery` /
|
|
152
|
+
`getAvailableModels` call triggers `initialize()`. Multiple parallel
|
|
153
|
+
callers **must** share a single init promise. See:
|
|
154
|
+
- `claude/environment.ts::setupEnvironmentOnce`
|
|
155
|
+
- `opencode/server.ts::ensureClient`
|
|
156
|
+
|
|
157
|
+
### 2.2 `index.ts` — registry & lifecycle
|
|
158
|
+
|
|
159
|
+
Two instance tiers:
|
|
160
|
+
|
|
161
|
+
| Tier | Factory | Used for |
|
|
162
|
+
|--------------------|-------------------------------|-------------------------------------------|
|
|
163
|
+
| Global singleton | `getEngine(type)` | Non-streaming ops: `models:list`, settings|
|
|
164
|
+
| Per-project | `getProjectEngine(projectId, type)` | Streaming chat — isolated per-project|
|
|
165
|
+
|
|
166
|
+
Cleanup:
|
|
167
|
+
- `disposeProjectEngines(projectId)` when a project closes.
|
|
168
|
+
- `disposeAllEngines()` at server shutdown — also calls
|
|
169
|
+
`disposeOpenCodeClient()`. Pattern: when an adapter owns a shared
|
|
170
|
+
subprocess, expose `disposeXxxClient()` from `adapters/<name>/index.ts`
|
|
171
|
+
and call it from `disposeAllProjectEngines()` in `index.ts`.
|
|
172
|
+
|
|
173
|
+
### 2.3 `EngineOutput` — the event contract
|
|
174
|
+
|
|
175
|
+
In `shared/types/unified/stream.ts`:
|
|
176
|
+
|
|
177
|
+
```ts
|
|
178
|
+
type EngineOutput =
|
|
179
|
+
| UserMessage // persisted to DB
|
|
180
|
+
| AssistantMessage // persisted to DB
|
|
181
|
+
| ReasoningMessage // persisted to DB
|
|
182
|
+
| CompactBoundaryMessage
|
|
183
|
+
| StreamEvent // transient: 'start' | 'stop' | 'delta'
|
|
184
|
+
| ResultEvent // transient: success / error_max_turns / etc.
|
|
185
|
+
| SystemInitEvent // transient: model + tools + mcpServers
|
|
186
|
+
| RateLimitEvent; // transient
|
|
187
|
+
```
|
|
188
|
+
|
|
189
|
+
`stream-manager.ts` discriminates on `output.type`:
|
|
190
|
+
|
|
191
|
+
| `type` | Routing |
|
|
192
|
+
|----------------|---------------------------------------------------------|
|
|
193
|
+
| `user`/`assistant`/`reasoning`/`compact_boundary` | save DB + emit `chat:message` |
|
|
194
|
+
| `stream_event` | forward to frontend for live typing (`chat:partial`) |
|
|
195
|
+
| `result` | extract metadata + emit `chat:stream-finished` |
|
|
196
|
+
| `system_init` | emit MCP-failure notification if any |
|
|
197
|
+
| `rate_limit` | emit `chat:notification` |
|
|
198
|
+
|
|
199
|
+
> **Strict rule:** do not invent new types. If an SDK has an event that
|
|
200
|
+
> needs to be propagated, **extend** the union in
|
|
201
|
+
> `shared/types/unified/stream.ts` first, teach `stream-manager` how to
|
|
202
|
+
> route it, and only then emit it from the adapter.
|
|
203
|
+
|
|
204
|
+
### 2.4 `EngineQueryOptions`
|
|
205
|
+
|
|
206
|
+
```ts
|
|
207
|
+
interface EngineQueryOptions {
|
|
208
|
+
projectPath: string;
|
|
209
|
+
prompt: UserMessage;
|
|
210
|
+
resume?: string; // SDK session id for resume / fork
|
|
211
|
+
forkSession?: boolean;
|
|
212
|
+
maxTurns?: number;
|
|
213
|
+
providerSlug: string; // 'anthropic', 'openai', etc — required for opencode
|
|
214
|
+
modelId: string; // 'claude-opus-4-7', 'gpt-5', etc
|
|
215
|
+
includePartialMessages?: boolean;
|
|
216
|
+
abortController?: AbortController;
|
|
217
|
+
accountId?: number; // override credential for a single stream
|
|
218
|
+
mcpContext?: McpExecutionContext; // { projectId, chatSessionId, streamId }
|
|
219
|
+
}
|
|
220
|
+
```
|
|
221
|
+
|
|
222
|
+
`mcpContext` is bound into the MCP handler so a tool call from project A
|
|
223
|
+
**cannot** write into project B. Always forward it: see `claude/stream.ts`
|
|
224
|
+
calling `getEnabledMcpServers(options.mcpContext)`.
|
|
225
|
+
|
|
226
|
+
### 2.5 What an adapter **MUST NOT** do
|
|
227
|
+
|
|
228
|
+
- ❌ Call `ws.emit.*` — that is the stream-manager's job.
|
|
229
|
+
- ❌ Touch chat / message DB (`messageQueries`, `sessionQueries`) —
|
|
230
|
+
persistence belongs to the stream-manager. Adapters **may** read
|
|
231
|
+
credentials via `engineQueries`.
|
|
232
|
+
- ❌ Mutate `process.env` or call `process.chdir()` — pass env & cwd via
|
|
233
|
+
SDK options. Many projects stream concurrently.
|
|
234
|
+
- ❌ Define shared types inline — extend `shared/types/unified/*`.
|
|
235
|
+
- ❌ Use `console.*` — use `debug` from `$shared/utils/logger` with
|
|
236
|
+
category `'engine'`, `'chat'`, or `'mcp'`.
|
|
237
|
+
- ❌ **Build a new MCP HTTP server for the adapter.** Use the existing
|
|
238
|
+
`backend/mcp/remote-server.ts` and add a `getXxxMcpConfig()` helper in
|
|
239
|
+
`backend/mcp/config.ts` returning the URL in the engine's expected
|
|
240
|
+
shape. New MCP servers are added via `defineServer()` — never via a
|
|
241
|
+
parallel HTTP listener.
|
|
242
|
+
- ❌ **Create per-account isolated home directories** to multiplex two
|
|
243
|
+
accounts into the same CLI's shared dotfile. Snapshot the CLI's auth
|
|
244
|
+
file into `engine_accounts.credential` on login; write the chosen
|
|
245
|
+
account's snapshot back into the shared location on switch. See §9.13.
|
|
246
|
+
|
|
247
|
+
### 2.6 Standard files in each adapter
|
|
248
|
+
|
|
249
|
+
Adapters follow a fixed file taxonomy. **Mandatory** files exist in every
|
|
250
|
+
adapter; **optional** files may be omitted, but when present they MUST use
|
|
251
|
+
the canonical name below — never a synonym (`auth.ts`, `provider-catalog.ts`,
|
|
252
|
+
etc.). This keeps `git grep` and the README's quick-reference rows usable.
|
|
253
|
+
|
|
254
|
+
```
|
|
255
|
+
adapters/<name>/
|
|
256
|
+
├── index.ts ← MANDATORY re-exports only, NO logic
|
|
257
|
+
├── stream.ts ← MANDATORY class implements AIEngine
|
|
258
|
+
├── models.ts ← MANDATORY static EngineModel[] OR dynamic fetcher
|
|
259
|
+
├── message-converter.ts ← MANDATORY SDK message → EngineOutput (pure)
|
|
260
|
+
├── error-handler.ts ← MANDATORY SDK error → user-facing string
|
|
261
|
+
├── credential.ts? ← OPTIONAL credential parse / auth-blob swap (codex, qwen)
|
|
262
|
+
├── environment.ts? ← OPTIONAL env / dotfile setup (claude, qwen)
|
|
263
|
+
├── server.ts? ← OPTIONAL subprocess + client lifecycle (opencode)
|
|
264
|
+
├── config.ts? ← OPTIONAL runtime config builder (opencode)
|
|
265
|
+
├── presets.ts? ← OPTIONAL multi-provider/region preset catalog (qwen, opencode)
|
|
266
|
+
└── session-fork.ts? ← OPTIONAL on-disk session fork workaround (codex, copilot)
|
|
267
|
+
```
|
|
268
|
+
|
|
269
|
+
Naming rules — strict, even when an SDK's local jargon differs:
|
|
270
|
+
|
|
271
|
+
| File | Owns |
|
|
272
|
+
|-------------------|-----------------------------------------------------------------------|
|
|
273
|
+
| `credential.ts` | Parse `engine_accounts.credential` (JSON wrapper or raw key); for shared-CLI engines, materialise the auth-blob into the dotfile and snapshot it back. **Never** name this `auth.ts` — credentials are the unified concept (see §9.13). |
|
|
274
|
+
| `error-handler.ts`| Export `handleStreamError(error: unknown, ...): void` that swallows abort errors and re-throws everything else as a sanitised `Error`. Required even when the body is short — `OpenCodeEngine` previously inlined ~50 lines into the catch block; that pattern is no longer accepted. |
|
|
275
|
+
| `presets.ts` | Multi-provider/region picker catalog (Qwen's DashScope/OpenRouter/Fireworks; OpenCode's models.dev cache). Multi-provider engines that lacked a `presets.ts` (OpenCode used to call this `config.ts`) have been migrated. |
|
|
276
|
+
| `config.ts` | Runtime config builder ONLY — turning DB providers + accounts into env vars / spawn options. Catalog data goes in `presets.ts`. |
|
|
277
|
+
|
|
278
|
+
Important conventions:
|
|
279
|
+
- `message-converter.ts` is generally pure. If you need per-stream state
|
|
280
|
+
(e.g. tracking "is the reasoning block already closed?"), expose a
|
|
281
|
+
**factory** `createSdkMessageConverter()` returning a stateful converter
|
|
282
|
+
— see Claude.
|
|
283
|
+
- Tool names **must** be canonicalised via `toCanonicalToolName(...)`
|
|
284
|
+
(`shared/types/unified/tool.ts`) so the frontend renders the same UI for
|
|
285
|
+
tools that have different names across SDKs.
|
|
286
|
+
- `cancel()` ordering: **abort the local controller first**, **then** RPC
|
|
287
|
+
to the SDK/server. RPCs can hang; the local abort cuts the `for await`
|
|
288
|
+
loop deterministically. See `OpenCodeEngine.cancel`,
|
|
289
|
+
`ClaudeCodeEngine.cancel`, `CopilotEngine.cancel`.
|
|
290
|
+
- Dynamic-catalog fetchers in `models.ts` MUST return `EngineModel[]` and
|
|
291
|
+
use `[]` as the failure sentinel (network, auth, parse error). Do **not**
|
|
292
|
+
return `null` — both `fetchOpenCodeModels` and `fetchQwenModels` return
|
|
293
|
+
`[]` on failure so the picker renders empty rather than a stale catalog.
|
|
294
|
+
|
|
295
|
+
---
|
|
296
|
+
|
|
297
|
+
## 3. Database — `engine_providers` & `engine_accounts`
|
|
298
|
+
|
|
299
|
+
Migration: `backend/database/migrations/029_migrate_messages_to_unified.ts`
|
|
300
|
+
(Phases 6–7). Previously split into `claude_accounts`, `opencode_providers`,
|
|
301
|
+
`opencode_accounts` — now **consolidated**.
|
|
302
|
+
|
|
303
|
+
### 3.1 Schema
|
|
304
|
+
|
|
305
|
+
```sql
|
|
306
|
+
CREATE TABLE engine_providers (
|
|
307
|
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
308
|
+
engine_type TEXT NOT NULL, -- 'claude-code' | 'opencode' | 'copilot' | <new>
|
|
309
|
+
slug TEXT NOT NULL, -- 'anthropic', 'openai', etc (lowercase)
|
|
310
|
+
name TEXT NOT NULL, -- display name
|
|
311
|
+
npm TEXT, -- npm package (opencode), NULL for claude/copilot
|
|
312
|
+
api_url TEXT, -- custom endpoint
|
|
313
|
+
options TEXT NOT NULL DEFAULT '{}', -- JSON: env var values, flags
|
|
314
|
+
is_enabled INTEGER NOT NULL DEFAULT 1,
|
|
315
|
+
created_at TEXT NOT NULL DEFAULT (datetime('now')),
|
|
316
|
+
UNIQUE (engine_type, slug)
|
|
317
|
+
);
|
|
318
|
+
|
|
319
|
+
CREATE TABLE engine_accounts (
|
|
320
|
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
321
|
+
provider_id INTEGER NOT NULL REFERENCES engine_providers(id) ON DELETE CASCADE,
|
|
322
|
+
name TEXT NOT NULL,
|
|
323
|
+
credential TEXT NOT NULL, -- OAuth token / API key / PAT
|
|
324
|
+
is_active INTEGER NOT NULL DEFAULT 0,
|
|
325
|
+
created_at TEXT NOT NULL DEFAULT (datetime('now'))
|
|
326
|
+
);
|
|
327
|
+
```
|
|
328
|
+
|
|
329
|
+
Concepts:
|
|
330
|
+
- **Provider** = "who owns the model". For `claude-code` there is exactly
|
|
331
|
+
one provider (`anthropic`, seeded in the migration). For `copilot` there
|
|
332
|
+
is exactly one provider (`github`, seeded in `032_seed_copilot_provider.ts`).
|
|
333
|
+
For `opencode`, the user adds many providers (Anthropic, OpenAI, Google,
|
|
334
|
+
OpenRouter, …).
|
|
335
|
+
- **Account** = the concrete credential under a provider. Multiple are
|
|
336
|
+
allowed; exactly one row per provider has `is_active = 1`.
|
|
337
|
+
- **Switching account** flip-flags automatically:
|
|
338
|
+
`engineQueries.switchAccount(id)` sets all accounts under that provider
|
|
339
|
+
to `is_active = 0`, then sets the chosen one to `1`.
|
|
340
|
+
- **Deleting the active account** automatically promotes another account in
|
|
341
|
+
the same provider to active (logic in `engineQueries.deleteAccount`).
|
|
342
|
+
|
|
343
|
+
### 3.2 Main helpers (`engineQueries`)
|
|
344
|
+
|
|
345
|
+
```ts
|
|
346
|
+
// Provider
|
|
347
|
+
getProviders(engineType?) getEnabledProviders(engineType?)
|
|
348
|
+
getProvider(id) getProviderBySlug(engineType, slug)
|
|
349
|
+
createProvider({...}) updateProviderOptions(id, jsonStr)
|
|
350
|
+
toggleProvider(id, enabled) deleteProvider(id) // cascades to accounts
|
|
351
|
+
|
|
352
|
+
// Account
|
|
353
|
+
getAccount(id) getAccountsByProvider(providerId)
|
|
354
|
+
getActiveAccount(providerId) getActiveAccountForEngine(engineType)
|
|
355
|
+
createAccount(providerId, name, credential) // auto-active if first
|
|
356
|
+
switchAccount(accountId) deleteAccount(accountId)
|
|
357
|
+
renameAccount(accountId, name)
|
|
358
|
+
|
|
359
|
+
// Composite
|
|
360
|
+
getProvidersWithAccounts(engineType?) // join used by endpoint listing
|
|
361
|
+
```
|
|
362
|
+
|
|
363
|
+
### 3.3 How an adapter reads them
|
|
364
|
+
|
|
365
|
+
- **Claude** — `environment.ts` calls
|
|
366
|
+
`engineQueries.getActiveAccountForEngine('claude-code')` inside
|
|
367
|
+
`setupEnvironmentOnce()` to inject `CLAUDE_CODE_OAUTH_TOKEN`. When
|
|
368
|
+
`streamQuery` is called with an explicit `accountId`,
|
|
369
|
+
`getEngineEnv(accountId)` overrides the token without mutating singleton
|
|
370
|
+
state — ideal for per-stream account override.
|
|
371
|
+
|
|
372
|
+
- **OpenCode** — `config.ts::generateOpenCodeProviderConfig()`:
|
|
373
|
+
1. `engineQueries.getEnabledProviders('opencode')`
|
|
374
|
+
2. For each provider, `getActiveAccount(provider.id)`
|
|
375
|
+
3. Look up the env-var name(s) from the `models.dev` catalog cached in
|
|
376
|
+
`presets.ts::getCachedModelsDevCatalog()` (see §3.4)
|
|
377
|
+
4. Inject the first env var with `account.credential`, remaining env vars
|
|
378
|
+
from `provider.options` JSON
|
|
379
|
+
5. Result: `enabledProviders[]` (for `OPENCODE_CONFIG_CONTENT`) +
|
|
380
|
+
`envVars{}` (merged into the `opencode serve` process)
|
|
381
|
+
|
|
382
|
+
- **Copilot** — `stream.ts::initialize(accountId?)` calls
|
|
383
|
+
`engineQueries.getAccount(accountId)` (or
|
|
384
|
+
`getActiveAccountForEngine('copilot')` when no override is supplied)
|
|
385
|
+
and constructs a fresh `CopilotClient({ gitHubToken: account.credential })`.
|
|
386
|
+
The Copilot SDK takes the token at **client construction time**, so a
|
|
387
|
+
per-stream account switch requires `dispose()` + `initialize(newId)` —
|
|
388
|
+
see `streamQuery` in `copilot/stream.ts` and §9.9 below.
|
|
389
|
+
|
|
390
|
+
> **Pattern: auth-blob materialization for shared CLI dotfiles.**
|
|
391
|
+
> Some CLIs (e.g. Codex's `~/.codex/auth.json`) read credentials from a
|
|
392
|
+
> fixed location on disk that **cannot** be redirected per-process without
|
|
393
|
+
> isolating the entire home dir. For those engines, `credential` stores
|
|
394
|
+
> the **whole file content** as a JSON wrapper
|
|
395
|
+
> (`{ kind: 'chatgpt', authJson: '...' }`), and the adapter / WS handler
|
|
396
|
+
> writes that blob back to the shared dotfile on `accounts-switch`. After
|
|
397
|
+
> each stream, snapshot the (possibly-refreshed-by-the-CLI) dotfile back
|
|
398
|
+
> into `engine_accounts.credential` so token refreshes survive across
|
|
399
|
+
> account switches. This keeps multi-account support working without
|
|
400
|
+
> isolated `XYZ_HOME` directories — see §9.13 for the rationale.
|
|
401
|
+
|
|
402
|
+
### 3.4 The models.dev catalog (OpenCode-specific)
|
|
403
|
+
|
|
404
|
+
`presets.ts::fetchAndCacheModelsDevCatalog()` caches the catalog in the
|
|
405
|
+
`settings` table under `opencode.models_dev_cache`
|
|
406
|
+
(+ `opencode.models_dev_cached_at`). `getCachedModelsDevCatalog()` reads it
|
|
407
|
+
back. The catalog lists the providers OpenCode supports along with the
|
|
408
|
+
env-var names they expect. The frontend uses the catalog in the "Add
|
|
409
|
+
Provider" picker — the user just selects a provider, enters the API key,
|
|
410
|
+
and the env-var mapping is automatically correct.
|
|
411
|
+
|
|
412
|
+
The split between `presets.ts` (catalog data + cache) and `config.ts`
|
|
413
|
+
(runtime env-var builder) mirrors `qwen/`, the canonical multi-provider
|
|
414
|
+
adapter — see §2.6 and §4.6.
|
|
415
|
+
|
|
416
|
+
---
|
|
417
|
+
|
|
418
|
+
## 4. WebSocket routes
|
|
419
|
+
|
|
420
|
+
All handlers use `createRouter()` (Elysia + ws-server). Routers are merged
|
|
421
|
+
in `backend/ws/index.ts`. Four groups are relevant for engines:
|
|
422
|
+
|
|
423
|
+
| Group | Path | Purpose |
|
|
424
|
+
|---------------------------------|-------------------------------------|--------------------------------------------|
|
|
425
|
+
| `engine:claude-*` | `backend/ws/engine/claude/` | Status + Claude account CRUD |
|
|
426
|
+
| `engine:opencode-*` | `backend/ws/engine/opencode/` | Status + provider/account CRUD + restart |
|
|
427
|
+
| `engine:copilot-*` | `backend/ws/engine/copilot/` | Status + Copilot account CRUD |
|
|
428
|
+
| `system-tools:*` | `backend/ws/system-tools/` | Detect/install binaries |
|
|
429
|
+
| `models:list`, `chat:stream` | `backend/ws/settings/crud.ts`, `backend/ws/chat/stream.ts` | Model fetch + stream start |
|
|
430
|
+
|
|
431
|
+
### 4.1 Claude — `engine:claude-*`
|
|
432
|
+
|
|
433
|
+
`backend/ws/engine/claude/index.ts` merges two sub-handlers:
|
|
434
|
+
|
|
435
|
+
| Event | Mode | Purpose |
|
|
436
|
+
|---------------------------------------------|---------|-----------------------------------------------|
|
|
437
|
+
| `engine:claude-status` | `.http` | `{ installed, version, activeAccount, accountsCount, backendOS }` |
|
|
438
|
+
| `engine:claude-accounts-list` | `.http` | List Claude accounts |
|
|
439
|
+
| `engine:claude-accounts-switch` | `.http` | Set active; calls `resetEnvironment()` so a new token is picked up on the next stream |
|
|
440
|
+
| `engine:claude-accounts-delete` | `.http` | |
|
|
441
|
+
| `engine:claude-accounts-rename` | `.http` | |
|
|
442
|
+
| `engine:claude-account-setup-start` | `.on` | Spawn PTY `claude setup-token` (state machine `waiting-url → waiting-token → done`) |
|
|
443
|
+
| `engine:claude-account-setup-submit` | `.on` | Send the auth code to the PTY |
|
|
444
|
+
| `engine:claude-account-setup-cancel` | `.on` | |
|
|
445
|
+
| `engine:claude-account-setup-url` (emit) | | OAuth URL detected in PTY output |
|
|
446
|
+
| `engine:claude-account-setup-complete` (emit) | | Token success → `engineQueries.createAccount` + `resetEnvironment()` |
|
|
447
|
+
| `engine:claude-account-setup-error` (emit) | | |
|
|
448
|
+
| `engine:claude-account-setup-pty-data` (emit) | | Stream raw PTY (debug) |
|
|
449
|
+
|
|
450
|
+
The Claude setup flow needs a PTY because Anthropic's CLI is interactive.
|
|
451
|
+
See `backend/ws/engine/claude/accounts.ts` for the state-machine details
|
|
452
|
+
(one `onData` listener + one `onExit` per session, the phase tracked in a
|
|
453
|
+
`phase` field).
|
|
454
|
+
|
|
455
|
+
### 4.2 OpenCode — `engine:opencode-*`
|
|
456
|
+
|
|
457
|
+
`backend/ws/engine/opencode/index.ts` merges:
|
|
458
|
+
|
|
459
|
+
| Event | Purpose |
|
|
460
|
+
|---------------------------------------------|-----------------------------------------------|
|
|
461
|
+
| `engine:opencode-status` | `{ installed, version, backendOS }` |
|
|
462
|
+
| `engine:opencode-providers-list` | List `engine_providers WHERE engine_type='opencode'` + accounts |
|
|
463
|
+
| `engine:opencode-provider-add` | Create provider + first account (auto-active) |
|
|
464
|
+
| `engine:opencode-provider-remove` | Cascades to accounts |
|
|
465
|
+
| `engine:opencode-provider-toggle` | Flip `is_enabled` |
|
|
466
|
+
| `engine:opencode-provider-update-options` | Update JSON options (handler validates JSON) |
|
|
467
|
+
| `engine:opencode-account-add` | Add an account to a provider |
|
|
468
|
+
| `engine:opencode-account-switch` | |
|
|
469
|
+
| `engine:opencode-account-delete` | |
|
|
470
|
+
| `engine:opencode-account-rename` | |
|
|
471
|
+
| `engine:opencode-models-dev-list` | Cached catalog (auto-fetches if absent) |
|
|
472
|
+
| `engine:opencode-models-dev-fetch` | Force refetch |
|
|
473
|
+
| `engine:opencode-server-restart` | Stop subprocess + clear stored URL → next stream spawns a fresh server |
|
|
474
|
+
|
|
475
|
+
`engine:opencode-server-restart` first checks whether any OpenCode stream
|
|
476
|
+
is active: if so and `force` was not set, it returns
|
|
477
|
+
`{ needsConfirmation: true, activeChats: N }` so the UI can ask for
|
|
478
|
+
confirmation. When `force=true`, all OpenCode streams are `cancelStream`'d,
|
|
479
|
+
followed by `disposeEngine('opencode')` + `disposeOpenCodeClient(true)` —
|
|
480
|
+
the `forRestart` flag drops the stored URL and kills the server even if
|
|
481
|
+
Clopen did not spawn it (the reuse case).
|
|
482
|
+
|
|
483
|
+
#### Restart-Server pattern (long-lived server engines)
|
|
484
|
+
|
|
485
|
+
Engines that hold a **long-lived process or client** (OpenCode's `opencode
|
|
486
|
+
serve` subprocess, Copilot's `CopilotClient`) cache provider/account
|
|
487
|
+
credentials at boot or construction time. Adding, removing, or switching
|
|
488
|
+
an account does **not** automatically take effect for in-flight streams or
|
|
489
|
+
the cached client — the engine must be **restarted**. The adapter exposes
|
|
490
|
+
a `*-server-restart` event; the UI surfaces this to the user as a
|
|
491
|
+
**"Restart Server"** button in two places:
|
|
492
|
+
|
|
493
|
+
1. **Settings → Engines** card — shown whenever the user has just changed
|
|
494
|
+
provider/account state (add / remove / switch). See
|
|
495
|
+
`AIEnginesSettings.svelte::handleRestartServer` (with the
|
|
496
|
+
`needsConfirmation` confirm-dialog flow) and
|
|
497
|
+
`forceRestartServer`.
|
|
498
|
+
2. **Chat Input → next to the model/account picker** — shown when the
|
|
499
|
+
active session's account has just been switched mid-flight and the
|
|
500
|
+
user needs to apply it before sending the next prompt. See
|
|
501
|
+
`EngineModelPicker.svelte::ocNeedsRestart` / `restartOCServer`. The
|
|
502
|
+
button uses `force: true` so users in chat don't see another modal.
|
|
503
|
+
|
|
504
|
+
The handler contract any restart event must follow:
|
|
505
|
+
|
|
506
|
+
| Step | Behavior |
|
|
507
|
+
|---|---|
|
|
508
|
+
| 1 | Inspect the engine's active streams. If any exist and `force !== true`, return `{ needsConfirmation: true, activeChats: N }` — UI then opens a confirm dialog. |
|
|
509
|
+
| 2 | When `force === true`, call `cancelStream` on every active stream for that engine. |
|
|
510
|
+
| 3 | Call `disposeEngine(engineType)` (clears the per-project map) and any adapter-specific shared-resource cleanup (`disposeOpenCodeClient(true)`, etc.). The flag tells the cleanup routine that this is a restart, not a shutdown — drop cached URLs / sockets even if reused from outside. |
|
|
511
|
+
| 4 | Resolve. The next `streamQuery` call will lazy-init the engine fresh against the new account state. |
|
|
512
|
+
|
|
513
|
+
After a successful restart the UI also refreshes models
|
|
514
|
+
(`modelStore.refreshModels(engineType)`) because the model catalog can
|
|
515
|
+
change with the credential.
|
|
516
|
+
|
|
517
|
+
**When a new engine does NOT need this:** if the engine spawns a
|
|
518
|
+
**fresh subprocess per turn** (Codex's `codex exec`, Claude's per-turn
|
|
519
|
+
`query()`), the credential is re-read at every turn and there is nothing
|
|
520
|
+
to "restart". Such engines do not implement `*-server-restart`. The
|
|
521
|
+
appropriate analog for shared-CLI-dotfile engines like Codex is the
|
|
522
|
+
auth-blob swap (§9.13) — performed inside `accounts-switch`, not via a
|
|
523
|
+
separate restart event.
|
|
524
|
+
|
|
525
|
+
### 4.3 Copilot — `engine:copilot-*`
|
|
526
|
+
|
|
527
|
+
`backend/ws/engine/copilot/index.ts` merges:
|
|
528
|
+
|
|
529
|
+
| Event | Purpose |
|
|
530
|
+
|--------------------------------------|-----------------------------------------------|
|
|
531
|
+
| `engine:copilot-status` | `{ installed, version, activeAccount, accountsCount, backendOS }` |
|
|
532
|
+
| `engine:copilot-accounts-list` | List Copilot accounts |
|
|
533
|
+
| `engine:copilot-accounts-add` | Add account by submitting a GitHub PAT |
|
|
534
|
+
| `engine:copilot-accounts-switch` | Set active |
|
|
535
|
+
| `engine:copilot-accounts-delete` | |
|
|
536
|
+
| `engine:copilot-accounts-rename` | |
|
|
537
|
+
| `engine:copilot-server-restart` | Restart cached `CopilotClient` so a new PAT applies — same Restart-Server pattern as §4.2 |
|
|
538
|
+
|
|
539
|
+
The Copilot setup flow does not need a PTY — the user pastes a GitHub
|
|
540
|
+
Personal Access Token in the UI (Copilot Requests + read:user scope), and
|
|
541
|
+
the handler stores it via `engineQueries.createAccount`. No re-auth dance.
|
|
542
|
+
|
|
543
|
+
Copilot follows the **same Restart-Server pattern** documented in §4.2
|
|
544
|
+
because `CopilotClient` takes the PAT at construction time. Account
|
|
545
|
+
add / remove / switch flips a `needsRestart` flag in the UI that surfaces
|
|
546
|
+
a "Restart Server" button in both Settings → Engines and Chat Input.
|
|
547
|
+
|
|
548
|
+
### 4.4 System Tools — `system-tools:*`
|
|
549
|
+
|
|
550
|
+
`backend/ws/system-tools/`:
|
|
551
|
+
|
|
552
|
+
| Event | Purpose |
|
|
553
|
+
|------------------------------------|---------------------------------------------|
|
|
554
|
+
| `system-tools:status` | Detect a single tool: `{ status, recipe, activeSession }` |
|
|
555
|
+
| `system-tools:status-all` | Hardcoded list `['git','claude','opencode','chrome','cloudflared']` |
|
|
556
|
+
| `system-tools:install-start` | Spawn the recipe via `install-runner` |
|
|
557
|
+
| `system-tools:install-cancel` | |
|
|
558
|
+
| `system-tools:install-session` | Snapshot session (for re-attach) |
|
|
559
|
+
| `system-tools:install-started` (emit) | Session begun |
|
|
560
|
+
| `system-tools:install-stream` (emit) | Per-line stdout/stderr |
|
|
561
|
+
| `system-tools:install-finished` (emit) | exit code + final status |
|
|
562
|
+
|
|
563
|
+
### 4.5 `models:list` (in `backend/ws/settings/crud.ts`)
|
|
564
|
+
|
|
565
|
+
```ts
|
|
566
|
+
.http('models:list', { data: { engine } }, async ({ data }) => {
|
|
567
|
+
const engine = await initializeEngine(data.engine);
|
|
568
|
+
const models = await engine.getAvailableModels();
|
|
569
|
+
registerModels(data.engine, models);
|
|
570
|
+
return models;
|
|
571
|
+
})
|
|
572
|
+
```
|
|
573
|
+
|
|
574
|
+
The handler is **uniform across engines** — no per-engine short-circuits.
|
|
575
|
+
Every engine flows through `initializeEngine` → `engine.getAvailableModels()`
|
|
576
|
+
→ `registerModels(...)` so the shared in-memory `modelRegistry` is always
|
|
577
|
+
populated regardless of whether the catalog is static or dynamic.
|
|
578
|
+
|
|
579
|
+
> **Why uniform.** The previous version hard-coded `if (engine === 'claude-code') return CLAUDE_CODE_MODELS`
|
|
580
|
+
> for static engines. That short-circuit bypassed `registerModels()`, so the
|
|
581
|
+
> backend registry stayed empty for static engines and the frontend's
|
|
582
|
+
> `getByEngine('claude-code')` returned nothing — the symptom that motivated
|
|
583
|
+
> this whole standardization. Don't reintroduce the special case; if a static
|
|
584
|
+
> engine's `getAvailableModels()` is too expensive to call repeatedly, cache
|
|
585
|
+
> inside the adapter (`CLAUDE_CODE_MODELS` is already a module-level const,
|
|
586
|
+
> so the call is free).
|
|
587
|
+
|
|
588
|
+
Each engine owns its model catalog in `backend/engine/adapters/<engine>/models.ts`:
|
|
589
|
+
|
|
590
|
+
| Engine | Catalog kind | Source |
|
|
591
|
+
|---------------|--------------|-----------------------------------------------------|
|
|
592
|
+
| `claude-code` | static | hardcoded `CLAUDE_CODE_MODELS` array |
|
|
593
|
+
| `codex` | static | hardcoded `CODEX_MODELS` array |
|
|
594
|
+
| `copilot` | dynamic | `client.listModels()` via `fetchCopilotModels` |
|
|
595
|
+
| `opencode` | dynamic | `client.config.providers()` via `fetchOpenCodeModels`|
|
|
596
|
+
| `qwen` | dynamic | OpenAI-compatible `/models` via `fetchQwenModels` |
|
|
597
|
+
|
|
598
|
+
Failure-mode contract (dynamic engines): return `EngineModel[]` and use
|
|
599
|
+
`[]` as the failure sentinel — never `null` (see §2.6). The picker then
|
|
600
|
+
renders an empty list rather than a stale cached catalog. `fetchOpenCodeModels`
|
|
601
|
+
and `fetchQwenModels` already follow this; new dynamic fetchers must too.
|
|
602
|
+
|
|
603
|
+
### 4.6 Engine-specific config (presets — multi-provider / multi-region)
|
|
604
|
+
|
|
605
|
+
Anything else an engine needs that the frontend has to render — provider
|
|
606
|
+
choice, region selection, BYOK templates — also lives with the adapter
|
|
607
|
+
rather than `shared/constants/engines.ts`. The canonical filename is
|
|
608
|
+
`presets.ts` (see §2.6). Two adapters use this slot:
|
|
609
|
+
|
|
610
|
+
- **Qwen** (`backend/engine/adapters/qwen/presets.ts`) — `QWEN_PROVIDER_PRESETS`
|
|
611
|
+
array (DashScope CN/INTL, OpenRouter, Fireworks), `DEFAULT_QWEN_PRESET`,
|
|
612
|
+
`getQwenPreset(id)`. Static, hardcoded.
|
|
613
|
+
- **OpenCode** (`backend/engine/adapters/opencode/presets.ts`) — the
|
|
614
|
+
models.dev provider catalog: `fetchAndCacheModelsDevCatalog()` +
|
|
615
|
+
`getCachedModelsDevCatalog()`. Dynamic (fetched + cached in `settings`).
|
|
616
|
+
|
|
617
|
+
The wire-format types (`QwenProviderPresetId`, `QwenProviderPreset`,
|
|
618
|
+
`ModelsDevProvider`) live in `shared/types/unified/engine.ts` (or are
|
|
619
|
+
re-exported there) so the frontend stays typed without importing from
|
|
620
|
+
`$backend`.
|
|
621
|
+
|
|
622
|
+
Each adapter that has a `presets.ts` ships a thin WS router exposing it:
|
|
623
|
+
|
|
624
|
+
| Engine | WS event | Frontend store |
|
|
625
|
+
|-----------|------------------------------------------|---------------------------------------------------|
|
|
626
|
+
| `qwen` | `engine:qwen-presets-list` | `qwenPresetsStore` (`frontend/stores/features/qwen-presets.svelte.ts`) |
|
|
627
|
+
| `opencode`| `engine:opencode-models-dev-list` (+ `…-fetch` to refresh) | `opencodeProvidersStore.catalog` (`frontend/stores/features/opencode-providers.svelte.ts`) |
|
|
628
|
+
|
|
629
|
+
The rule: **frontend never imports `$backend` directly**. Runtime values
|
|
630
|
+
the frontend needs (model lists, presets, …) flow through WS endpoints;
|
|
631
|
+
types flow through `$shared`.
|
|
632
|
+
|
|
633
|
+
### 4.7 `chat:stream` — the streaming entry point
|
|
634
|
+
|
|
635
|
+
`backend/ws/chat/stream.ts` accepts:
|
|
636
|
+
|
|
637
|
+
```ts
|
|
638
|
+
{
|
|
639
|
+
sessionId: string,
|
|
640
|
+
chatSessionId: string,
|
|
641
|
+
projectPath: string,
|
|
642
|
+
prompt: UserMessage,
|
|
643
|
+
engine: { type, provider, model: { id, name }, account: { id, name } },
|
|
644
|
+
sender: { id, name }
|
|
645
|
+
}
|
|
646
|
+
```
|
|
647
|
+
|
|
648
|
+
The handler calls `streamManager.startStream(...)`, which then:
|
|
649
|
+
1. Resolves `getProjectEngine(projectId, engine.type)`
|
|
650
|
+
2. Calls `engine.streamQuery({ projectPath, prompt, providerSlug, modelId, accountId, mcpContext, ... })`
|
|
651
|
+
3. Iterates over `EngineOutput` and emits each one to the chat session room
|
|
652
|
+
via `ws.emit.chatSession(...)`.
|
|
653
|
+
|
|
654
|
+
---
|
|
655
|
+
|
|
656
|
+
## 5. Frontend — Settings UI
|
|
657
|
+
|
|
658
|
+
### 5.1 Settings → Engines
|
|
659
|
+
|
|
660
|
+
Files:
|
|
661
|
+
- `frontend/components/settings/engines/AIEnginesSettings.svelte`
|
|
662
|
+
- Stores: `frontend/stores/features/claude-accounts.svelte.ts`,
|
|
663
|
+
`frontend/stores/features/copilot-accounts.svelte.ts`,
|
|
664
|
+
`frontend/stores/features/opencode-providers.svelte.ts`
|
|
665
|
+
|
|
666
|
+
Pattern:
|
|
667
|
+
- The component renders one card **per engine** from the `ENGINES` constant
|
|
668
|
+
in `shared/constants/engines.ts` (icon, name, description).
|
|
669
|
+
- For **Claude**: calls `engine:claude-status`. The "Add Account" button
|
|
670
|
+
starts `engine:claude-account-setup-start` and renders an xterm terminal
|
|
671
|
+
for debug + to display the auth URL.
|
|
672
|
+
- For **Copilot**: calls `engine:copilot-status` and
|
|
673
|
+
`copilotAccountsStore.fetch()`. "Add Account" submits a GitHub PAT
|
|
674
|
+
directly via `engine:copilot-accounts-add` (no PTY required).
|
|
675
|
+
- For **OpenCode**: calls `engine:opencode-status` and
|
|
676
|
+
`opencodeProvidersStore.fetchProviders()`. "Add Provider" picks from the
|
|
677
|
+
`models.dev` catalog, fills in API key + extra env options (per
|
|
678
|
+
`catalogEntry.env[]`), and submits → `engine:opencode-provider-add`.
|
|
679
|
+
- After an account switch / restart: refresh the relevant store
|
|
680
|
+
(`claudeAccountsStore.refresh()` / `copilotAccountsStore.refresh()` /
|
|
681
|
+
`opencodeProvidersStore.refreshProviders()`) and call
|
|
682
|
+
`modelStore.refreshModels()` to stay in sync.
|
|
683
|
+
|
|
684
|
+
**Stores**:
|
|
685
|
+
```ts
|
|
686
|
+
claudeAccountsStore // accounts[], fetch(), refresh(), set(), reset()
|
|
687
|
+
copilotAccountsStore // accounts[], fetch(), refresh(), set(), reset()
|
|
688
|
+
// (identical API to claudeAccountsStore)
|
|
689
|
+
opencodeProvidersStore // providers[], catalog[], catalogCachedAt,
|
|
690
|
+
// fetchProviders/refreshProviders, addProvider,
|
|
691
|
+
// removeProvider, toggleProvider,
|
|
692
|
+
// updateProviderOptions,
|
|
693
|
+
// addAccount, switchAccount, deleteAccount,
|
|
694
|
+
// renameAccount,
|
|
695
|
+
// fetchCatalog, refreshCatalog, refetchCatalog,
|
|
696
|
+
// restartServer, reset
|
|
697
|
+
modelStore // models[], fetchModels(engine), refreshModels(engine),
|
|
698
|
+
// getByEngine(engine), getById(modelId)
|
|
699
|
+
```
|
|
700
|
+
|
|
701
|
+
### 5.2 Settings → System Tools
|
|
702
|
+
|
|
703
|
+
Files:
|
|
704
|
+
- `frontend/components/settings/system-tools/SystemToolsSettings.svelte`
|
|
705
|
+
- `frontend/components/settings/system-tools/ToolInstallCard.svelte`
|
|
706
|
+
|
|
707
|
+
`SystemToolsSettings` renders one `ToolInstallCard` per tool (`git`,
|
|
708
|
+
`claude`, `opencode`, `chrome`, `cloudflared`). `ToolInstallCard`:
|
|
709
|
+
|
|
710
|
+
1. Calls `system-tools:status` on mount.
|
|
711
|
+
2. Renders: status (installed/version/source), an "Install" button if
|
|
712
|
+
`recipe.autoInstallable`, otherwise a "Manual install" dialog.
|
|
713
|
+
3. While installing: `system-tools:install-start` → subscribe to
|
|
714
|
+
`system-tools:install-stream` (per-line) → render in xterm + show
|
|
715
|
+
exit status from `system-tools:install-finished`.
|
|
716
|
+
4. The session survives navigation: if `activeSession` exists on refresh,
|
|
717
|
+
re-attach to the same session id.
|
|
718
|
+
|
|
719
|
+
To add a new tool (e.g. `goose`):
|
|
720
|
+
1. Add the literal to `ToolId` (`backend/engine/install-recipes.ts`).
|
|
721
|
+
2. Add `resolveGooseRecipe()` + a case in `resolveRecipe()`.
|
|
722
|
+
3. Add the literal to `TOOL_UNION` (`backend/ws/system-tools/status.ts`
|
|
723
|
+
and `install.ts`).
|
|
724
|
+
4. Add `<ToolInstallCard tool="goose" title="Goose" description="…" />`
|
|
725
|
+
in `SystemToolsSettings.svelte`.
|
|
726
|
+
5. (Optional) expose detection in the `engine:<name>-status` handler so
|
|
727
|
+
Settings → Engines can show an "Installed" badge.
|
|
728
|
+
|
|
729
|
+
---
|
|
730
|
+
|
|
731
|
+
## 6. Chat integration — model picker & stream
|
|
732
|
+
|
|
733
|
+
### 6.1 chat-input state
|
|
734
|
+
|
|
735
|
+
`frontend/stores/ui/chat-model.svelte.ts` — `chatModelState`:
|
|
736
|
+
|
|
737
|
+
```ts
|
|
738
|
+
{ engine, provider, modelId, modelName,
|
|
739
|
+
engineModelMemory: { [engine]: { provider, id, name } },
|
|
740
|
+
accountId, accountName }
|
|
741
|
+
```
|
|
742
|
+
|
|
743
|
+
This store is **local to the active session**: settings under Settings →
|
|
744
|
+
Engines only seed the initial defaults via `initChatModel(...)`. Switching
|
|
745
|
+
engine/model in chat input does **not** affect Settings.
|
|
746
|
+
|
|
747
|
+
### 6.2 EngineModelPicker (in chat input)
|
|
748
|
+
|
|
749
|
+
`frontend/components/chat/input/components/EngineModelPicker.svelte`:
|
|
750
|
+
- Engine tabs from `ENGINES`.
|
|
751
|
+
- Model list from `modelStore.getByEngine(engine)` — auto-fetched via
|
|
752
|
+
`modelStore.fetchModels(engine)` whenever the engine changes.
|
|
753
|
+
- **Account picker for `claude-code` and `copilot`** (single-account-list
|
|
754
|
+
engines): both stores expose the same
|
|
755
|
+
`{ accounts, fetch, refresh, set, reset }` API, so a single dropdown
|
|
756
|
+
drives both. The component derives `accountsForEngine` from
|
|
757
|
+
`chatModelState.engine`, the chosen account is written into
|
|
758
|
+
`chatModelState.accountId` / `accountName`, and on send it is forwarded
|
|
759
|
+
as `engine.account.id` to the backend (see §6.3). To add a third engine
|
|
760
|
+
with this same shape, add a branch in `accountsForEngine`,
|
|
761
|
+
`accountPickerLabel`, `showAccountPicker`, and the auto-select `$effect`
|
|
762
|
+
— no new dropdown markup is needed.
|
|
763
|
+
- **OpenCode** has a separate picker because its accounts are scoped to a
|
|
764
|
+
provider, which is implied by the currently selected model. The picker
|
|
765
|
+
resolves the model's provider via `ocMatchingProvider`, then writes the
|
|
766
|
+
chosen account into `chatModelState.accountId` and triggers a server
|
|
767
|
+
restart.
|
|
768
|
+
|
|
769
|
+
### 6.3 Send path → backend
|
|
770
|
+
|
|
771
|
+
`frontend/services/chat/chat.service.ts` on submit:
|
|
772
|
+
|
|
773
|
+
```ts
|
|
774
|
+
ws.emit('chat:stream', {
|
|
775
|
+
sessionId: <ephemeral>,
|
|
776
|
+
chatSessionId: ...,
|
|
777
|
+
projectPath: ...,
|
|
778
|
+
prompt: <UserMessage>,
|
|
779
|
+
engine: {
|
|
780
|
+
type: chatModelState.engine,
|
|
781
|
+
provider: chatModelState.provider,
|
|
782
|
+
model: { id: chatModelState.modelId, name: chatModelState.modelName },
|
|
783
|
+
account: { id: chatModelState.accountId ?? 0, name: chatModelState.accountName ?? '' },
|
|
784
|
+
},
|
|
785
|
+
sender: { id, name }
|
|
786
|
+
});
|
|
787
|
+
```
|
|
788
|
+
|
|
789
|
+
Backend `chat:stream` then `streamManager.startStream(...)`, which:
|
|
790
|
+
- Resolves `getProjectEngine(projectId, engine.type)`
|
|
791
|
+
- Calls `engine.streamQuery({ projectPath, prompt, providerSlug: engine.provider, modelId: engine.model.id, accountId: engine.account.id !== 0 ? engine.account.id : undefined, mcpContext })`
|
|
792
|
+
- Yields `EngineOutput` → emits `chat:message` / `chat:partial` /
|
|
793
|
+
`chat:notification` to the session room.
|
|
794
|
+
|
|
795
|
+
> **`accountId !== 0`** is the convention for "use override". `0` means
|
|
796
|
+
> "fall back to the active account in DB". Account-aware adapters
|
|
797
|
+
> (`claude`, `copilot`) read this and override their per-stream credential
|
|
798
|
+
> accordingly.
|
|
799
|
+
|
|
800
|
+
### 6.4 Reasoning, attachments, AskUserQuestion
|
|
801
|
+
|
|
802
|
+
- **Reasoning**: an adapter must emit
|
|
803
|
+
`StreamLifecycleEvent { reasoning: true }` to mark start/stop of the
|
|
804
|
+
thinking block, then `TextDeltaEvent { reasoning: true }` for each delta.
|
|
805
|
+
The frontend renders these in a separate bubble.
|
|
806
|
+
- **Attachments**: `UserMessage.content` carries `text | image | document`
|
|
807
|
+
blocks. The adapter maps these to the SDK's format — Claude uses native
|
|
808
|
+
content blocks, OpenCode uses `extractPromptParts()` to
|
|
809
|
+
`data:<mime>;base64,...`.
|
|
810
|
+
- **AskUserQuestion**: a standard tool that the adapter must intercept.
|
|
811
|
+
Three patterns exist depending on what the SDK supports:
|
|
812
|
+
1. **In-process callback** (Claude) — `claude/stream.ts::canUseTool`
|
|
813
|
+
blocks the SDK until the user answers.
|
|
814
|
+
2. **SDK event + HTTP fallback** (OpenCode) — `opencode/stream.ts`
|
|
815
|
+
listens for `question.asked` and resolves via
|
|
816
|
+
`engine.resolveUserAnswer(toolUseId, answers)`.
|
|
817
|
+
3. **MCP tool** (engines whose SDK has neither, e.g. Codex) — the
|
|
818
|
+
question is exposed as an MCP tool registered via `defineServer()`;
|
|
819
|
+
the tool handler emits `chat:partial` and blocks on a Promise; the
|
|
820
|
+
answer arrives via a chat WS event that resolves the Promise from a
|
|
821
|
+
module-local registry. The flow is **engine-agnostic** — no
|
|
822
|
+
`resolveUserAnswer` method on the adapter. See §9.12.
|
|
823
|
+
|
|
824
|
+
---
|
|
825
|
+
|
|
826
|
+
## 7. Registering a binary in System Tools (`install-recipes.ts`)
|
|
827
|
+
|
|
828
|
+
`install-recipes.ts` is a **declarative** registry of install commands.
|
|
829
|
+
`install-runner.ts` is what actually runs them.
|
|
830
|
+
|
|
831
|
+
### 7.1 Anatomy of a `Recipe`
|
|
832
|
+
|
|
833
|
+
```ts
|
|
834
|
+
interface Recipe {
|
|
835
|
+
tool: ToolId;
|
|
836
|
+
autoInstallable: boolean;
|
|
837
|
+
unavailableReason?: string; // shown when not auto-installable
|
|
838
|
+
command?: string[]; // argv for Bun.spawn
|
|
839
|
+
shell?: { program; args }; // wrap argv (sh -c, pwsh -Command)
|
|
840
|
+
requiresCurl?: boolean; // staged static-curl if needed
|
|
841
|
+
pendingCurlDownload?: { version, url, sha256, archKey };
|
|
842
|
+
displayCommand?: string; // string for the confirm dialog
|
|
843
|
+
env?: Record<string, string>; // extra env for the subprocess
|
|
844
|
+
missingPrereqs: ToolId[];
|
|
845
|
+
manualInstructions: ManualInstruction[]; // always present (copy-able fallback)
|
|
846
|
+
}
|
|
847
|
+
```
|
|
848
|
+
|
|
849
|
+
### 7.2 Per-platform pattern
|
|
850
|
+
|
|
851
|
+
`resolveRecipe(tool)` switches to a per-tool resolver. Each resolver:
|
|
852
|
+
1. Builds `base: Recipe` with full `manualInstructions` (always provide a
|
|
853
|
+
fallback for users on unsupported OSes).
|
|
854
|
+
2. Checks platform (`process.platform`) and package manager:
|
|
855
|
+
- macOS: `brew`
|
|
856
|
+
- Linux: `apt | dnf | pacman | apk | zypper` (`detectLinuxPkgMgr`)
|
|
857
|
+
- Windows: `winget | scoop | choco` (`detectWindowsPkgMgr`)
|
|
858
|
+
3. Checks privilege via `isElevated()` if the package manager needs
|
|
859
|
+
root/admin.
|
|
860
|
+
4. If the installer uses `curl`, calls `attachCurlRequirement(base, label)`
|
|
861
|
+
so the runner can stage SHA-pinned static-curl from
|
|
862
|
+
`static-curl-assets.ts` when the system has no curl.
|
|
863
|
+
5. Sets `autoInstallable = true` + `command` + `shell` + `displayCommand`,
|
|
864
|
+
or leaves it `false` with `unavailableReason` so the UI renders manual
|
|
865
|
+
instructions only.
|
|
866
|
+
|
|
867
|
+
### 7.3 Status detection
|
|
868
|
+
|
|
869
|
+
`getToolStatus(tool)` returns `{ tool, installed, version, source }`:
|
|
870
|
+
- `chrome` has a special path (puppeteer cache scan + system Chrome).
|
|
871
|
+
- `cloudflared` at `~/.clopen/bin/cloudflared` is marked `source: 'clopen'`.
|
|
872
|
+
- Otherwise `resolveBinaryWithRefresh(tool)` + `runVersion(resolved)`.
|
|
873
|
+
|
|
874
|
+
### 7.4 Runner
|
|
875
|
+
|
|
876
|
+
`install-runner.ts::startInstall(tool, userId)`:
|
|
877
|
+
1. Verifies no other session is active for this tool
|
|
878
|
+
(`InstallAlreadyRunningError`).
|
|
879
|
+
2. Resolves the recipe, validates `autoInstallable && command`
|
|
880
|
+
(`InstallNotAutoInstallableError`).
|
|
881
|
+
3. If `requiresCurl`, calls `ensureCurlAvailable(...)` (downloads
|
|
882
|
+
pinned static-curl if needed, prepends its dir to PATH).
|
|
883
|
+
4. `Bun.spawn(spawnArgs, { stdout: 'pipe', stderr: 'pipe', stdin: 'ignore', env })`.
|
|
884
|
+
5. Streams stdout/stderr per-line into a ring buffer (10k lines) + emits
|
|
885
|
+
`system-tools:install-stream` to the user room.
|
|
886
|
+
6. On exit: emits `system-tools:install-finished` + retains the session
|
|
887
|
+
for 5 minutes for re-attach.
|
|
888
|
+
|
|
889
|
+
Exit-code hints (`explainFailure(137|143, cancelled)`) explain SIGKILL OOM
|
|
890
|
+
or SIGTERM with actual total/free memory readings.
|
|
891
|
+
|
|
892
|
+
### 7.5 Adding a new tool
|
|
893
|
+
|
|
894
|
+
1. Add the literal to `ToolId` (`'goose'`).
|
|
895
|
+
2. Write `resolveGooseRecipe(): Promise<Recipe>` following the
|
|
896
|
+
`resolveOpenCodeRecipe` pattern.
|
|
897
|
+
3. Add a case in `resolveRecipe(tool)`.
|
|
898
|
+
4. Add the literal to `TOOL_UNION` (`status.ts`, `install.ts`).
|
|
899
|
+
5. Add `<ToolInstallCard tool="goose" ... />` in
|
|
900
|
+
`SystemToolsSettings.svelte`.
|
|
901
|
+
6. (Optional) detect in `engine:<engine>-status` so Settings → Engines
|
|
902
|
+
knows the binary is installed.
|
|
903
|
+
|
|
904
|
+
---
|
|
905
|
+
|
|
906
|
+
## 8. End-to-end checklist for adding a new engine
|
|
907
|
+
|
|
908
|
+
The steps below are the same pattern used when the **`copilot`**
|
|
909
|
+
(`@github/copilot-sdk`) adapter was added to the repo. Use it as a
|
|
910
|
+
blueprint for the next engine you add.
|
|
911
|
+
|
|
912
|
+
### Stage 1 — Shared types
|
|
913
|
+
|
|
914
|
+
- [ ] `shared/types/unified/common.ts`: add `'newengine'` to `EngineType`.
|
|
915
|
+
- [ ] `shared/types/unified/engine.ts`: add `'newengine'` to `EngineInfo.type`.
|
|
916
|
+
- [ ] `shared/types/unified/message.ts`: add `'newengine'` to `MessageEngine.type`.
|
|
917
|
+
- [ ] `shared/constants/engines.ts`: add an entry in `ENGINES[]`
|
|
918
|
+
(`type, name, description, icon.light, icon.dark`).
|
|
919
|
+
- [ ] `backend/engine/adapters/newengine/models.ts`: own the catalog. Static
|
|
920
|
+
engines export a `NEWENGINE_MODELS: EngineModel[]` array; dynamic
|
|
921
|
+
engines export a fetcher (`fetchNewengineModels(...)`) consumed by
|
|
922
|
+
`getAvailableModels()`. Don't add anything to `shared/constants/engines.ts`
|
|
923
|
+
for the catalog itself — the frontend loads it via `models:list`.
|
|
924
|
+
- [ ] (Optional) `backend/engine/adapters/newengine/presets.ts` if the
|
|
925
|
+
engine needs provider/region/BYOK presets exposed to the UI.
|
|
926
|
+
Mirror `qwen/presets.ts`: keep runtime values in the adapter,
|
|
927
|
+
export wire types from `shared/types/unified/engine.ts`, and ship
|
|
928
|
+
a WS endpoint (see Stage 4) — never import these from frontend
|
|
929
|
+
via `$backend`.
|
|
930
|
+
|
|
931
|
+
### Stage 2 — Adapter `backend/engine/`
|
|
932
|
+
|
|
933
|
+
Refer to §2.6 for the full file taxonomy. Every adapter ships these five
|
|
934
|
+
mandatory files; optional files use the canonical names from §2.6.
|
|
935
|
+
|
|
936
|
+
- [ ] Create `backend/engine/adapters/newengine/`
|
|
937
|
+
- [ ] `index.ts` (mandatory) → `export { NewEngineEngine } from './stream';`
|
|
938
|
+
(+ `disposeXxxClient` if there is a subprocess).
|
|
939
|
+
- [ ] `stream.ts` (mandatory) → class `NewEngineEngine implements AIEngine`.
|
|
940
|
+
Pick a template: `claude/stream.ts` (in-process SDK),
|
|
941
|
+
`opencode/stream.ts` (subprocess), `copilot/stream.ts` (in-process
|
|
942
|
+
with construction-time credential), or `qwen/stream.ts` (CLI subprocess
|
|
943
|
+
via SDK with auth-blob swap).
|
|
944
|
+
- [ ] `models.ts` (mandatory) → static `NEWENGINE_MODELS: EngineModel[]`
|
|
945
|
+
OR `fetchNewengineModels(...): Promise<EngineModel[]>` (dynamic;
|
|
946
|
+
return `[]` on failure — see §4.5).
|
|
947
|
+
- [ ] `message-converter.ts` (mandatory) → pure functions SDK → `EngineOutput`.
|
|
948
|
+
Use `toCanonicalToolName()` for tool names.
|
|
949
|
+
- [ ] `error-handler.ts` (mandatory) → exports `handleStreamError(error,
|
|
950
|
+
...): void` (and any helper formatters specific to the SDK's error
|
|
951
|
+
payload — see `opencode/error-handler.ts::formatSessionError` for the
|
|
952
|
+
pattern).
|
|
953
|
+
- [ ] `credential.ts` / `environment.ts` / `server.ts` / `config.ts` /
|
|
954
|
+
`presets.ts` / `session-fork.ts` (optional; canonical names only).
|
|
955
|
+
- [ ] `backend/engine/index.ts`: import + add a case in
|
|
956
|
+
`createEngine(type)`. If there is a shared subprocess, call
|
|
957
|
+
`disposeXxxClient()` from `disposeAllProjectEngines()`.
|
|
958
|
+
|
|
959
|
+
### Stage 3 — Database (if a default provider needs to be seeded)
|
|
960
|
+
|
|
961
|
+
- [ ] Add a new migration in `backend/database/migrations/` (e.g. seed
|
|
962
|
+
`('newengine', 'vendor', 'Vendor', NULL, NULL, '{}', 1)` into
|
|
963
|
+
`engine_providers`). **Do not change the schema** — the tables
|
|
964
|
+
are already generic.
|
|
965
|
+
|
|
966
|
+
### Stage 4 — WebSocket `engine:newengine-*`
|
|
967
|
+
|
|
968
|
+
- [ ] Create `backend/ws/engine/newengine/`:
|
|
969
|
+
- `status.ts` — `engine:newengine-status` (`installed`, `version`, etc).
|
|
970
|
+
- `accounts.ts` or `providers.ts` — account/provider CRUD:
|
|
971
|
+
- List, add, switch, delete, rename.
|
|
972
|
+
- Setup flow: PTY (Claude-style) OR direct API-key/PAT input
|
|
973
|
+
(OpenCode/Copilot-style) depending on the SDK's auth mechanism.
|
|
974
|
+
- (Optional) `presets.ts` — `engine:newengine-presets-list` if the
|
|
975
|
+
adapter has a `presets.ts` module. See `backend/ws/engine/qwen/presets.ts`.
|
|
976
|
+
- `index.ts` — merge the sub-router.
|
|
977
|
+
- [ ] `backend/ws/engine/index.ts`: `.merge(newengineEngineRouter)`.
|
|
978
|
+
- [ ] `backend/ws/chat/stream.ts`: add the `'newengine'` literal to the
|
|
979
|
+
typebox schema for `engine.type`.
|
|
980
|
+
- [ ] `backend/ws/settings/crud.ts`: add the `'newengine'` literal to the
|
|
981
|
+
`models:list` typebox schema.
|
|
982
|
+
|
|
983
|
+
### Stage 5 — Frontend store
|
|
984
|
+
|
|
985
|
+
- [ ] Add `frontend/stores/features/newengine-accounts.svelte.ts` (or
|
|
986
|
+
`newengine-providers.svelte.ts` following OpenCode's style if the
|
|
987
|
+
engine is multi-provider). Mirror the pattern of
|
|
988
|
+
`claudeAccountsStore` / `copilotAccountsStore` / `opencodeProvidersStore`.
|
|
989
|
+
|
|
990
|
+
### Stage 6 — Settings → Engines
|
|
991
|
+
|
|
992
|
+
- [ ] Add a panel to `AIEnginesSettings.svelte`: the card appears
|
|
993
|
+
automatically since `ENGINES` already has the new entry. Implement
|
|
994
|
+
the setup flow:
|
|
995
|
+
- Load status via `ws.http('engine:newengine-status', {})`.
|
|
996
|
+
- Subscribe to server-emit events for login progress.
|
|
997
|
+
- After save: `newengineStore.refresh()` +
|
|
998
|
+
`modelStore.refreshModels('newengine')`.
|
|
999
|
+
|
|
1000
|
+
### Stage 7 — Settings → System Tools
|
|
1001
|
+
|
|
1002
|
+
- [ ] `backend/engine/install-recipes.ts`:
|
|
1003
|
+
- Add `'newengine'` to `ToolId`.
|
|
1004
|
+
- Write `resolveNewEngineRecipe()` (winget/brew/curl pipe — whatever the
|
|
1005
|
+
SDK needs to install its CLI).
|
|
1006
|
+
- Add a case in `resolveRecipe()`.
|
|
1007
|
+
- [ ] `backend/ws/system-tools/status.ts` & `install.ts`: add
|
|
1008
|
+
`'newengine'` to `TOOL_UNION`.
|
|
1009
|
+
- [ ] `frontend/components/settings/system-tools/SystemToolsSettings.svelte`:
|
|
1010
|
+
`<ToolInstallCard tool="newengine" title="NewEngine CLI" description="..." />`.
|
|
1011
|
+
|
|
1012
|
+
### Stage 8 — Chat input
|
|
1013
|
+
|
|
1014
|
+
If the engine uses one-account-per-engine (Claude/Copilot style), wire it
|
|
1015
|
+
into `EngineModelPicker.svelte`:
|
|
1016
|
+
|
|
1017
|
+
- [ ] Import the new store + add a branch to `accountsForEngine`,
|
|
1018
|
+
`accountPickerLabel`, `showAccountPicker`, and the two
|
|
1019
|
+
`$effect` blocks (auto-fetch and auto-select active account).
|
|
1020
|
+
- [ ] No new dropdown markup is required — the existing dropdown iterates
|
|
1021
|
+
`accountsForEngine`.
|
|
1022
|
+
|
|
1023
|
+
If the engine is multi-provider (OpenCode style) the picker logic is
|
|
1024
|
+
heavier — copy the OpenCode block.
|
|
1025
|
+
|
|
1026
|
+
Other auto wiring:
|
|
1027
|
+
- [ ] The engine tab appears automatically in `EngineModelPicker` from
|
|
1028
|
+
`ENGINES`.
|
|
1029
|
+
- [ ] Verify: select engine → model list appears → send message → stream
|
|
1030
|
+
runs.
|
|
1031
|
+
|
|
1032
|
+
### Stage 9 — Manual QA
|
|
1033
|
+
|
|
1034
|
+
From the project root:
|
|
1035
|
+
|
|
1036
|
+
```sh
|
|
1037
|
+
bun run check && bun run lint
|
|
1038
|
+
```
|
|
1039
|
+
|
|
1040
|
+
Then the minimum UI scenarios that must pass:
|
|
1041
|
+
|
|
1042
|
+
- [ ] Settings → System Tools → Install NewEngine CLI → exit 0.
|
|
1043
|
+
- [ ] Settings → Engines → NewEngine → Add Account → status `Installed,
|
|
1044
|
+
Active account: <name>`.
|
|
1045
|
+
- [ ] Chat input → pick NewEngine + model → send a message → assistant
|
|
1046
|
+
replies → cancel mid-stream → idle → send again → resume works.
|
|
1047
|
+
- [ ] AskUserQuestion (if the SDK supports it) → appears in UI → submit
|
|
1048
|
+
answer → stream continues.
|
|
1049
|
+
- [ ] Restart Clopen → state survives (account, provider, last-used model
|
|
1050
|
+
in chat).
|
|
1051
|
+
|
|
1052
|
+
---
|
|
1053
|
+
|
|
1054
|
+
## 9. Lessons learned — pitfalls when authoring a new adapter
|
|
1055
|
+
|
|
1056
|
+
These notes come from building the `copilot` adapter. Each item has been
|
|
1057
|
+
gotten wrong at least once — keep this mental checklist in your head when
|
|
1058
|
+
writing the next adapter.
|
|
1059
|
+
|
|
1060
|
+
### 9.1 Both tool name **and** tool input must be canonicalised
|
|
1061
|
+
|
|
1062
|
+
`toCanonicalToolName()` only guarantees the tool name does not become
|
|
1063
|
+
`Unknown:*`. That is **not enough**: tool UI components (`Bash`, `Read`,
|
|
1064
|
+
`Edit`, …) read specific fields (`command`, `filePath`, `oldString`, …).
|
|
1065
|
+
Other SDKs use `snake_case` (`file_path`, `old_str`) or even bundle
|
|
1066
|
+
multiple subcommands under a single name (e.g. Copilot's
|
|
1067
|
+
`str_replace_editor` → split into `view`/`create`/`str_replace`/`edit`/`insert`).
|
|
1068
|
+
|
|
1069
|
+
The pattern used in `copilot/message-converter.ts`:
|
|
1070
|
+
|
|
1071
|
+
```ts
|
|
1072
|
+
// 1. Map raw name → canonical UI name (snake → PascalCase + dispatch subcommand).
|
|
1073
|
+
const COPILOT_TOOL_NAME_MAP: Record<string, string> = { 'bash': 'Bash', ... };
|
|
1074
|
+
function mapCopilotToolName(rawName, mcpServerName) { ... }
|
|
1075
|
+
|
|
1076
|
+
// 2. Per-tool normaliser: takes Record<string, unknown>, returns canonical shape.
|
|
1077
|
+
function normalizeReadInput(raw): ReadInput {
|
|
1078
|
+
// path → filePath, view_range:[s,e] → offset/limit, etc.
|
|
1079
|
+
}
|
|
1080
|
+
|
|
1081
|
+
// 3. Dispatcher called from buildToolUseBlock.
|
|
1082
|
+
function normalizeCopilotToolInput(canonical, raw) {
|
|
1083
|
+
switch (canonical) { case 'Read': return normalizeReadInput(raw); ... }
|
|
1084
|
+
}
|
|
1085
|
+
```
|
|
1086
|
+
|
|
1087
|
+
If only the name mapping is done, the UI still picks the right component
|
|
1088
|
+
but the fields are `undefined` → the user sees an empty block. Always
|
|
1089
|
+
install **both** layers.
|
|
1090
|
+
|
|
1091
|
+
### 9.2 Filter the SDK's "harness tools"
|
|
1092
|
+
|
|
1093
|
+
Some SDKs emit internal tools used for model↔harness coordination that
|
|
1094
|
+
**must not** appear in chat (intent reporting, task-completion markers,
|
|
1095
|
+
internal documentation). Examples from Copilot CLI: `report_intent`,
|
|
1096
|
+
`task_complete`, `propose_work`, `fetch_copilot_cli_documentation`.
|
|
1097
|
+
|
|
1098
|
+
Strategy: filter at the adapter boundary, do not render `Unknown:*`. See
|
|
1099
|
+
`copilot/message-converter.ts::IGNORED_COPILOT_TOOLS` +
|
|
1100
|
+
`isIgnoredCopilotTool()`. Drop **both sides**: the tool_use (in
|
|
1101
|
+
`convertAssistantMessage`) **and** the tool_result that arrives later (in
|
|
1102
|
+
`convertToolComplete`) — if you only drop one side, the UI either gets an
|
|
1103
|
+
orphan result without a tool or an orphan tool without a result.
|
|
1104
|
+
|
|
1105
|
+
### 9.3 One `tool_use` per `AssistantMessage`
|
|
1106
|
+
|
|
1107
|
+
The convention used by Claude and OpenCode: each assistant message that
|
|
1108
|
+
reaches the frontend has **at most one** `tool_use` block. SDKs like
|
|
1109
|
+
Copilot CLI may send a single `assistant.message` with many `toolRequests`
|
|
1110
|
+
— the adapter must split it.
|
|
1111
|
+
|
|
1112
|
+
Pattern:
|
|
1113
|
+
```ts
|
|
1114
|
+
const blocks: AssistantContentBlock[] = [];
|
|
1115
|
+
if (data.content) blocks.push({ type: 'text', text: data.content });
|
|
1116
|
+
for (const req of visibleToolRequests) blocks.push(buildToolUseBlock(req));
|
|
1117
|
+
|
|
1118
|
+
const messages = blocks.map((block, idx) => ({
|
|
1119
|
+
type: 'assistant',
|
|
1120
|
+
messageId: blocks.length === 1 ? baseId : `${baseId}:${idx}`,
|
|
1121
|
+
content: [block], // one block per message
|
|
1122
|
+
...
|
|
1123
|
+
}));
|
|
1124
|
+
```
|
|
1125
|
+
|
|
1126
|
+
If violated, the frontend `message-grouper` still works but Compact mode
|
|
1127
|
+
and the tool layout do not stitch correctly.
|
|
1128
|
+
|
|
1129
|
+
### 9.4 Buffer messages until the usage event arrives
|
|
1130
|
+
|
|
1131
|
+
In many SDKs (Copilot included), `assistant.usage` is a **separate** event
|
|
1132
|
+
that arrives **after** `assistant.message` for the same turn iteration.
|
|
1133
|
+
If the adapter yields the message immediately, the `usage` field is
|
|
1134
|
+
always `null` in the DB and in the token-cost dashboard.
|
|
1135
|
+
|
|
1136
|
+
Buffering pattern in `copilot/message-converter.ts`:
|
|
1137
|
+
|
|
1138
|
+
```ts
|
|
1139
|
+
// State:
|
|
1140
|
+
pendingMessages: UnifiedAssistantMessage[];
|
|
1141
|
+
lastUsage: AssistantUsageData | null;
|
|
1142
|
+
|
|
1143
|
+
// convertAssistantMessage: push to pending, return what was already flushed.
|
|
1144
|
+
state.pendingMessages.push(...messages);
|
|
1145
|
+
return flushPending(state); // flush old queue, leave the new ones waiting
|
|
1146
|
+
|
|
1147
|
+
// captureUsage: attach to the last pending, then flush.
|
|
1148
|
+
state.pendingMessages.at(-1)!.usage = mapUsage(data);
|
|
1149
|
+
return flushPending(state);
|
|
1150
|
+
|
|
1151
|
+
// flushPending also has a fallback: if a pending message still has
|
|
1152
|
+
// usage == null but state.lastUsage is set, fill it in. This covers
|
|
1153
|
+
// turns where the SDK emits assistant.message after assistant.usage,
|
|
1154
|
+
// or tool-only iterations whose usage event landed earlier.
|
|
1155
|
+
//
|
|
1156
|
+
// Defensive flush at tool.execution_complete, turn_end, session.idle —
|
|
1157
|
+
// preserve ordering even when the SDK sends events out of order.
|
|
1158
|
+
```
|
|
1159
|
+
|
|
1160
|
+
The `lastUsage` state is also kept around to build the aggregate
|
|
1161
|
+
`ResultEvent` at `session.idle` — that is the **per-stream** usage, not
|
|
1162
|
+
per-message.
|
|
1163
|
+
|
|
1164
|
+
### 9.5 `tool_use.result: null` is **expected** before render
|
|
1165
|
+
|
|
1166
|
+
When inspecting raw adapter output (e.g. logs or DB rows before render),
|
|
1167
|
+
`tool_use` blocks always carry `result: null`. That is **correct**: the
|
|
1168
|
+
tool_result arrives as a synthetic `UserMessage` with `toolUseId`. The
|
|
1169
|
+
frontend `message-grouper.ts` (via `processToolMessage` + `toolUseMap`)
|
|
1170
|
+
attaches it at display time.
|
|
1171
|
+
|
|
1172
|
+
Do not try to perform that stitching in the adapter — if you do, the
|
|
1173
|
+
`stream-manager` loses the chance to persist the tool_result as its own
|
|
1174
|
+
DB row, and resume-session breaks.
|
|
1175
|
+
|
|
1176
|
+
**Sharp edge — `parent.toolUseId` MUST be null on the synthetic
|
|
1177
|
+
UserMessage.** The toolCallId belongs only on the inner `tool_result`
|
|
1178
|
+
block, never on the message-level `parent.toolUseId`. The frontend
|
|
1179
|
+
grouper interprets any user message with `parent.toolUseId !== null` as
|
|
1180
|
+
a **sub-agent message** (i.e. one emitted from inside an `Agent` /
|
|
1181
|
+
`Task` tool execution): if the parent id matches an Agent tool it goes
|
|
1182
|
+
into the sub-agent activity bucket, otherwise it is silently dropped.
|
|
1183
|
+
Setting `parent.toolUseId = data.toolCallId` therefore makes the
|
|
1184
|
+
tool_result invisible to the UI and `tool_use.result` stays null after
|
|
1185
|
+
render.
|
|
1186
|
+
|
|
1187
|
+
```ts
|
|
1188
|
+
// ✅ correct — top-level tool_result (Claude, OpenCode, Copilot)
|
|
1189
|
+
parent: { messageId: null, sessionId: null, toolUseId: null }
|
|
1190
|
+
|
|
1191
|
+
// ❌ wrong — frontend grouper drops this as a "sub-agent" message
|
|
1192
|
+
parent: { messageId: null, sessionId: null, toolUseId: data.toolCallId }
|
|
1193
|
+
```
|
|
1194
|
+
|
|
1195
|
+
Only set `parent.toolUseId` when the message is genuinely a child of an
|
|
1196
|
+
`Agent` / `Task` tool execution (e.g. the OpenCode Task adapter passes
|
|
1197
|
+
`parentToolUseId` through `convertToolResultOnly`). For raw
|
|
1198
|
+
`tool.execution_complete` events at the top of the loop, leave it null.
|
|
1199
|
+
|
|
1200
|
+
### 9.6 Enable the SDK's streaming flag explicitly
|
|
1201
|
+
|
|
1202
|
+
Some SDKs default to emitting only the final message. For delta/partial
|
|
1203
|
+
streaming you must set the SDK-specific flag:
|
|
1204
|
+
|
|
1205
|
+
- Copilot: `streaming: true` in `SessionConfig` & `ResumeSessionConfig`.
|
|
1206
|
+
- OpenCode: `partial: true` in chat options.
|
|
1207
|
+
- Claude: `includePartialMessages: true` (already on by default in
|
|
1208
|
+
`ClaudeCodeEngine.streamQuery`).
|
|
1209
|
+
|
|
1210
|
+
Without the flag, the UI shows text "all at once" — the symptom is
|
|
1211
|
+
identical to an adapter that forgot to emit `StreamLifecycleEvent` /
|
|
1212
|
+
`TextDeltaEvent`, so check the flag first before debugging the converter.
|
|
1213
|
+
|
|
1214
|
+
### 9.7 Pair `start`/`stop` lifecycle for reasoning
|
|
1215
|
+
|
|
1216
|
+
The frontend stream-manager renders reasoning in a separate bubble
|
|
1217
|
+
**only** while `StreamLifecycleEvent { reasoning: true, event: 'start' }`
|
|
1218
|
+
is open. Always emit `stop` when reasoning ends (or when assistant text
|
|
1219
|
+
begins — the two are mutually exclusive in the UI). See
|
|
1220
|
+
`copilot/message-converter.ts::convertReasoningDelta`, which flushes the
|
|
1221
|
+
text stream before opening the reasoning stream.
|
|
1222
|
+
|
|
1223
|
+
### 9.8 Event-order debug workflow
|
|
1224
|
+
|
|
1225
|
+
If chat output looks weird, log the raw `SessionEvent` per stream before
|
|
1226
|
+
the converter. The canonical Copilot order is:
|
|
1227
|
+
|
|
1228
|
+
```
|
|
1229
|
+
session.start
|
|
1230
|
+
assistant.turn_start
|
|
1231
|
+
[assistant.reasoning_delta...] assistant.reasoning
|
|
1232
|
+
[assistant.message_delta...] assistant.message assistant.usage
|
|
1233
|
+
tool.execution_start
|
|
1234
|
+
tool.execution_complete
|
|
1235
|
+
[loop back to reasoning/message for the next turn iteration]
|
|
1236
|
+
assistant.turn_end
|
|
1237
|
+
session.idle
|
|
1238
|
+
```
|
|
1239
|
+
|
|
1240
|
+
From here it is easy to trace: if `usage` is always null, buffering is
|
|
1241
|
+
wrong. If you see orphan tool_results, the ignored-tools filter is not
|
|
1242
|
+
consistent on both sides. If text appears all at once, the SDK streaming
|
|
1243
|
+
flag is off.
|
|
1244
|
+
|
|
1245
|
+
### 9.9 Per-stream account override when the SDK takes the credential at construction
|
|
1246
|
+
|
|
1247
|
+
Most SDKs accept env vars per-call (Claude) or read them from the
|
|
1248
|
+
subprocess environment (OpenCode). The Copilot SDK is different: the
|
|
1249
|
+
GitHub token is passed to `new CopilotClient({ gitHubToken })` at
|
|
1250
|
+
construction time and cannot be swapped on the fly.
|
|
1251
|
+
|
|
1252
|
+
Pattern in `copilot/stream.ts`:
|
|
1253
|
+
|
|
1254
|
+
```ts
|
|
1255
|
+
private currentAccountId: number | null = null;
|
|
1256
|
+
|
|
1257
|
+
async initialize(accountId?: number): Promise<void> {
|
|
1258
|
+
if (this._isInitialized && (accountId == null || accountId === this.currentAccountId)) {
|
|
1259
|
+
return; // already initialised with this account → no-op
|
|
1260
|
+
}
|
|
1261
|
+
const account = accountId != null
|
|
1262
|
+
? engineQueries.getAccount(accountId)
|
|
1263
|
+
: engineQueries.getActiveAccountForEngine('copilot');
|
|
1264
|
+
this.client = new CopilotClient({ gitHubToken: account.credential, ... });
|
|
1265
|
+
this.currentAccountId = account.id;
|
|
1266
|
+
...
|
|
1267
|
+
}
|
|
1268
|
+
|
|
1269
|
+
async *streamQuery(options) {
|
|
1270
|
+
// Per-stream account override: dispose + re-init when it differs.
|
|
1271
|
+
if (this._isInitialized && options.accountId != null
|
|
1272
|
+
&& options.accountId !== this.currentAccountId) {
|
|
1273
|
+
await this.dispose();
|
|
1274
|
+
}
|
|
1275
|
+
if (!this._isInitialized) await this.initialize(options.accountId);
|
|
1276
|
+
...
|
|
1277
|
+
}
|
|
1278
|
+
```
|
|
1279
|
+
|
|
1280
|
+
The frontend wiring is shared with Claude (single-account-list engines —
|
|
1281
|
+
see §6.2): both stores expose the same API, so `EngineModelPicker.svelte`
|
|
1282
|
+
uses one derived `accountsForEngine` and one dropdown. To add a fourth
|
|
1283
|
+
adapter that follows this same pattern, just add a branch in the four
|
|
1284
|
+
derived values and the `$effect` blocks; do not duplicate the dropdown.
|
|
1285
|
+
|
|
1286
|
+
If you forget the per-stream override path, the chat input appears to
|
|
1287
|
+
honour the account picker but the engine actually streams against the
|
|
1288
|
+
last initialised credential — silently using the wrong PAT/quota.
|
|
1289
|
+
|
|
1290
|
+
### 9.10 Fork session — native API vs. on-disk workaround
|
|
1291
|
+
|
|
1292
|
+
The multi-branch checkpoints feature requires that **every** resume
|
|
1293
|
+
spawn a fresh session id, so the engine continues from that point
|
|
1294
|
+
**without** mutating the original session's history. Each adapter wires
|
|
1295
|
+
it differently, but the contract is the same: fork unconditionally on
|
|
1296
|
+
resume.
|
|
1297
|
+
|
|
1298
|
+
| Adapter | How |
|
|
1299
|
+
|-----------|----------------------------------------------------------------------------------------------|
|
|
1300
|
+
| Claude | Pass `forkSession: true` in the SDK options on every call — native. |
|
|
1301
|
+
| OpenCode | Call `client.session.fork({ path: { id: resume } })` on every resume — native. |
|
|
1302
|
+
| Copilot | **No native API yet** — fork by copying the on-disk session-state DIRECTORY on every resume. |
|
|
1303
|
+
| Codex | **No native API yet** — fork by copying the rollout JSONL FILE on every resume. |
|
|
1304
|
+
| Qwen Code | **No native API yet** — fork by copying the chat JSONL FILE on every resume. |
|
|
1305
|
+
|
|
1306
|
+
> **Sharp edge — fork is NOT gated on `EngineQueryOptions.forkSession`.**
|
|
1307
|
+
> The `forkSession` field exists on the type but the stream-manager
|
|
1308
|
+
> never sets it; Claude/OpenCode hard-code their fork call. Every other
|
|
1309
|
+
> adapter must do the same. If you only fork "when forkSession is true"
|
|
1310
|
+
> the same session id is reused across every turn (visible in persisted
|
|
1311
|
+
> assistant messages) and downstream branch logic breaks.
|
|
1312
|
+
|
|
1313
|
+
The three on-disk workarounds all follow the same shape — copy the
|
|
1314
|
+
state, replace the source id with a fresh one, then resume against the
|
|
1315
|
+
fork — but the SDKs lay state out differently. Get the layout wrong and
|
|
1316
|
+
`sessionStateExists()` silently returns false on every turn, the fork
|
|
1317
|
+
block is skipped, and the engine resumes the original session — exactly
|
|
1318
|
+
the symptom multi-branch checkpoints surface as.
|
|
1319
|
+
|
|
1320
|
+
**Copilot — directory layout.** Tracking issues:
|
|
1321
|
+
github/copilot-cli#1313, #1697, #2058. State lives in a directory:
|
|
1322
|
+
|
|
1323
|
+
```
|
|
1324
|
+
~/.copilot/session-state/<sessionId>/
|
|
1325
|
+
├── workspace.yaml ← first line: `id: <sessionId>` ← rewrite
|
|
1326
|
+
├── events.jsonl ← first event session.start.data.sessionId ← rewrite
|
|
1327
|
+
├── checkpoints/
|
|
1328
|
+
├── files/
|
|
1329
|
+
└── research/
|
|
1330
|
+
```
|
|
1331
|
+
|
|
1332
|
+
Both `workspace.yaml#id` and the first `events.jsonl` line's
|
|
1333
|
+
`data.sessionId` must be replaced with the new fork id. After that,
|
|
1334
|
+
`client.resumeSession(forkId, ...)` picks the directory up as a fresh
|
|
1335
|
+
independent session.
|
|
1336
|
+
|
|
1337
|
+
**Codex — single rollout JSONL in a date-tree.** The thread id is in
|
|
1338
|
+
the filename, not a directory name:
|
|
1339
|
+
|
|
1340
|
+
```
|
|
1341
|
+
~/.codex/sessions/<YYYY>/<MM>/<DD>/rollout-<TIMESTAMP>-<thread_id>.jsonl
|
|
1342
|
+
```
|
|
1343
|
+
|
|
1344
|
+
The fork helper walks the date-tree to find the source by
|
|
1345
|
+
`-<thread_id>.jsonl` suffix, copies it into TODAY's `YYYY/MM/DD` dir
|
|
1346
|
+
under a new `rollout-<now>-<forkId>.jsonl` filename, and replaces every
|
|
1347
|
+
occurrence of the source id (UUIDs don't collide with other content in
|
|
1348
|
+
the file). Earlier versions of `codex/session-fork.ts` mistakenly
|
|
1349
|
+
assumed a directory layout (`~/.codex/sessions/<thread_id>/`) — the
|
|
1350
|
+
result was a permanently-broken fork because `sessionStateExists()`
|
|
1351
|
+
never matched. If you change the helper, watch for that regression.
|
|
1352
|
+
|
|
1353
|
+
**Qwen Code — single chat JSONL keyed by sanitised cwd.** The chat id
|
|
1354
|
+
is the filename basename; the parent directory is derived from the
|
|
1355
|
+
project's cwd via the SDK's `sanitizeCwd()`
|
|
1356
|
+
(`cwd.replace(/[^a-zA-Z0-9]/g, '-')`, lowercased on win32):
|
|
1357
|
+
|
|
1358
|
+
```
|
|
1359
|
+
~/.qwen/projects/<sanitized-cwd>/chats/<sessionId>.jsonl
|
|
1360
|
+
```
|
|
1361
|
+
|
|
1362
|
+
Every record line carries a `sessionId` field equal to the file's
|
|
1363
|
+
basename. The fork helper copies the file to
|
|
1364
|
+
`<chats>/<forkId>.jsonl` in the same project directory and replaces
|
|
1365
|
+
the source id throughout. The Qwen `session-fork.ts` therefore takes
|
|
1366
|
+
`projectPath` as an extra argument — Codex and Copilot are
|
|
1367
|
+
cwd-agnostic because their layouts aren't keyed on it.
|
|
1368
|
+
|
|
1369
|
+
```ts
|
|
1370
|
+
// stream.ts (resume path) — fork on EVERY resume; pattern is identical
|
|
1371
|
+
// across copilot/codex/qwen, only the helper signature differs.
|
|
1372
|
+
let resumeId = resume;
|
|
1373
|
+
if (resume && sessionStateExists(/* projectPath if qwen, */ resume)) {
|
|
1374
|
+
const forkId = crypto.randomUUID();
|
|
1375
|
+
if (forkXxxSessionState(/* projectPath if qwen, */ resume, forkId)) {
|
|
1376
|
+
resumeId = forkId;
|
|
1377
|
+
}
|
|
1378
|
+
}
|
|
1379
|
+
// then pass resumeId to the SDK's resume entry point.
|
|
1380
|
+
```
|
|
1381
|
+
|
|
1382
|
+
The expected effect, observable by logging the session/thread id per
|
|
1383
|
+
turn:
|
|
1384
|
+
|
|
1385
|
+
```
|
|
1386
|
+
turn 1 user → assistant sessionId: A
|
|
1387
|
+
turn 2 user → assistant sessionId: B (forked from A)
|
|
1388
|
+
turn 3 user → assistant sessionId: C (forked from B)
|
|
1389
|
+
```
|
|
1390
|
+
|
|
1391
|
+
Every assistant message carries its **own** session id. Reusing the
|
|
1392
|
+
same id across turns is the symptom that forking is gated or skipped.
|
|
1393
|
+
|
|
1394
|
+
When an SDK eventually adds a native `forkSession` (or equivalent), the
|
|
1395
|
+
migration is a one-liner: delete that adapter's `session-fork.ts`, drop
|
|
1396
|
+
the fork block in `stream.ts`, and pass the SDK flag the same way
|
|
1397
|
+
Claude and OpenCode already do. The `// TODO` comment at the top of
|
|
1398
|
+
each `session-fork.ts` pins the migration target.
|
|
1399
|
+
|
|
1400
|
+
### 9.11 Reset `currentAccountId` in `dispose()`
|
|
1401
|
+
|
|
1402
|
+
Whenever you track per-init state on the engine (e.g.
|
|
1403
|
+
`currentAccountId`, cached models, the SDK client itself), reset every
|
|
1404
|
+
field in `dispose()`. A half-disposed engine that still reports
|
|
1405
|
+
`isInitialized = false` but holds a stale `currentAccountId` will short-
|
|
1406
|
+
circuit the next `initialize(accountId)` call and reuse the wrong
|
|
1407
|
+
credential.
|
|
1408
|
+
|
|
1409
|
+
```ts
|
|
1410
|
+
async dispose(): Promise<void> {
|
|
1411
|
+
await this.cancel();
|
|
1412
|
+
if (this.client) await this.client.stop();
|
|
1413
|
+
this.client = null;
|
|
1414
|
+
this.modelsCache = null;
|
|
1415
|
+
this.currentAccountId = null; // ← do not forget
|
|
1416
|
+
this._isInitialized = false;
|
|
1417
|
+
}
|
|
1418
|
+
```
|
|
1419
|
+
|
|
1420
|
+
### 9.12 Reuse the existing MCP HTTP infrastructure — never build a new bridge
|
|
1421
|
+
|
|
1422
|
+
`backend/mcp/remote-server.ts` already mounts every server registered via
|
|
1423
|
+
`defineServer()` as a **Streamable HTTP MCP** endpoint at
|
|
1424
|
+
`http://localhost:<port>/mcp`. OpenCode consumes it via
|
|
1425
|
+
`getOpenCodeMcpConfig()`. Tool handlers run **in-process** in the Clopen
|
|
1426
|
+
backend — there is no subprocess, no per-engine HTTP listener, no
|
|
1427
|
+
per-stream MCP path. Project context propagates via
|
|
1428
|
+
`projectContextService` (AsyncLocalStorage with a `mostRecentActiveStream`
|
|
1429
|
+
fallback when the transport doesn't preserve the context).
|
|
1430
|
+
|
|
1431
|
+
When you add an engine whose CLI/SDK accepts a streamable-http MCP URL
|
|
1432
|
+
(e.g. Codex, Copilot):
|
|
1433
|
+
|
|
1434
|
+
1. Add a sibling helper next to `getOpenCodeMcpConfig()` —
|
|
1435
|
+
`getXxxMcpConfig()` — that returns the **same** URL in the engine's
|
|
1436
|
+
expected shape (Codex format: `{ '<server-name>': { url: '...' } }`;
|
|
1437
|
+
Copilot format: `{ '<server-name>': { type: 'http', url: '...', tools: [...] } }`).
|
|
1438
|
+
The engine sees every enabled MCP server (`browser-automation`,
|
|
1439
|
+
`weather-service`, …) as one logical MCP server namespace exposing all
|
|
1440
|
+
the tools.
|
|
1441
|
+
|
|
1442
|
+
**Naming conventions for the helper** (mirror the existing two so the
|
|
1443
|
+
reviewer doesn't ping you twice):
|
|
1444
|
+
- Use the SDK's **exported type** for the return shape if one exists
|
|
1445
|
+
— e.g. Open Code's `McpRemoteConfig` from `@opencode-ai/sdk`,
|
|
1446
|
+
Copilot's `MCPHTTPServerConfig` from `@github/copilot-sdk`. Only
|
|
1447
|
+
define a local type alias when the SDK doesn't export one (Codex).
|
|
1448
|
+
- Reuse the `'clopen-mcp'` namespace key. Don't invent a new one
|
|
1449
|
+
per engine — the tool-name resolver below depends on it.
|
|
1450
|
+
- In the adapter, name the local variable holding the helper's return
|
|
1451
|
+
value **`mcpConfig`**, not `mcpServers`. The latter shadows both the
|
|
1452
|
+
SDK's config field name AND the registry exported from
|
|
1453
|
+
`backend/mcp/config.ts`, and reads as a bug at the call site.
|
|
1454
|
+
|
|
1455
|
+
2. Use `resolveOpenCodeToolName()` (in `backend/mcp/config.ts`) on
|
|
1456
|
+
incoming tool names; it strips the `clopen-mcp_` / `clopen-mcp-`
|
|
1457
|
+
prefix and reverse-maps to `mcp__<server>__<tool>`. The same helper
|
|
1458
|
+
works for any engine that uses the same naming convention.
|
|
1459
|
+
|
|
1460
|
+
**Engines DO NOT agree on the prefix separator.** Open Code joins the
|
|
1461
|
+
server-config key to the tool name with `_` (`clopen-mcp_open_new_tab`);
|
|
1462
|
+
Copilot joins with `-` (`clopen-mcp-open_new_tab`); Codex emits a bare
|
|
1463
|
+
tool name and carries the server name separately on the event payload.
|
|
1464
|
+
`resolveOpenCodeToolName()` strips **both** `clopen-mcp_` and
|
|
1465
|
+
`clopen-mcp-` prefixes for this reason. If a new engine introduces yet
|
|
1466
|
+
another separator, extend the prefix list in that helper — do **not**
|
|
1467
|
+
add a parallel resolver in the adapter.
|
|
1468
|
+
|
|
1469
|
+
The symptom of skipping this step is a tool that renders in the UI
|
|
1470
|
+
with the doubled-up name `mcp__clopen-mcp__clopen-mcp-<tool>` instead
|
|
1471
|
+
of `mcp__<server>__<tool>` — the prefix didn't strip and the registry
|
|
1472
|
+
lookup fell through to the `mcp__<mcpServerName>__<rawName>` fallback.
|
|
1473
|
+
|
|
1474
|
+
3. If your engine has **no callback hook** for AskUserQuestion (Codex's
|
|
1475
|
+
SDK is the canonical example), AskUserQuestion stays unsupported for
|
|
1476
|
+
that engine until the upstream SDK exposes a native primitive. The
|
|
1477
|
+
previous engine-agnostic MCP fallback (`ask-user-question` tool +
|
|
1478
|
+
stream-keyed pending registry) was removed once the carrying cost —
|
|
1479
|
+
AsyncLocalStorage plumbing, dual resolve paths in
|
|
1480
|
+
`backend/ws/chat/stream.ts`, manual cancel-aborts — outweighed the
|
|
1481
|
+
benefit. Wire the engine's native hook to `resolveUserAnswer` when it
|
|
1482
|
+
ships; do not reintroduce a parallel MCP path.
|
|
1483
|
+
|
|
1484
|
+
4. Auto-approval of MCP tool calls is **per-engine**, not centralised.
|
|
1485
|
+
Each SDK exposes its own approval surface and they are not
|
|
1486
|
+
interchangeable:
|
|
1487
|
+
- Claude Code: `canUseTool` returns `{ behavior: 'allow' }` for all
|
|
1488
|
+
non-AskUserQuestion tools (already handled by the adapter).
|
|
1489
|
+
- Open Code: replies `'once'` to `permission.asked` events at runtime
|
|
1490
|
+
via `autoApprovePermission()`.
|
|
1491
|
+
- Codex: enumerates every enabled tool with `approval_mode: 'approve'`
|
|
1492
|
+
in the per-server config — `codex exec` is non-interactive and has
|
|
1493
|
+
no runtime approval channel, so the decision must be baked in
|
|
1494
|
+
up-front.
|
|
1495
|
+
- Copilot: `onPermissionRequest: approveAll` covers MCP tools
|
|
1496
|
+
too — no per-tool enumeration needed.
|
|
1497
|
+
|
|
1498
|
+
Wire whichever path exists; do not assume Codex-style enumeration is
|
|
1499
|
+
required when a runtime hook is available, and do not assume runtime
|
|
1500
|
+
approval works when only static config is offered.
|
|
1501
|
+
|
|
1502
|
+
What you must NOT do:
|
|
1503
|
+
- ❌ A second HTTP listener (e.g. "MCP HTTP bridge for Codex"). Reuse `/mcp`.
|
|
1504
|
+
- ❌ Per-engine MCP servers in `backend/mcp/servers/` (e.g. one folder
|
|
1505
|
+
per engine). All MCP servers are engine-agnostic and registered via
|
|
1506
|
+
`defineServer()` once.
|
|
1507
|
+
- ❌ Per-stream bearer tokens or unique URLs. Authorization piggy-backs
|
|
1508
|
+
on `projectContextService` exactly like the Claude in-process path.
|
|
1509
|
+
- ❌ A new namespace key in `getXxxMcpConfig()` (e.g. `'copilot-mcp'`).
|
|
1510
|
+
Always use `'clopen-mcp'` — `resolveOpenCodeToolName()` keys off it.
|
|
1511
|
+
- ❌ A local type alias when the SDK exports the type (Open Code,
|
|
1512
|
+
Copilot). Import `McpRemoteConfig` / `MCPHTTPServerConfig` directly.
|
|
1513
|
+
|
|
1514
|
+
### 9.13 Auth-blob swap into a shared CLI dotfile (vs. per-account isolated dirs)
|
|
1515
|
+
|
|
1516
|
+
When a CLI hard-codes its credential location (Codex reads
|
|
1517
|
+
`~/.codex/auth.json`; Gemini CLI reads `~/.gemini/oauth_creds.json`;
|
|
1518
|
+
etc.), the naïve approach is to give each Clopen account its own
|
|
1519
|
+
isolated home directory and override the CLI's home env var
|
|
1520
|
+
(`CODEX_HOME`, `GEMINI_HOME`). **Don't.** That approach has bitten us:
|
|
1521
|
+
|
|
1522
|
+
- Session/thread state lives in the same dir tree (`~/.codex/sessions/`,
|
|
1523
|
+
`~/.codex/projects/`), so isolating the dir splits session memory,
|
|
1524
|
+
breaks fork-by-copy, and loses the user's `config.toml` overrides.
|
|
1525
|
+
- Token refresh happens in-place in the dotfile — refreshes performed
|
|
1526
|
+
inside an isolated dir do not propagate back to the user's "real"
|
|
1527
|
+
home unless we add a watcher.
|
|
1528
|
+
- The CLI's other features (e.g. project trust, `.agents` allowlist)
|
|
1529
|
+
expect the dir to be the user's normal one.
|
|
1530
|
+
|
|
1531
|
+
**Use the shared-location-with-DB-swap pattern instead:**
|
|
1532
|
+
|
|
1533
|
+
| Step | Behavior |
|
|
1534
|
+
|---|---|
|
|
1535
|
+
| **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>' }`. |
|
|
1536
|
+
| **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`). |
|
|
1537
|
+
| **Stream-start** | Adapter ensures the dotfile reflects the right blob (re-write if drift detected; cheap idempotent op). |
|
|
1538
|
+
| **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. |
|
|
1539
|
+
|
|
1540
|
+
Trade-off: only **one** Codex/CLI account is "active" on disk at a
|
|
1541
|
+
time. Concurrent streams from two different accounts will race; UI must
|
|
1542
|
+
surface only one active account per engine and document the limitation.
|
|
1543
|
+
For Clopen, that matches existing UI assumptions. If a future engine
|
|
1544
|
+
genuinely needs concurrent multi-account streams, escalate the trade-off
|
|
1545
|
+
explicitly — do **not** silently switch to per-account home dirs.
|
|
1546
|
+
|
|
1547
|
+
Concurrency caveat: if the login command itself writes to the shared
|
|
1548
|
+
dotfile (Codex's `codex login` does), serialize the login flows with a
|
|
1549
|
+
backend-wide mutex so two simultaneous "Add Account" attempts can't
|
|
1550
|
+
clobber each other.
|
|
1551
|
+
|
|
1552
|
+
### 9.14 Long-lived server engines need a "Restart Server" UX
|
|
1553
|
+
|
|
1554
|
+
If your engine boots a process or constructs an SDK client that **caches
|
|
1555
|
+
credentials** beyond a single stream (OpenCode's `opencode serve`
|
|
1556
|
+
subprocess, Copilot's `CopilotClient` constructor), then add / remove /
|
|
1557
|
+
switch account does NOT take effect until that cached state is rebuilt.
|
|
1558
|
+
The fix is the **Restart-Server pattern** documented in §4.2:
|
|
1559
|
+
|
|
1560
|
+
1. Add a `*-server-restart` WS event with the standard contract: check
|
|
1561
|
+
active streams, return `{ needsConfirmation, activeChats }` when not
|
|
1562
|
+
forced; on `force === true`, cancel streams + dispose engine + drop
|
|
1563
|
+
any cached subprocess/client; the next `streamQuery` lazy-inits fresh.
|
|
1564
|
+
2. Surface a **"Restart Server"** button in **two** UI places:
|
|
1565
|
+
- **Settings → Engines** — visible after add/remove/switch in the
|
|
1566
|
+
engines settings panel itself. Confirmation dialog for non-forced.
|
|
1567
|
+
- **Chat Input** — visible next to the model/account picker when the
|
|
1568
|
+
user has switched account mid-session. Uses `force: true` so the
|
|
1569
|
+
send-flow stays inline. See `EngineModelPicker.svelte::ocNeedsRestart`
|
|
1570
|
+
for the flag and `restartOCServer` for the handler.
|
|
1571
|
+
3. After a successful restart, refresh the model catalog
|
|
1572
|
+
(`modelStore.refreshModels(engineType)`) since model availability can
|
|
1573
|
+
depend on credential state.
|
|
1574
|
+
|
|
1575
|
+
Engines that **do not** need this:
|
|
1576
|
+
|
|
1577
|
+
- Subprocess-per-turn engines (Claude Code's `query()`, Codex's
|
|
1578
|
+
`codex exec`) re-read credentials at every turn — there is nothing
|
|
1579
|
+
cached to invalidate.
|
|
1580
|
+
- Engines using the auth-blob swap pattern (§9.13) — the swap happens
|
|
1581
|
+
inside `accounts-switch`, and the next turn's subprocess picks up the
|
|
1582
|
+
new dotfile without a restart event.
|
|
1583
|
+
|
|
1584
|
+
If you are tempted to add a `*-server-restart` event for an engine that
|
|
1585
|
+
spawns a fresh subprocess per turn, you almost certainly want the
|
|
1586
|
+
auth-blob swap (§9.13) instead — adding the restart event ships dead
|
|
1587
|
+
code and confuses the UX (button that does nothing observable).
|
|
1588
|
+
|
|
1589
|
+
### 9.15 Sub-agent (`Task` / `Agent` tool) routing — name, input, parent id
|
|
1590
|
+
|
|
1591
|
+
Every engine SDK we support exposes a "dispatch sub-agent" tool. Each
|
|
1592
|
+
SDK names it differently (Claude → `Task`, OpenCode → `task`, Copilot →
|
|
1593
|
+
`task`) and emits the sub-agent's tool calls / messages on the **same
|
|
1594
|
+
event stream** as the main turn. Without explicit routing those nested
|
|
1595
|
+
messages render as orphan top-level rows in the UI, and the dispatch
|
|
1596
|
+
tool itself appears as `Unknown:task`. There are three independent
|
|
1597
|
+
fixes — miss any one and the symptom shows up in the UI.
|
|
1598
|
+
|
|
1599
|
+
**1. Canonicalise the dispatch tool name to `Agent`.** Every adapter
|
|
1600
|
+
must map its native name into the unified `Agent` block so the frontend
|
|
1601
|
+
tool renderer (`handleAgentTool`) and `subAgentMap` lookups work:
|
|
1602
|
+
|
|
1603
|
+
```ts
|
|
1604
|
+
// claude/message-converter.ts
|
|
1605
|
+
const name = block.name === 'Task' ? 'Agent' : block.name;
|
|
1606
|
+
|
|
1607
|
+
// opencode + copilot tool-name maps
|
|
1608
|
+
'task': 'Agent',
|
|
1609
|
+
```
|
|
1610
|
+
|
|
1611
|
+
Then normalise the SDK's raw input fields into `AgentInput { prompt,
|
|
1612
|
+
description, subagentType }` (see §9.1). Field names vary —
|
|
1613
|
+
`prompt`/`task`/`instruction`, `agent_type`/`subagent_type`/`agent` —
|
|
1614
|
+
so the normaliser must accept them all and default `subagentType` to
|
|
1615
|
+
`'general-purpose'`.
|
|
1616
|
+
|
|
1617
|
+
**2. Stamp `parent.toolUseId` on every sub-agent message.** The
|
|
1618
|
+
frontend grouper (`message-grouper.ts`) routes messages with
|
|
1619
|
+
`parent.toolUseId !== null` into `subAgentMap[parentToolId]` and
|
|
1620
|
+
attaches them as `subActivities` on the parent `Agent` tool block.
|
|
1621
|
+
Top-level messages must keep `parent.toolUseId = null` (see §9.5);
|
|
1622
|
+
sub-agent messages must carry the **parent dispatch tool's** call id.
|
|
1623
|
+
Each SDK exposes that linkage differently:
|
|
1624
|
+
|
|
1625
|
+
| Engine | How the parent id is discovered |
|
|
1626
|
+
|----------|------------------------------------------------------------------|
|
|
1627
|
+
| Claude | `msg.parent_tool_use_id` is on every nested SDK message |
|
|
1628
|
+
| OpenCode | `convertToolUseOnly` / `convertToolResultOnly` / `convertSubtaskToolUseOnly` take a `parentToolUseId` parameter; the caller threads it through when iterating the subtask part |
|
|
1629
|
+
| 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` |
|
|
1630
|
+
|
|
1631
|
+
The converter functions for assistant messages, reasoning messages and
|
|
1632
|
+
`tool.execution_complete` then accept an optional `parentToolUseId` and
|
|
1633
|
+
stamp it onto `parent: { ..., toolUseId: parentToolUseId ?? null }`.
|
|
1634
|
+
On `subagent.completed` / `subagent.failed`, delete the map entry so
|
|
1635
|
+
the next sub-agent dispatch re-registers cleanly.
|
|
1636
|
+
|
|
1637
|
+
**3. Suppress the SDK's sub-agent streaming deltas.** Some SDKs
|
|
1638
|
+
double-emit sub-agent activity: once as live text/reasoning deltas
|
|
1639
|
+
inside the main stream, and again as final non-streaming
|
|
1640
|
+
`assistant.message` / `assistant.reasoning` / `tool.execution_complete`
|
|
1641
|
+
events scoped to the sub-agent. The deltas have no clean parent
|
|
1642
|
+
linkage and would leak into the main chat bubble. The fix is to disable
|
|
1643
|
+
streaming for sub-agents at the SDK config level so only the final
|
|
1644
|
+
bundled events arrive — those carry `agentId` and route correctly via
|
|
1645
|
+
step 2 above:
|
|
1646
|
+
|
|
1647
|
+
```ts
|
|
1648
|
+
// copilot/stream.ts — baseConfig
|
|
1649
|
+
includeSubAgentStreamingEvents: false,
|
|
1650
|
+
```
|
|
1651
|
+
|
|
1652
|
+
If your SDK has no equivalent flag, the fallback is client-side: in the
|
|
1653
|
+
event switch, `if (parentToolUseId) break` for any
|
|
1654
|
+
`assistant.turn_start` / text-delta / reasoning-delta lifecycle event,
|
|
1655
|
+
since those lifecycles belong to the sub-agent and would corrupt the
|
|
1656
|
+
main turn's stream state.
|
|
1657
|
+
|
|
1658
|
+
**Cross-engine consistency.** Once all three fixes are in place, the
|
|
1659
|
+
frontend treats the three engines identically: the `Agent` block in the
|
|
1660
|
+
main timeline carries `subActivities`, no orphan top-level messages
|
|
1661
|
+
appear, and the dispatch tool's name renders as `Agent`. If only step 1
|
|
1662
|
+
ships, sub-agent tool calls float to the top of the chat. If only step
|
|
1663
|
+
2 ships, the dispatch tool still says `Unknown:task`. If only step 3 is
|
|
1664
|
+
missed (in an SDK that does double-emit), sub-agent text appears in
|
|
1665
|
+
both places.
|
|
1666
|
+
|
|
1667
|
+
---
|
|
1668
|
+
|
|
1669
|
+
## 10. Quick reference table
|
|
1670
|
+
|
|
1671
|
+
| Need | File |
|
|
1672
|
+
|---------------------------------------------|-----------------------------------------------------------|
|
|
1673
|
+
| Lazy + concurrency-safe init | `claude/environment.ts::setupEnvironmentOnce`, `opencode/server.ts::ensureClient` |
|
|
1674
|
+
| Per-account credential override (env-var SDK) | `claude/environment.ts::getEngineEnv(accountId)` |
|
|
1675
|
+
| Per-account credential override (constructor SDK) | `copilot/stream.ts::initialize(accountId)` + dispose+reinit in `streamQuery` |
|
|
1676
|
+
| Subprocess spawn + health + recovery | `opencode/server.ts` |
|
|
1677
|
+
| Stateful per-stream converter | `claude/message-converter.ts::createSdkMessageConverter` |
|
|
1678
|
+
| Split one SDK message → N `EngineOutput` | `opencode/message-converter.ts::convertAssistantMessages`, `copilot/message-converter.ts::convertAssistantMessage` |
|
|
1679
|
+
| Buffer until usage event arrives | `copilot/message-converter.ts::flushPending` + `captureUsage` |
|
|
1680
|
+
| Reasoning stream lifecycle | `opencode/stream.ts::flushReasoning`, `copilot/message-converter.ts::convertReasoningDelta` |
|
|
1681
|
+
| Cancel-before-RPC ordering | `opencode/stream.ts::cancel`, `claude/stream.ts::cancel`, `copilot/stream.ts::cancel` |
|
|
1682
|
+
| Fork session (native vs. on-disk workaround) | `claude/stream.ts` (`forkSession: true`), `opencode/stream.ts` (`client.session.fork`), `copilot/session-fork.ts` (copy disk state) |
|
|
1683
|
+
| 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) |
|
|
1684
|
+
| AskUserQuestion event + HTTP fallback | `opencode/stream.ts::resolveUserAnswer`, `claude/stream.ts::canUseTool` |
|
|
1685
|
+
| MCP servers exposed over HTTP (single source) | `backend/mcp/remote-server.ts`, `backend/mcp/config.ts::getOpenCodeMcpConfig` (and future `getXxxMcpConfig`) |
|
|
1686
|
+
| Auth-blob swap into shared CLI dotfile | Pattern only (no implementation yet); see §3.3 callout + §9.13 |
|
|
1687
|
+
| 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` |
|
|
1688
|
+
| `generateStructured` (no tools, JSON) | `claude/stream.ts::generateStructured`, `opencode/stream.ts::generateStructured` |
|
|
1689
|
+
| Error normalisation | `claude/error-handler.ts`, `copilot/error-handler.ts`, `opencode/error-handler.ts`, `qwen/error-handler.ts`, `codex/error-handler.ts` |
|
|
1690
|
+
| DB provider/account access | `backend/database/queries/engine-queries.ts` |
|
|
1691
|
+
| Per-platform install recipe | `backend/engine/install-recipes.ts` |
|
|
1692
|
+
| Streaming install logs | `backend/engine/install-runner.ts` |
|
|
1693
|
+
| Frontend account/provider stores | `frontend/stores/features/{claude-accounts,copilot-accounts,opencode-providers}.svelte.ts` |
|
|
1694
|
+
| Frontend chat-model state | `frontend/stores/ui/chat-model.svelte.ts` |
|
|
1695
|
+
| Settings UI (Engines) | `frontend/components/settings/engines/AIEnginesSettings.svelte` |
|
|
1696
|
+
| Settings UI (System Tools) | `frontend/components/settings/system-tools/{SystemToolsSettings,ToolInstallCard}.svelte` |
|
|
1697
|
+
| Chat picker (engine + model + account) | `frontend/components/chat/input/components/EngineModelPicker.svelte` |
|
|
1698
|
+
| Chat send → backend | `frontend/services/chat/chat.service.ts` (`ws.emit('chat:stream', …)`), `backend/ws/chat/stream.ts` |
|
|
1699
|
+
| Stream-manager (`EngineOutput` routing) | `backend/chat/stream-manager.ts` |
|
|
1700
|
+
|
|
1701
|
+
When in doubt: **mirror** the existing adapters and let `EngineOutput`
|
|
1702
|
+
remain the only contract that crosses the adapter boundary.
|