@myrialabs/clopen 0.3.13 → 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.
@@ -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
+