@myrialabs/clopen 0.3.12 → 0.3.14

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (55) hide show
  1. package/backend/auth/session-invalidation.test.ts +45 -1
  2. package/backend/auth/session-invalidation.ts +35 -1
  3. package/backend/chat/stream-manager.ts +15 -0
  4. package/backend/database/migrations/037_repair_auth_audit_log_schema.ts +38 -0
  5. package/backend/database/migrations/index.ts +7 -0
  6. package/backend/engine/README.md +16 -1597
  7. package/backend/engine/adapters/claude/message-converter.ts +34 -7
  8. package/backend/engine/adapters/claude/models.ts +174 -2
  9. package/backend/engine/adapters/codex/stream.ts +54 -1
  10. package/backend/engine/adapters/copilot/stream.ts +79 -19
  11. package/backend/engine/adapters/opencode/stream.ts +23 -23
  12. package/backend/engine/adapters/qwen/stream.ts +83 -1
  13. package/backend/engine/docs/adapter-contract.md +183 -0
  14. package/backend/engine/docs/adding-an-engine.md +150 -0
  15. package/backend/engine/docs/database.md +123 -0
  16. package/backend/engine/docs/frontend-and-chat.md +176 -0
  17. package/backend/engine/docs/lessons-learned.md +715 -0
  18. package/backend/engine/docs/quick-reference.md +36 -0
  19. package/backend/engine/docs/system-tools.md +82 -0
  20. package/backend/engine/docs/websocket-routes.md +240 -0
  21. package/backend/engine/structured-helpers.ts +59 -0
  22. package/backend/files/file-archive.test.ts +131 -0
  23. package/backend/files/file-archive.ts +252 -0
  24. package/backend/files/file-operations.ts +39 -66
  25. package/backend/files/file-size-limit.test.ts +71 -15
  26. package/backend/files/file-size-limit.ts +36 -8
  27. package/backend/files/file-watcher.ts +117 -3
  28. package/backend/http/files-upload.ts +168 -0
  29. package/backend/index.ts +8 -0
  30. package/backend/mcp/servers/helper.ts +5 -1
  31. package/backend/projects/project-cleanup.ts +1 -1
  32. package/backend/terminal/pty-session-manager.ts +3 -0
  33. package/backend/terminal/stream-manager.ts +1 -1
  34. package/backend/utils/ws.ts +9 -0
  35. package/backend/ws/auth/users.ts +1 -1
  36. package/backend/ws/chat/stream.ts +46 -38
  37. package/backend/ws/files/path-access.test.ts +166 -0
  38. package/backend/ws/files/path-access.ts +56 -22
  39. package/backend/ws/files/read.ts +5 -5
  40. package/backend/ws/files/watch.ts +48 -19
  41. package/backend/ws/files/write.ts +53 -27
  42. package/backend/ws/git/commit-message.ts +12 -5
  43. package/backend/ws/terminal/session.ts +1 -0
  44. package/dist/assets/main-BqiSLc8F.css +1 -0
  45. package/dist/assets/{main-HIDO3ugS.js → main-C37-Y8f-.js} +230 -229
  46. package/dist/index.html +2 -2
  47. package/package.json +8 -7
  48. package/shared/types/git.ts +4 -2
  49. package/shared/types/stores/settings.ts +2 -0
  50. package/shared/types/unified/index.ts +6 -0
  51. package/shared/types/unified/stream.ts +15 -1
  52. package/shared/types/unified/tool.ts +41 -1
  53. package/shared/utils/ws-server.ts +6 -0
  54. package/backend/engine/adapters/copilot/session-fork.ts +0 -111
  55. package/dist/assets/main-C2JiGYnx.css +0 -1
@@ -0,0 +1,183 @@
1
+ [← Engine adapter guide](../README.md)
2
+
3
+ ## 2. The `backend/engine/` layer — core contract
4
+
5
+ ### 2.1 `types.ts` — the `AIEngine` interface
6
+
7
+ ```ts
8
+ export interface AIEngine {
9
+ readonly name: EngineType; // 'claude-code' | 'opencode' | 'copilot'
10
+ readonly isInitialized: boolean;
11
+ readonly isActive: boolean;
12
+
13
+ initialize(accountId?: number): Promise<void>; // lazy; idempotent
14
+ dispose(): Promise<void>; // called per-project & on shutdown
15
+ cancel(): Promise<void>; // hard cancel
16
+ interrupt(): Promise<void>; // soft stop
17
+
18
+ streamQuery(options: EngineQueryOptions):
19
+ AsyncGenerator<EngineOutput, void, unknown>;
20
+
21
+ getAvailableModels(): Promise<EngineModel[]>;
22
+
23
+ // Optional
24
+ resolveUserAnswer?(toolUseId: string, answers: Record<string,string>): boolean;
25
+ generateStructured?<T>(options: StructuredGenerationOptions): Promise<T>;
26
+ }
27
+ ```
28
+
29
+ Three invariants:
30
+
31
+ 1. **`streamQuery` is the only streaming output path.** It is an
32
+ `AsyncGenerator<EngineOutput>`. The adapter translates SDK events into
33
+ `EngineOutput` — that is all.
34
+ 2. **Streaming state lives on the instance.** Because `getProjectEngine`
35
+ returns one instance per `(projectId, engineType)`, the abort controller,
36
+ active query, `pendingUserAnswers`, and session ID are automatically
37
+ isolated per-project.
38
+ 3. **Init is lazy & concurrency-safe.** The first `streamQuery` /
39
+ `getAvailableModels` call triggers `initialize()`. Multiple parallel
40
+ callers **must** share a single init promise. See:
41
+ - `claude/environment.ts::setupEnvironmentOnce`
42
+ - `opencode/server.ts::ensureClient`
43
+
44
+ ### 2.2 `index.ts` — registry & lifecycle
45
+
46
+ Two instance tiers:
47
+
48
+ | Tier | Factory | Used for |
49
+ |--------------------|-------------------------------|-------------------------------------------|
50
+ | Global singleton | `getEngine(type)` | Non-streaming ops: `models:list`, settings|
51
+ | Per-project | `getProjectEngine(projectId, type)` | Streaming chat — isolated per-project|
52
+
53
+ Cleanup:
54
+ - `disposeProjectEngines(projectId)` when a project closes.
55
+ - `disposeAllEngines()` at server shutdown — also calls
56
+ `disposeOpenCodeClient()`. Pattern: when an adapter owns a shared
57
+ subprocess, expose `disposeXxxClient()` from `adapters/<name>/index.ts`
58
+ and call it from `disposeAllProjectEngines()` in `index.ts`.
59
+
60
+ ### 2.3 `EngineOutput` — the event contract
61
+
62
+ In `shared/types/unified/stream.ts`:
63
+
64
+ ```ts
65
+ type EngineOutput =
66
+ | UserMessage // persisted to DB
67
+ | AssistantMessage // persisted to DB
68
+ | ReasoningMessage // persisted to DB
69
+ | CompactBoundaryMessage
70
+ | StreamEvent // transient: 'start' | 'stop' | 'delta'
71
+ | ResultEvent // transient: success / error_max_turns / etc.
72
+ | SystemInitEvent // transient: model + tools + mcpServers
73
+ | RateLimitEvent; // transient
74
+ ```
75
+
76
+ `stream-manager.ts` discriminates on `output.type`:
77
+
78
+ | `type` | Routing |
79
+ |----------------|---------------------------------------------------------|
80
+ | `user`/`assistant`/`reasoning`/`compact_boundary` | save DB + emit `chat:message` |
81
+ | `stream_event` | forward to frontend for live typing (`chat:partial`) |
82
+ | `result` | extract metadata + emit `chat:stream-finished` |
83
+ | `system_init` | emit MCP-failure notification if any |
84
+ | `rate_limit` | emit `chat:notification` |
85
+
86
+ > **Strict rule:** do not invent new types. If an SDK has an event that
87
+ > needs to be propagated, **extend** the union in
88
+ > `shared/types/unified/stream.ts` first, teach `stream-manager` how to
89
+ > route it, and only then emit it from the adapter.
90
+
91
+ ### 2.4 `EngineQueryOptions`
92
+
93
+ ```ts
94
+ interface EngineQueryOptions {
95
+ projectPath: string;
96
+ prompt: UserMessage;
97
+ resume?: string; // SDK session id for resume / fork
98
+ forkSession?: boolean;
99
+ maxTurns?: number;
100
+ providerSlug: string; // 'anthropic', 'openai', etc — required for opencode
101
+ modelId: string; // 'claude-opus-4-7', 'gpt-5', etc
102
+ includePartialMessages?: boolean;
103
+ abortController?: AbortController;
104
+ accountId?: number; // override credential for a single stream
105
+ mcpContext?: McpExecutionContext; // { projectId, chatSessionId, streamId }
106
+ }
107
+ ```
108
+
109
+ `mcpContext` is bound into the MCP handler so a tool call from project A
110
+ **cannot** write into project B. Always forward it: see `claude/stream.ts`
111
+ calling `getEnabledMcpServers(options.mcpContext)`.
112
+
113
+ ### 2.5 What an adapter **MUST NOT** do
114
+
115
+ - ❌ Call `ws.emit.*` — that is the stream-manager's job.
116
+ - ❌ Touch chat / message DB (`messageQueries`, `sessionQueries`) —
117
+ persistence belongs to the stream-manager. Adapters **may** read
118
+ credentials via `engineQueries`.
119
+ - ❌ Mutate `process.env` or call `process.chdir()` — pass env & cwd via
120
+ SDK options. Many projects stream concurrently.
121
+ - ❌ Define shared types inline — extend `shared/types/unified/*`.
122
+ - ❌ Use `console.*` — use `debug` from `$shared/utils/logger` with
123
+ category `'engine'`, `'chat'`, or `'mcp'`.
124
+ - ❌ **Build a new MCP HTTP server for the adapter.** Use the existing
125
+ `backend/mcp/remote-server.ts` and add a `getXxxMcpConfig()` helper in
126
+ `backend/mcp/config.ts` returning the URL in the engine's expected
127
+ shape. New MCP servers are added via `defineServer()` — never via a
128
+ parallel HTTP listener.
129
+ - ❌ **Create per-account isolated home directories** to multiplex two
130
+ accounts into the same CLI's shared dotfile. Snapshot the CLI's auth
131
+ file into `engine_accounts.credential` on login; write the chosen
132
+ account's snapshot back into the shared location on switch. See §9.13.
133
+
134
+ ### 2.6 Standard files in each adapter
135
+
136
+ Adapters follow a fixed file taxonomy. **Mandatory** files exist in every
137
+ adapter; **optional** files may be omitted, but when present they MUST use
138
+ the canonical name below — never a synonym (`auth.ts`, `provider-catalog.ts`,
139
+ etc.). This keeps `git grep` and the README's quick-reference rows usable.
140
+
141
+ ```
142
+ adapters/<name>/
143
+ ├── index.ts ← MANDATORY re-exports only, NO logic
144
+ ├── stream.ts ← MANDATORY class implements AIEngine
145
+ ├── models.ts ← MANDATORY static EngineModel[] OR dynamic fetcher
146
+ ├── message-converter.ts ← MANDATORY SDK message → EngineOutput (pure)
147
+ ├── error-handler.ts ← MANDATORY SDK error → user-facing string
148
+ ├── credential.ts? ← OPTIONAL credential parse / auth-blob swap (codex, qwen)
149
+ ├── environment.ts? ← OPTIONAL env / dotfile setup (claude, qwen)
150
+ ├── server.ts? ← OPTIONAL subprocess + client lifecycle (opencode)
151
+ ├── config.ts? ← OPTIONAL runtime config builder (opencode)
152
+ ├── presets.ts? ← OPTIONAL multi-provider/region preset catalog (qwen, opencode)
153
+ └── session-fork.ts? ← OPTIONAL on-disk session fork workaround (codex, qwen)
154
+ ```
155
+
156
+ Naming rules — strict, even when an SDK's local jargon differs:
157
+
158
+ | File | Owns |
159
+ |-------------------|-----------------------------------------------------------------------|
160
+ | `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). |
161
+ | `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. |
162
+ | `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. |
163
+ | `config.ts` | Runtime config builder ONLY — turning DB providers + accounts into env vars / spawn options. Catalog data goes in `presets.ts`. |
164
+
165
+ Important conventions:
166
+ - `message-converter.ts` is generally pure. If you need per-stream state
167
+ (e.g. tracking "is the reasoning block already closed?"), expose a
168
+ **factory** `createSdkMessageConverter()` returning a stateful converter
169
+ — see Claude.
170
+ - Tool names **must** be canonicalised via `toCanonicalToolName(...)`
171
+ (`shared/types/unified/tool.ts`) so the frontend renders the same UI for
172
+ tools that have different names across SDKs.
173
+ - `cancel()` ordering: **abort the local controller first**, **then** RPC
174
+ to the SDK/server. RPCs can hang; the local abort cuts the `for await`
175
+ loop deterministically. See `OpenCodeEngine.cancel`,
176
+ `ClaudeCodeEngine.cancel`, `CopilotEngine.cancel`.
177
+ - Dynamic-catalog fetchers in `models.ts` MUST return `EngineModel[]` and
178
+ use `[]` as the failure sentinel (network, auth, parse error). Do **not**
179
+ return `null` — both `fetchOpenCodeModels` and `fetchQwenModels` return
180
+ `[]` on failure so the picker renders empty rather than a stale catalog.
181
+
182
+ ---
183
+
@@ -0,0 +1,150 @@
1
+ [← Engine adapter guide](../README.md)
2
+
3
+ ## 8. End-to-end checklist for adding a new engine
4
+
5
+ The steps below are the same pattern used when the **`copilot`**
6
+ (`@github/copilot-sdk`) adapter was added to the repo. Use it as a
7
+ blueprint for the next engine you add.
8
+
9
+ ### Stage 1 — Shared types
10
+
11
+ - [ ] `shared/types/unified/common.ts`: add `'newengine'` to `EngineType`.
12
+ - [ ] `shared/types/unified/engine.ts`: add `'newengine'` to `EngineInfo.type`.
13
+ - [ ] `shared/types/unified/message.ts`: add `'newengine'` to `MessageEngine.type`.
14
+ - [ ] `shared/constants/engines.ts`: add an entry in `ENGINES[]`
15
+ (`type, name, description, icon.light, icon.dark`).
16
+ - [ ] `backend/engine/adapters/newengine/models.ts`: own the catalog. Static
17
+ engines export a `NEWENGINE_MODELS: EngineModel[]` array; dynamic
18
+ engines export a fetcher (`fetchNewengineModels(...)`) consumed by
19
+ `getAvailableModels()`. Don't add anything to `shared/constants/engines.ts`
20
+ for the catalog itself — the frontend loads it via `models:list`.
21
+ - [ ] (Optional) `backend/engine/adapters/newengine/presets.ts` if the
22
+ engine needs provider/region/BYOK presets exposed to the UI.
23
+ Mirror `qwen/presets.ts`: keep runtime values in the adapter,
24
+ export wire types from `shared/types/unified/engine.ts`, and ship
25
+ a WS endpoint (see Stage 4) — never import these from frontend
26
+ via `$backend`.
27
+
28
+ ### Stage 2 — Adapter `backend/engine/`
29
+
30
+ Refer to §2.6 for the full file taxonomy. Every adapter ships these five
31
+ mandatory files; optional files use the canonical names from §2.6.
32
+
33
+ - [ ] Create `backend/engine/adapters/newengine/`
34
+ - [ ] `index.ts` (mandatory) → `export { NewEngineEngine } from './stream';`
35
+ (+ `disposeXxxClient` if there is a subprocess).
36
+ - [ ] `stream.ts` (mandatory) → class `NewEngineEngine implements AIEngine`.
37
+ Pick a template: `claude/stream.ts` (in-process SDK),
38
+ `opencode/stream.ts` (subprocess), `copilot/stream.ts` (in-process
39
+ with construction-time credential), or `qwen/stream.ts` (CLI subprocess
40
+ via SDK with auth-blob swap).
41
+ - [ ] `models.ts` (mandatory) → static `NEWENGINE_MODELS: EngineModel[]`
42
+ OR `fetchNewengineModels(...): Promise<EngineModel[]>` (dynamic;
43
+ return `[]` on failure — see §4.5).
44
+ - [ ] `message-converter.ts` (mandatory) → pure functions SDK → `EngineOutput`.
45
+ Use `toCanonicalToolName()` for tool names.
46
+ - [ ] `error-handler.ts` (mandatory) → exports `handleStreamError(error,
47
+ ...): void` (and any helper formatters specific to the SDK's error
48
+ payload — see `opencode/error-handler.ts::formatSessionError` for the
49
+ pattern).
50
+ - [ ] `credential.ts` / `environment.ts` / `server.ts` / `config.ts` /
51
+ `presets.ts` / `session-fork.ts` (optional; canonical names only).
52
+ - [ ] `backend/engine/index.ts`: import + add a case in
53
+ `createEngine(type)`. If there is a shared subprocess, call
54
+ `disposeXxxClient()` from `disposeAllProjectEngines()`.
55
+
56
+ ### Stage 3 — Database (if a default provider needs to be seeded)
57
+
58
+ - [ ] Add a new migration in `backend/database/migrations/` (e.g. seed
59
+ `('newengine', 'vendor', 'Vendor', NULL, NULL, '{}', 1)` into
60
+ `engine_providers`). **Do not change the schema** — the tables
61
+ are already generic.
62
+
63
+ ### Stage 4 — WebSocket `engine:newengine-*`
64
+
65
+ - [ ] Create `backend/ws/engine/newengine/`:
66
+ - `status.ts` — `engine:newengine-status` (`installed`, `version`, etc).
67
+ - `accounts.ts` or `providers.ts` — account/provider CRUD:
68
+ - List, add, switch, delete, rename.
69
+ - Setup flow: PTY (Claude-style) OR direct API-key/PAT input
70
+ (OpenCode/Copilot-style) depending on the SDK's auth mechanism.
71
+ - (Optional) `presets.ts` — `engine:newengine-presets-list` if the
72
+ adapter has a `presets.ts` module. See `backend/ws/engine/qwen/presets.ts`.
73
+ - `index.ts` — merge the sub-router.
74
+ - [ ] `backend/ws/engine/index.ts`: `.merge(newengineEngineRouter)`.
75
+ - [ ] `backend/ws/chat/stream.ts`: add the `'newengine'` literal to the
76
+ typebox schema for `engine.type`.
77
+ - [ ] `backend/ws/settings/crud.ts`: add the `'newengine'` literal to the
78
+ `models:list` typebox schema.
79
+
80
+ ### Stage 5 — Frontend store
81
+
82
+ - [ ] Add `frontend/stores/features/newengine-accounts.svelte.ts` (or
83
+ `newengine-providers.svelte.ts` following OpenCode's style if the
84
+ engine is multi-provider). Mirror the pattern of
85
+ `claudeAccountsStore` / `copilotAccountsStore` / `opencodeProvidersStore`.
86
+
87
+ ### Stage 6 — Settings → Engines
88
+
89
+ - [ ] Add a panel to `AIEnginesSettings.svelte`: the card appears
90
+ automatically since `ENGINES` already has the new entry. Implement
91
+ the setup flow:
92
+ - Load status via `ws.http('engine:newengine-status', {})`.
93
+ - Subscribe to server-emit events for login progress.
94
+ - After save: `newengineStore.refresh()` +
95
+ `modelStore.refreshModels('newengine')`.
96
+
97
+ ### Stage 7 — Settings → System Tools
98
+
99
+ - [ ] `backend/engine/install-recipes.ts`:
100
+ - Add `'newengine'` to `ToolId`.
101
+ - Write `resolveNewEngineRecipe()` (winget/brew/curl pipe — whatever the
102
+ SDK needs to install its CLI).
103
+ - Add a case in `resolveRecipe()`.
104
+ - [ ] `backend/ws/system-tools/status.ts` & `install.ts`: add
105
+ `'newengine'` to `TOOL_UNION`.
106
+ - [ ] `frontend/components/settings/system-tools/SystemToolsSettings.svelte`:
107
+ `<ToolInstallCard tool="newengine" title="NewEngine CLI" description="..." />`.
108
+
109
+ ### Stage 8 — Chat input
110
+
111
+ If the engine uses one-account-per-engine (Claude/Copilot style), wire it
112
+ into `EngineModelPicker.svelte`:
113
+
114
+ - [ ] Import the new store + add a branch to `accountsForEngine`,
115
+ `accountPickerLabel`, `showAccountPicker`, and the two
116
+ `$effect` blocks (auto-fetch and auto-select active account).
117
+ - [ ] No new dropdown markup is required — the existing dropdown iterates
118
+ `accountsForEngine`.
119
+
120
+ If the engine is multi-provider (OpenCode style) the picker logic is
121
+ heavier — copy the OpenCode block.
122
+
123
+ Other auto wiring:
124
+ - [ ] The engine tab appears automatically in `EngineModelPicker` from
125
+ `ENGINES`.
126
+ - [ ] Verify: select engine → model list appears → send message → stream
127
+ runs.
128
+
129
+ ### Stage 9 — Manual QA
130
+
131
+ From the project root:
132
+
133
+ ```sh
134
+ bun run check && bun run lint
135
+ ```
136
+
137
+ Then the minimum UI scenarios that must pass:
138
+
139
+ - [ ] Settings → System Tools → Install NewEngine CLI → exit 0.
140
+ - [ ] Settings → Engines → NewEngine → Add Account → status `Installed,
141
+ Active account: <name>`.
142
+ - [ ] Chat input → pick NewEngine + model → send a message → assistant
143
+ replies → cancel mid-stream → idle → send again → resume works.
144
+ - [ ] AskUserQuestion (if the SDK supports it) → appears in UI → submit
145
+ answer → stream continues.
146
+ - [ ] Restart Clopen → state survives (account, provider, last-used model
147
+ in chat).
148
+
149
+ ---
150
+
@@ -0,0 +1,123 @@
1
+ [← Engine adapter guide](../README.md)
2
+
3
+ ## 3. Database — `engine_providers` & `engine_accounts`
4
+
5
+ Migration: `backend/database/migrations/029_migrate_messages_to_unified.ts`
6
+ (Phases 6–7). Previously split into `claude_accounts`, `opencode_providers`,
7
+ `opencode_accounts` — now **consolidated**.
8
+
9
+ ### 3.1 Schema
10
+
11
+ ```sql
12
+ CREATE TABLE engine_providers (
13
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
14
+ engine_type TEXT NOT NULL, -- 'claude-code' | 'opencode' | 'copilot' | <new>
15
+ slug TEXT NOT NULL, -- 'anthropic', 'openai', etc (lowercase)
16
+ name TEXT NOT NULL, -- display name
17
+ npm TEXT, -- npm package (opencode), NULL for claude/copilot
18
+ api_url TEXT, -- custom endpoint
19
+ options TEXT NOT NULL DEFAULT '{}', -- JSON: env var values, flags
20
+ is_enabled INTEGER NOT NULL DEFAULT 1,
21
+ created_at TEXT NOT NULL DEFAULT (datetime('now')),
22
+ UNIQUE (engine_type, slug)
23
+ );
24
+
25
+ CREATE TABLE engine_accounts (
26
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
27
+ provider_id INTEGER NOT NULL REFERENCES engine_providers(id) ON DELETE CASCADE,
28
+ name TEXT NOT NULL,
29
+ credential TEXT NOT NULL, -- OAuth token / API key / PAT
30
+ is_active INTEGER NOT NULL DEFAULT 0,
31
+ created_at TEXT NOT NULL DEFAULT (datetime('now'))
32
+ );
33
+ ```
34
+
35
+ Concepts:
36
+ - **Provider** = "who owns the model". For `claude-code` there is exactly
37
+ one provider (`anthropic`, seeded in the migration). For `copilot` there
38
+ is exactly one provider (`github`, seeded in `032_seed_copilot_provider.ts`).
39
+ For `opencode`, the user adds many providers (Anthropic, OpenAI, Google,
40
+ OpenRouter, …).
41
+ - **Account** = the concrete credential under a provider. Multiple are
42
+ allowed; exactly one row per provider has `is_active = 1`.
43
+ - **Switching account** flip-flags automatically:
44
+ `engineQueries.switchAccount(id)` sets all accounts under that provider
45
+ to `is_active = 0`, then sets the chosen one to `1`.
46
+ - **Deleting the active account** automatically promotes another account in
47
+ the same provider to active (logic in `engineQueries.deleteAccount`).
48
+
49
+ ### 3.2 Main helpers (`engineQueries`)
50
+
51
+ ```ts
52
+ // Provider
53
+ getProviders(engineType?) getEnabledProviders(engineType?)
54
+ getProvider(id) getProviderBySlug(engineType, slug)
55
+ createProvider({...}) updateProviderOptions(id, jsonStr)
56
+ toggleProvider(id, enabled) deleteProvider(id) // cascades to accounts
57
+
58
+ // Account
59
+ getAccount(id) getAccountsByProvider(providerId)
60
+ getActiveAccount(providerId) getActiveAccountForEngine(engineType)
61
+ createAccount(providerId, name, credential) // auto-active if first
62
+ switchAccount(accountId) deleteAccount(accountId)
63
+ renameAccount(accountId, name)
64
+
65
+ // Composite
66
+ getProvidersWithAccounts(engineType?) // join used by endpoint listing
67
+ ```
68
+
69
+ ### 3.3 How an adapter reads them
70
+
71
+ - **Claude** — `environment.ts` calls
72
+ `engineQueries.getActiveAccountForEngine('claude-code')` inside
73
+ `setupEnvironmentOnce()` to inject `CLAUDE_CODE_OAUTH_TOKEN`. When
74
+ `streamQuery` is called with an explicit `accountId`,
75
+ `getEngineEnv(accountId)` overrides the token without mutating singleton
76
+ state — ideal for per-stream account override.
77
+
78
+ - **OpenCode** — `config.ts::generateOpenCodeProviderConfig()`:
79
+ 1. `engineQueries.getEnabledProviders('opencode')`
80
+ 2. For each provider, `getActiveAccount(provider.id)`
81
+ 3. Look up the env-var name(s) from the `models.dev` catalog cached in
82
+ `presets.ts::getCachedModelsDevCatalog()` (see §3.4)
83
+ 4. Inject the first env var with `account.credential`, remaining env vars
84
+ from `provider.options` JSON
85
+ 5. Result: `enabledProviders[]` (for `OPENCODE_CONFIG_CONTENT`) +
86
+ `envVars{}` (merged into the `opencode serve` process)
87
+
88
+ - **Copilot** — `stream.ts::initialize(accountId?)` calls
89
+ `engineQueries.getAccount(accountId)` (or
90
+ `getActiveAccountForEngine('copilot')` when no override is supplied)
91
+ and constructs a fresh `CopilotClient({ gitHubToken: account.credential })`.
92
+ The Copilot SDK takes the token at **client construction time**, so a
93
+ per-stream account switch requires `dispose()` + `initialize(newId)` —
94
+ see `streamQuery` in `copilot/stream.ts` and §9.9 below.
95
+
96
+ > **Pattern: auth-blob materialization for shared CLI dotfiles.**
97
+ > Some CLIs (e.g. Codex's `~/.codex/auth.json`) read credentials from a
98
+ > fixed location on disk that **cannot** be redirected per-process without
99
+ > isolating the entire home dir. For those engines, `credential` stores
100
+ > the **whole file content** as a JSON wrapper
101
+ > (`{ kind: 'chatgpt', authJson: '...' }`), and the adapter / WS handler
102
+ > writes that blob back to the shared dotfile on `accounts-switch`. After
103
+ > each stream, snapshot the (possibly-refreshed-by-the-CLI) dotfile back
104
+ > into `engine_accounts.credential` so token refreshes survive across
105
+ > account switches. This keeps multi-account support working without
106
+ > isolated `XYZ_HOME` directories — see §9.13 for the rationale.
107
+
108
+ ### 3.4 The models.dev catalog (OpenCode-specific)
109
+
110
+ `presets.ts::fetchAndCacheModelsDevCatalog()` caches the catalog in the
111
+ `settings` table under `opencode.models_dev_cache`
112
+ (+ `opencode.models_dev_cached_at`). `getCachedModelsDevCatalog()` reads it
113
+ back. The catalog lists the providers OpenCode supports along with the
114
+ env-var names they expect. The frontend uses the catalog in the "Add
115
+ Provider" picker — the user just selects a provider, enters the API key,
116
+ and the env-var mapping is automatically correct.
117
+
118
+ The split between `presets.ts` (catalog data + cache) and `config.ts`
119
+ (runtime env-var builder) mirrors `qwen/`, the canonical multi-provider
120
+ adapter — see §2.6 and §4.6.
121
+
122
+ ---
123
+
@@ -0,0 +1,176 @@
1
+ [← Engine adapter guide](../README.md)
2
+
3
+ ## 5. Frontend — Settings UI
4
+
5
+ ### 5.1 Settings → Engines
6
+
7
+ Files:
8
+ - `frontend/components/settings/engines/AIEnginesSettings.svelte`
9
+ - Stores: `frontend/stores/features/claude-accounts.svelte.ts`,
10
+ `frontend/stores/features/copilot-accounts.svelte.ts`,
11
+ `frontend/stores/features/opencode-providers.svelte.ts`
12
+
13
+ Pattern:
14
+ - The component renders one card **per engine** from the `ENGINES` constant
15
+ in `shared/constants/engines.ts` (icon, name, description).
16
+ - For **Claude**: calls `engine:claude-status`. The "Add Account" button
17
+ starts `engine:claude-account-setup-start` and renders an xterm terminal
18
+ for debug + to display the auth URL.
19
+ - For **Copilot**: calls `engine:copilot-status` and
20
+ `copilotAccountsStore.fetch()`. "Add Account" submits a GitHub PAT
21
+ directly via `engine:copilot-accounts-add` (no PTY required).
22
+ - For **OpenCode**: calls `engine:opencode-status` and
23
+ `opencodeProvidersStore.fetchProviders()`. "Add Provider" picks from the
24
+ `models.dev` catalog, fills in API key + extra env options (per
25
+ `catalogEntry.env[]`), and submits → `engine:opencode-provider-add`.
26
+ - After an account switch / restart: refresh the relevant store
27
+ (`claudeAccountsStore.refresh()` / `copilotAccountsStore.refresh()` /
28
+ `opencodeProvidersStore.refreshProviders()`) and call
29
+ `modelStore.refreshModels()` to stay in sync.
30
+
31
+ **Stores**:
32
+ ```ts
33
+ claudeAccountsStore // accounts[], fetch(), refresh(), set(), reset()
34
+ copilotAccountsStore // accounts[], fetch(), refresh(), set(), reset()
35
+ // (identical API to claudeAccountsStore)
36
+ opencodeProvidersStore // providers[], catalog[], catalogCachedAt,
37
+ // fetchProviders/refreshProviders, addProvider,
38
+ // removeProvider, toggleProvider,
39
+ // updateProviderOptions,
40
+ // addAccount, switchAccount, deleteAccount,
41
+ // renameAccount,
42
+ // fetchCatalog, refreshCatalog, refetchCatalog,
43
+ // restartServer, reset
44
+ modelStore // models[], fetchModels(engine), refreshModels(engine),
45
+ // getByEngine(engine), getById(modelId)
46
+ ```
47
+
48
+ ### 5.2 Settings → System Tools
49
+
50
+ Files:
51
+ - `frontend/components/settings/system-tools/SystemToolsSettings.svelte`
52
+ - `frontend/components/settings/system-tools/ToolInstallCard.svelte`
53
+
54
+ `SystemToolsSettings` renders one `ToolInstallCard` per tool (`git`,
55
+ `claude`, `opencode`, `chrome`, `cloudflared`). `ToolInstallCard`:
56
+
57
+ 1. Calls `system-tools:status` on mount.
58
+ 2. Renders: status (installed/version/source), an "Install" button if
59
+ `recipe.autoInstallable`, otherwise a "Manual install" dialog.
60
+ 3. While installing: `system-tools:install-start` → subscribe to
61
+ `system-tools:install-stream` (per-line) → render in xterm + show
62
+ exit status from `system-tools:install-finished`.
63
+ 4. The session survives navigation: if `activeSession` exists on refresh,
64
+ re-attach to the same session id.
65
+
66
+ To add a new tool (e.g. `goose`):
67
+ 1. Add the literal to `ToolId` (`backend/engine/install-recipes.ts`).
68
+ 2. Add `resolveGooseRecipe()` + a case in `resolveRecipe()`.
69
+ 3. Add the literal to `TOOL_UNION` (`backend/ws/system-tools/status.ts`
70
+ and `install.ts`).
71
+ 4. Add `<ToolInstallCard tool="goose" title="Goose" description="…" />`
72
+ in `SystemToolsSettings.svelte`.
73
+ 5. (Optional) expose detection in the `engine:<name>-status` handler so
74
+ Settings → Engines can show an "Installed" badge.
75
+
76
+ ---
77
+
78
+ ## 6. Chat integration — model picker & stream
79
+
80
+ ### 6.1 chat-input state
81
+
82
+ `frontend/stores/ui/chat-model.svelte.ts` — `chatModelState`:
83
+
84
+ ```ts
85
+ { engine, provider, modelId, modelName,
86
+ engineModelMemory: { [engine]: { provider, id, name } },
87
+ accountId, accountName }
88
+ ```
89
+
90
+ This store is **local to the active session**: settings under Settings →
91
+ Engines only seed the initial defaults via `initChatModel(...)`. Switching
92
+ engine/model in chat input does **not** affect Settings.
93
+
94
+ ### 6.2 EngineModelPicker (in chat input)
95
+
96
+ `frontend/components/chat/input/components/EngineModelPicker.svelte`:
97
+ - Engine tabs from `ENGINES`.
98
+ - Model list from `modelStore.getByEngine(engine)` — auto-fetched via
99
+ `modelStore.fetchModels(engine)` whenever the engine changes.
100
+ - **Account picker for `claude-code` and `copilot`** (single-account-list
101
+ engines): both stores expose the same
102
+ `{ accounts, fetch, refresh, set, reset }` API, so a single dropdown
103
+ drives both. The component derives `accountsForEngine` from
104
+ `chatModelState.engine`, the chosen account is written into
105
+ `chatModelState.accountId` / `accountName`, and on send it is forwarded
106
+ as `engine.account.id` to the backend (see §6.3). To add a third engine
107
+ with this same shape, add a branch in `accountsForEngine`,
108
+ `accountPickerLabel`, `showAccountPicker`, and the auto-select `$effect`
109
+ — no new dropdown markup is needed.
110
+ - **OpenCode** has a separate picker because its accounts are scoped to a
111
+ provider, which is implied by the currently selected model. The picker
112
+ resolves the model's provider via `ocMatchingProvider`, then writes the
113
+ chosen account into `chatModelState.accountId` and triggers a server
114
+ restart.
115
+
116
+ ### 6.3 Send path → backend
117
+
118
+ `frontend/services/chat/chat.service.ts` on submit:
119
+
120
+ ```ts
121
+ ws.emit('chat:stream', {
122
+ sessionId: <ephemeral>,
123
+ chatSessionId: ...,
124
+ projectPath: ...,
125
+ prompt: <UserMessage>,
126
+ engine: {
127
+ type: chatModelState.engine,
128
+ provider: chatModelState.provider,
129
+ model: { id: chatModelState.modelId, name: chatModelState.modelName },
130
+ account: { id: chatModelState.accountId ?? 0, name: chatModelState.accountName ?? '' },
131
+ },
132
+ sender: { id, name }
133
+ });
134
+ ```
135
+
136
+ Backend `chat:stream` then `streamManager.startStream(...)`, which:
137
+ - Resolves `getProjectEngine(projectId, engine.type)`
138
+ - Calls `engine.streamQuery({ projectPath, prompt, providerSlug: engine.provider, modelId: engine.model.id, accountId: engine.account.id !== 0 ? engine.account.id : undefined, mcpContext })`
139
+ - Yields `EngineOutput` → emits `chat:message` / `chat:partial` /
140
+ `chat:notification` to the session room.
141
+
142
+ > **`accountId !== 0`** is the convention for "use override". `0` means
143
+ > "fall back to the active account in DB". Account-aware adapters
144
+ > (`claude`, `copilot`) read this and override their per-stream credential
145
+ > accordingly.
146
+
147
+ ### 6.4 Reasoning, attachments, AskUserQuestion
148
+
149
+ - **Reasoning**: an adapter must emit
150
+ `StreamLifecycleEvent { reasoning: true }` to mark start/stop of the
151
+ thinking block, then `TextDeltaEvent { reasoning: true }` for each delta.
152
+ The frontend renders these in a separate bubble.
153
+ - **Attachments**: `UserMessage.content` carries `text | image | document`
154
+ blocks. The adapter maps these to the SDK's format — Claude uses native
155
+ content blocks, OpenCode uses `extractPromptParts()` to
156
+ `data:<mime>;base64,...`.
157
+ - **AskUserQuestion**: a standard tool the adapter intercepts **only when
158
+ the SDK exposes a native interactive hook**. Two patterns are in use, plus
159
+ one explicit non-support case:
160
+ 1. **In-process callback** (Claude, Qwen) — `claude/stream.ts::canUseTool`
161
+ blocks the SDK until the user answers; Qwen mirrors this with its own
162
+ `canUseTool`.
163
+ 2. **SDK event + HTTP fallback** (OpenCode, Copilot) — `opencode/stream.ts`
164
+ listens for `question.asked` and resolves via
165
+ `engine.resolveUserAnswer(toolUseId, answers)`; Copilot parks its
166
+ `onUserInputRequest` callback the same way.
167
+ 3. **Unsupported** (Codex) — the `@openai/codex-sdk` exposes no callback
168
+ hook, permission event, or elicitation primitive, so AskUserQuestion
169
+ stays unsupported for Codex until the upstream SDK ships one. There is
170
+ **no** MCP-tool fallback: the previous engine-agnostic MCP path was
171
+ removed (its carrying cost outweighed the benefit). Do not reintroduce
172
+ it — wire the engine's native hook to `resolveUserAnswer` when it
173
+ exists. See §9.12 point 3.
174
+
175
+ ---
176
+