@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,36 @@
1
+ [← Engine adapter guide](../README.md)
2
+
3
+ ## 10. Quick reference table
4
+
5
+ | Need | File |
6
+ |---------------------------------------------|-----------------------------------------------------------|
7
+ | Lazy + concurrency-safe init | `claude/environment.ts::setupEnvironmentOnce`, `opencode/server.ts::ensureClient` |
8
+ | Per-account credential override (env-var SDK) | `claude/environment.ts::getEngineEnv(accountId)` |
9
+ | Per-account credential override (constructor SDK) | `copilot/stream.ts::initialize(accountId)` + dispose+reinit in `streamQuery` |
10
+ | Subprocess spawn + health + recovery | `opencode/server.ts` |
11
+ | Stateful per-stream converter | `claude/message-converter.ts::createSdkMessageConverter` |
12
+ | Split one SDK message → N `EngineOutput` | `opencode/message-converter.ts::convertAssistantMessages`, `copilot/message-converter.ts::convertAssistantMessage` |
13
+ | Buffer until usage event arrives | `copilot/message-converter.ts::flushPending` + `captureUsage` |
14
+ | Reasoning stream lifecycle | `opencode/stream.ts::flushReasoning`, `copilot/message-converter.ts::convertReasoningDelta` |
15
+ | Cancel-before-RPC ordering | `opencode/stream.ts::cancel`, `claude/stream.ts::cancel`, `copilot/stream.ts::cancel` |
16
+ | Fork session (native vs. on-disk workaround) | `claude/stream.ts` (`forkSession: true`), `opencode/stream.ts` (`client.session.fork`), `copilot/stream.ts` (`client.rpc.sessions.fork`), `codex/session-fork.ts` + `qwen/session-fork.ts` (copy disk state) |
17
+ | Sub-agent (`Task`/`Agent`) routing | `claude/message-converter.ts` (`parent_tool_use_id`), `opencode/message-converter.ts::convertSubtaskToolUseOnly`, `copilot/message-converter.ts::resolveParentToolUseId` + `agentParentMap` (see §9.15) |
18
+ | AskUserQuestion event + HTTP fallback | `opencode/stream.ts::resolveUserAnswer`, `claude/stream.ts::canUseTool` |
19
+ | MCP servers exposed over HTTP (single source) | `backend/mcp/remote-server.ts`, `backend/mcp/config.ts::getOpenCodeMcpConfig` (and future `getXxxMcpConfig`) |
20
+ | Auth-blob swap into shared CLI dotfile | Pattern only (no implementation yet); see §3.3 callout + §9.13 |
21
+ | Restart-Server pattern (long-lived engines) | `backend/ws/engine/opencode/providers.ts::engine:opencode-server-restart`, `frontend/components/chat/input/components/EngineModelPicker.svelte::restartOCServer`, `AIEnginesSettings.svelte::handleRestartServer`/`forceRestartServer` |
22
+ | `generateStructured` (no tools, JSON) | `claude/stream.ts::generateStructured` (native `outputFormat`), `codex/stream.ts::generateStructured` (native `outputSchema`), `opencode/stream.ts::generateStructured` + `copilot/stream.ts::generateStructured` + `qwen/stream.ts::generateStructured` (prompt-engineered via `backend/engine/structured-helpers.ts`). See §9.16 for the strict-schema + part-fallback gotchas. |
23
+ | Error normalisation | `claude/error-handler.ts`, `copilot/error-handler.ts`, `opencode/error-handler.ts`, `qwen/error-handler.ts`, `codex/error-handler.ts` |
24
+ | DB provider/account access | `backend/database/queries/engine-queries.ts` |
25
+ | Per-platform install recipe | `backend/engine/install-recipes.ts` |
26
+ | Streaming install logs | `backend/engine/install-runner.ts` |
27
+ | Frontend account/provider stores | `frontend/stores/features/{claude-accounts,copilot-accounts,opencode-providers}.svelte.ts` |
28
+ | Frontend chat-model state | `frontend/stores/ui/chat-model.svelte.ts` |
29
+ | Settings UI (Engines) | `frontend/components/settings/engines/AIEnginesSettings.svelte` |
30
+ | Settings UI (System Tools) | `frontend/components/settings/system-tools/{SystemToolsSettings,ToolInstallCard}.svelte` |
31
+ | Chat picker (engine + model + account) | `frontend/components/chat/input/components/EngineModelPicker.svelte` |
32
+ | Chat send → backend | `frontend/services/chat/chat.service.ts` (`ws.emit('chat:stream', …)`), `backend/ws/chat/stream.ts` |
33
+ | Stream-manager (`EngineOutput` routing) | `backend/chat/stream-manager.ts` |
34
+
35
+ When in doubt: **mirror** the existing adapters and let `EngineOutput`
36
+ remain the only contract that crosses the adapter boundary.
@@ -0,0 +1,82 @@
1
+ [← Engine adapter guide](../README.md)
2
+
3
+ ## 7. Registering a binary in System Tools (`install-recipes.ts`)
4
+
5
+ `install-recipes.ts` is a **declarative** registry of install commands.
6
+ `install-runner.ts` is what actually runs them.
7
+
8
+ ### 7.1 Anatomy of a `Recipe`
9
+
10
+ ```ts
11
+ interface Recipe {
12
+ tool: ToolId;
13
+ autoInstallable: boolean;
14
+ unavailableReason?: string; // shown when not auto-installable
15
+ command?: string[]; // argv for Bun.spawn
16
+ shell?: { program; args }; // wrap argv (sh -c, pwsh -Command)
17
+ requiresCurl?: boolean; // staged static-curl if needed
18
+ pendingCurlDownload?: { version, url, sha256, archKey };
19
+ displayCommand?: string; // string for the confirm dialog
20
+ env?: Record<string, string>; // extra env for the subprocess
21
+ missingPrereqs: ToolId[];
22
+ manualInstructions: ManualInstruction[]; // always present (copy-able fallback)
23
+ }
24
+ ```
25
+
26
+ ### 7.2 Per-platform pattern
27
+
28
+ `resolveRecipe(tool)` switches to a per-tool resolver. Each resolver:
29
+ 1. Builds `base: Recipe` with full `manualInstructions` (always provide a
30
+ fallback for users on unsupported OSes).
31
+ 2. Checks platform (`process.platform`) and package manager:
32
+ - macOS: `brew`
33
+ - Linux: `apt | dnf | pacman | apk | zypper` (`detectLinuxPkgMgr`)
34
+ - Windows: `winget | scoop | choco` (`detectWindowsPkgMgr`)
35
+ 3. Checks privilege via `isElevated()` if the package manager needs
36
+ root/admin.
37
+ 4. If the installer uses `curl`, calls `attachCurlRequirement(base, label)`
38
+ so the runner can stage SHA-pinned static-curl from
39
+ `static-curl-assets.ts` when the system has no curl.
40
+ 5. Sets `autoInstallable = true` + `command` + `shell` + `displayCommand`,
41
+ or leaves it `false` with `unavailableReason` so the UI renders manual
42
+ instructions only.
43
+
44
+ ### 7.3 Status detection
45
+
46
+ `getToolStatus(tool)` returns `{ tool, installed, version, source }`:
47
+ - `chrome` has a special path (puppeteer cache scan + system Chrome).
48
+ - `cloudflared` at `~/.clopen/bin/cloudflared` is marked `source: 'clopen'`.
49
+ - Otherwise `resolveBinaryWithRefresh(tool)` + `runVersion(resolved)`.
50
+
51
+ ### 7.4 Runner
52
+
53
+ `install-runner.ts::startInstall(tool, userId)`:
54
+ 1. Verifies no other session is active for this tool
55
+ (`InstallAlreadyRunningError`).
56
+ 2. Resolves the recipe, validates `autoInstallable && command`
57
+ (`InstallNotAutoInstallableError`).
58
+ 3. If `requiresCurl`, calls `ensureCurlAvailable(...)` (downloads
59
+ pinned static-curl if needed, prepends its dir to PATH).
60
+ 4. `Bun.spawn(spawnArgs, { stdout: 'pipe', stderr: 'pipe', stdin: 'ignore', env })`.
61
+ 5. Streams stdout/stderr per-line into a ring buffer (10k lines) + emits
62
+ `system-tools:install-stream` to the user room.
63
+ 6. On exit: emits `system-tools:install-finished` + retains the session
64
+ for 5 minutes for re-attach.
65
+
66
+ Exit-code hints (`explainFailure(137|143, cancelled)`) explain SIGKILL OOM
67
+ or SIGTERM with actual total/free memory readings.
68
+
69
+ ### 7.5 Adding a new tool
70
+
71
+ 1. Add the literal to `ToolId` (`'goose'`).
72
+ 2. Write `resolveGooseRecipe(): Promise<Recipe>` following the
73
+ `resolveOpenCodeRecipe` pattern.
74
+ 3. Add a case in `resolveRecipe(tool)`.
75
+ 4. Add the literal to `TOOL_UNION` (`status.ts`, `install.ts`).
76
+ 5. Add `<ToolInstallCard tool="goose" ... />` in
77
+ `SystemToolsSettings.svelte`.
78
+ 6. (Optional) detect in `engine:<engine>-status` so Settings → Engines
79
+ knows the binary is installed.
80
+
81
+ ---
82
+
@@ -0,0 +1,240 @@
1
+ [← Engine adapter guide](../README.md)
2
+
3
+ ## 4. WebSocket routes
4
+
5
+ All handlers use `createRouter()` (Elysia + ws-server). Routers are merged
6
+ in `backend/ws/index.ts`. Four groups are relevant for engines:
7
+
8
+ | Group | Path | Purpose |
9
+ |---------------------------------|-------------------------------------|--------------------------------------------|
10
+ | `engine:claude-*` | `backend/ws/engine/claude/` | Status + Claude account CRUD |
11
+ | `engine:opencode-*` | `backend/ws/engine/opencode/` | Status + provider/account CRUD + restart |
12
+ | `engine:copilot-*` | `backend/ws/engine/copilot/` | Status + Copilot account CRUD |
13
+ | `system-tools:*` | `backend/ws/system-tools/` | Detect/install binaries |
14
+ | `models:list`, `chat:stream` | `backend/ws/settings/crud.ts`, `backend/ws/chat/stream.ts` | Model fetch + stream start |
15
+
16
+ ### 4.1 Claude — `engine:claude-*`
17
+
18
+ `backend/ws/engine/claude/index.ts` merges two sub-handlers:
19
+
20
+ | Event | Mode | Purpose |
21
+ |---------------------------------------------|---------|-----------------------------------------------|
22
+ | `engine:claude-status` | `.http` | `{ installed, version, activeAccount, accountsCount, backendOS }` |
23
+ | `engine:claude-accounts-list` | `.http` | List Claude accounts |
24
+ | `engine:claude-accounts-switch` | `.http` | Set active; calls `resetEnvironment()` so a new token is picked up on the next stream |
25
+ | `engine:claude-accounts-delete` | `.http` | |
26
+ | `engine:claude-accounts-rename` | `.http` | |
27
+ | `engine:claude-account-setup-start` | `.on` | Spawn PTY `claude setup-token` (state machine `waiting-url → waiting-token → done`) |
28
+ | `engine:claude-account-setup-submit` | `.on` | Send the auth code to the PTY |
29
+ | `engine:claude-account-setup-cancel` | `.on` | |
30
+ | `engine:claude-account-setup-url` (emit) | | OAuth URL detected in PTY output |
31
+ | `engine:claude-account-setup-complete` (emit) | | Token success → `engineQueries.createAccount` + `resetEnvironment()` |
32
+ | `engine:claude-account-setup-error` (emit) | | |
33
+ | `engine:claude-account-setup-pty-data` (emit) | | Stream raw PTY (debug) |
34
+
35
+ The Claude setup flow needs a PTY because Anthropic's CLI is interactive.
36
+ See `backend/ws/engine/claude/accounts.ts` for the state-machine details
37
+ (one `onData` listener + one `onExit` per session, the phase tracked in a
38
+ `phase` field).
39
+
40
+ ### 4.2 OpenCode — `engine:opencode-*`
41
+
42
+ `backend/ws/engine/opencode/index.ts` merges:
43
+
44
+ | Event | Purpose |
45
+ |---------------------------------------------|-----------------------------------------------|
46
+ | `engine:opencode-status` | `{ installed, version, backendOS }` |
47
+ | `engine:opencode-providers-list` | List `engine_providers WHERE engine_type='opencode'` + accounts |
48
+ | `engine:opencode-provider-add` | Create provider + first account (auto-active) |
49
+ | `engine:opencode-provider-remove` | Cascades to accounts |
50
+ | `engine:opencode-provider-toggle` | Flip `is_enabled` |
51
+ | `engine:opencode-provider-update-options` | Update JSON options (handler validates JSON) |
52
+ | `engine:opencode-account-add` | Add an account to a provider |
53
+ | `engine:opencode-account-switch` | |
54
+ | `engine:opencode-account-delete` | |
55
+ | `engine:opencode-account-rename` | |
56
+ | `engine:opencode-models-dev-list` | Cached catalog (auto-fetches if absent) |
57
+ | `engine:opencode-models-dev-fetch` | Force refetch |
58
+ | `engine:opencode-server-restart` | Stop subprocess + clear stored URL → next stream spawns a fresh server |
59
+
60
+ `engine:opencode-server-restart` first checks whether any OpenCode stream
61
+ is active: if so and `force` was not set, it returns
62
+ `{ needsConfirmation: true, activeChats: N }` so the UI can ask for
63
+ confirmation. When `force=true`, all OpenCode streams are `cancelStream`'d,
64
+ followed by `disposeEngine('opencode')` + `disposeOpenCodeClient(true)` —
65
+ the `forRestart` flag drops the stored URL and kills the server even if
66
+ Clopen did not spawn it (the reuse case).
67
+
68
+ #### Restart-Server pattern (long-lived server engines)
69
+
70
+ Engines that hold a **long-lived process or client** (OpenCode's `opencode
71
+ serve` subprocess, Copilot's `CopilotClient`) cache provider/account
72
+ credentials at boot or construction time. Adding, removing, or switching
73
+ an account does **not** automatically take effect for in-flight streams or
74
+ the cached client — the engine must be **restarted**. The adapter exposes
75
+ a `*-server-restart` event; the UI surfaces this to the user as a
76
+ **"Restart Server"** button in two places:
77
+
78
+ 1. **Settings → Engines** card — shown whenever the user has just changed
79
+ provider/account state (add / remove / switch). See
80
+ `AIEnginesSettings.svelte::handleRestartServer` (with the
81
+ `needsConfirmation` confirm-dialog flow) and
82
+ `forceRestartServer`.
83
+ 2. **Chat Input → next to the model/account picker** — shown when the
84
+ active session's account has just been switched mid-flight and the
85
+ user needs to apply it before sending the next prompt. See
86
+ `EngineModelPicker.svelte::ocNeedsRestart` / `restartOCServer`. The
87
+ button uses `force: true` so users in chat don't see another modal.
88
+
89
+ The handler contract any restart event must follow:
90
+
91
+ | Step | Behavior |
92
+ |---|---|
93
+ | 1 | Inspect the engine's active streams. If any exist and `force !== true`, return `{ needsConfirmation: true, activeChats: N }` — UI then opens a confirm dialog. |
94
+ | 2 | When `force === true`, call `cancelStream` on every active stream for that engine. |
95
+ | 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. |
96
+ | 4 | Resolve. The next `streamQuery` call will lazy-init the engine fresh against the new account state. |
97
+
98
+ After a successful restart the UI also refreshes models
99
+ (`modelStore.refreshModels(engineType)`) because the model catalog can
100
+ change with the credential.
101
+
102
+ **When a new engine does NOT need this:** if the engine spawns a
103
+ **fresh subprocess per turn** (Codex's `codex exec`, Claude's per-turn
104
+ `query()`), the credential is re-read at every turn and there is nothing
105
+ to "restart". Such engines do not implement `*-server-restart`. The
106
+ appropriate analog for shared-CLI-dotfile engines like Codex is the
107
+ auth-blob swap (§9.13) — performed inside `accounts-switch`, not via a
108
+ separate restart event.
109
+
110
+ ### 4.3 Copilot — `engine:copilot-*`
111
+
112
+ `backend/ws/engine/copilot/index.ts` merges:
113
+
114
+ | Event | Purpose |
115
+ |--------------------------------------|-----------------------------------------------|
116
+ | `engine:copilot-status` | `{ installed, version, activeAccount, accountsCount, backendOS }` |
117
+ | `engine:copilot-accounts-list` | List Copilot accounts |
118
+ | `engine:copilot-accounts-add` | Add account by submitting a GitHub PAT |
119
+ | `engine:copilot-accounts-switch` | Set active |
120
+ | `engine:copilot-accounts-delete` | |
121
+ | `engine:copilot-accounts-rename` | |
122
+ | `engine:copilot-server-restart` | Restart cached `CopilotClient` so a new PAT applies — same Restart-Server pattern as §4.2 |
123
+
124
+ The Copilot setup flow does not need a PTY — the user pastes a GitHub
125
+ Personal Access Token in the UI (Copilot Requests + read:user scope), and
126
+ the handler stores it via `engineQueries.createAccount`. No re-auth dance.
127
+
128
+ Copilot follows the **same Restart-Server pattern** documented in §4.2
129
+ because `CopilotClient` takes the PAT at construction time. Account
130
+ add / remove / switch flips a `needsRestart` flag in the UI that surfaces
131
+ a "Restart Server" button in both Settings → Engines and Chat Input.
132
+
133
+ ### 4.4 System Tools — `system-tools:*`
134
+
135
+ `backend/ws/system-tools/`:
136
+
137
+ | Event | Purpose |
138
+ |------------------------------------|---------------------------------------------|
139
+ | `system-tools:status` | Detect a single tool: `{ status, recipe, activeSession }` |
140
+ | `system-tools:status-all` | Hardcoded list `['git','claude','opencode','chrome','cloudflared']` |
141
+ | `system-tools:install-start` | Spawn the recipe via `install-runner` |
142
+ | `system-tools:install-cancel` | |
143
+ | `system-tools:install-session` | Snapshot session (for re-attach) |
144
+ | `system-tools:install-started` (emit) | Session begun |
145
+ | `system-tools:install-stream` (emit) | Per-line stdout/stderr |
146
+ | `system-tools:install-finished` (emit) | exit code + final status |
147
+
148
+ ### 4.5 `models:list` (in `backend/ws/settings/crud.ts`)
149
+
150
+ ```ts
151
+ .http('models:list', { data: { engine } }, async ({ data }) => {
152
+ const engine = await initializeEngine(data.engine);
153
+ const models = await engine.getAvailableModels();
154
+ registerModels(data.engine, models);
155
+ return models;
156
+ })
157
+ ```
158
+
159
+ The handler is **uniform across engines** — no per-engine short-circuits.
160
+ Every engine flows through `initializeEngine` → `engine.getAvailableModels()`
161
+ → `registerModels(...)` so the shared in-memory `modelRegistry` is always
162
+ populated regardless of whether the catalog is static or dynamic.
163
+
164
+ > **Why uniform.** The previous version hard-coded `if (engine === 'claude-code') return CLAUDE_CODE_MODELS`
165
+ > for static engines. That short-circuit bypassed `registerModels()`, so the
166
+ > backend registry stayed empty for static engines and the frontend's
167
+ > `getByEngine('claude-code')` returned nothing — the symptom that motivated
168
+ > this whole standardization. Don't reintroduce the special case; if a static
169
+ > engine's `getAvailableModels()` is too expensive to call repeatedly, cache
170
+ > inside the adapter (`CLAUDE_CODE_MODELS` is already a module-level const,
171
+ > so the call is free).
172
+
173
+ Each engine owns its model catalog in `backend/engine/adapters/<engine>/models.ts`:
174
+
175
+ | Engine | Catalog kind | Source |
176
+ |---------------|--------------|-----------------------------------------------------|
177
+ | `claude-code` | static | hardcoded `CLAUDE_CODE_MODELS` array |
178
+ | `codex` | static | hardcoded `CODEX_MODELS` array |
179
+ | `copilot` | dynamic | `client.listModels()` via `fetchCopilotModels` |
180
+ | `opencode` | dynamic | `client.config.providers()` via `fetchOpenCodeModels`|
181
+ | `qwen` | dynamic | OpenAI-compatible `/models` via `fetchQwenModels` |
182
+
183
+ Failure-mode contract (dynamic engines): return `EngineModel[]` and use
184
+ `[]` as the failure sentinel — never `null` (see §2.6). The picker then
185
+ renders an empty list rather than a stale cached catalog. `fetchOpenCodeModels`
186
+ and `fetchQwenModels` already follow this; new dynamic fetchers must too.
187
+
188
+ ### 4.6 Engine-specific config (presets — multi-provider / multi-region)
189
+
190
+ Anything else an engine needs that the frontend has to render — provider
191
+ choice, region selection, BYOK templates — also lives with the adapter
192
+ rather than `shared/constants/engines.ts`. The canonical filename is
193
+ `presets.ts` (see §2.6). Two adapters use this slot:
194
+
195
+ - **Qwen** (`backend/engine/adapters/qwen/presets.ts`) — `QWEN_PROVIDER_PRESETS`
196
+ array (DashScope CN/INTL, OpenRouter, Fireworks), `DEFAULT_QWEN_PRESET`,
197
+ `getQwenPreset(id)`. Static, hardcoded.
198
+ - **OpenCode** (`backend/engine/adapters/opencode/presets.ts`) — the
199
+ models.dev provider catalog: `fetchAndCacheModelsDevCatalog()` +
200
+ `getCachedModelsDevCatalog()`. Dynamic (fetched + cached in `settings`).
201
+
202
+ The wire-format types (`QwenProviderPresetId`, `QwenProviderPreset`,
203
+ `ModelsDevProvider`) live in `shared/types/unified/engine.ts` (or are
204
+ re-exported there) so the frontend stays typed without importing from
205
+ `$backend`.
206
+
207
+ Each adapter that has a `presets.ts` ships a thin WS router exposing it:
208
+
209
+ | Engine | WS event | Frontend store |
210
+ |-----------|------------------------------------------|---------------------------------------------------|
211
+ | `qwen` | `engine:qwen-presets-list` | `qwenPresetsStore` (`frontend/stores/features/qwen-presets.svelte.ts`) |
212
+ | `opencode`| `engine:opencode-models-dev-list` (+ `…-fetch` to refresh) | `opencodeProvidersStore.catalog` (`frontend/stores/features/opencode-providers.svelte.ts`) |
213
+
214
+ The rule: **frontend never imports `$backend` directly**. Runtime values
215
+ the frontend needs (model lists, presets, …) flow through WS endpoints;
216
+ types flow through `$shared`.
217
+
218
+ ### 4.7 `chat:stream` — the streaming entry point
219
+
220
+ `backend/ws/chat/stream.ts` accepts:
221
+
222
+ ```ts
223
+ {
224
+ sessionId: string,
225
+ chatSessionId: string,
226
+ projectPath: string,
227
+ prompt: UserMessage,
228
+ engine: { type, provider, model: { id, name }, account: { id, name } },
229
+ sender: { id, name }
230
+ }
231
+ ```
232
+
233
+ The handler calls `streamManager.startStream(...)`, which then:
234
+ 1. Resolves `getProjectEngine(projectId, engine.type)`
235
+ 2. Calls `engine.streamQuery({ projectPath, prompt, providerSlug, modelId, accountId, mcpContext, ... })`
236
+ 3. Iterates over `EngineOutput` and emits each one to the chat session room
237
+ via `ws.emit.chatSession(...)`.
238
+
239
+ ---
240
+
@@ -0,0 +1,59 @@
1
+ /**
2
+ * Shared helpers for one-shot structured JSON generation.
3
+ *
4
+ * Engines whose SDKs lack a native JSON-schema output mode (OpenCode, Copilot,
5
+ * Qwen) fall back to prompt engineering: instruct the model to emit JSON only,
6
+ * then parse it out of whatever text the model returns. The native path on
7
+ * Claude and Codex doesn't need these helpers.
8
+ */
9
+
10
+ /** Wrap a user prompt with a JSON-only instruction and the target schema. */
11
+ export function buildJsonPrompt(prompt: string, schema: Record<string, unknown>): string {
12
+ return `${prompt}
13
+
14
+ IMPORTANT: You MUST respond with ONLY a valid JSON object matching this schema, no other text, no markdown fences, no commentary:
15
+ ${JSON.stringify(schema, null, 2)}`;
16
+ }
17
+
18
+ /**
19
+ * Extract a JSON object from a model response.
20
+ *
21
+ * Models routinely wrap JSON in markdown fences or prose even when asked
22
+ * not to. This searches in order:
23
+ * 1. ```json … ``` or ``` … ``` fenced block
24
+ * 2. The first balanced `{ … }` substring
25
+ * 3. The raw trimmed text
26
+ *
27
+ * Throws if nothing parses.
28
+ */
29
+ export function extractJson<T = unknown>(text: string): T {
30
+ const trimmed = text.trim();
31
+ if (!trimmed) {
32
+ throw new Error('Empty response — no JSON to parse');
33
+ }
34
+
35
+ const candidates: string[] = [];
36
+ const fenced = trimmed.match(/```(?:json)?\s*([\s\S]*?)```/);
37
+ if (fenced) candidates.push(fenced[1].trim());
38
+
39
+ const braceStart = trimmed.indexOf('{');
40
+ const braceEnd = trimmed.lastIndexOf('}');
41
+ if (braceStart !== -1 && braceEnd > braceStart) {
42
+ candidates.push(trimmed.slice(braceStart, braceEnd + 1));
43
+ }
44
+
45
+ candidates.push(trimmed);
46
+
47
+ let lastError: unknown;
48
+ for (const candidate of candidates) {
49
+ try {
50
+ return JSON.parse(candidate) as T;
51
+ } catch (err) {
52
+ lastError = err;
53
+ }
54
+ }
55
+ throw new Error(
56
+ `Response did not contain valid JSON: ${trimmed.slice(0, 200)}${trimmed.length > 200 ? '…' : ''}` +
57
+ (lastError instanceof Error ? ` (${lastError.message})` : '')
58
+ );
59
+ }
@@ -0,0 +1,131 @@
1
+ import { afterEach, beforeEach, describe, expect, mock, test } from 'bun:test';
2
+ import { rm, mkdir } from 'node:fs/promises';
3
+ import { join } from 'node:path';
4
+ import { tmpdir } from 'node:os';
5
+
6
+ // Stub settingsQueries before importing the module under test so the file-size
7
+ // limit is controllable and never touches a real database during unit tests.
8
+ let mockSettingsRow: { key: string; value: string; updated_at: string } | null = null;
9
+ await mock.module('../database/queries', () => ({
10
+ settingsQueries: {
11
+ get: (_key: string) => mockSettingsRow,
12
+ getAll: () => [],
13
+ set: () => {},
14
+ delete: () => {}
15
+ }
16
+ }));
17
+
18
+ const { extractZipOperation } = await import('./file-archive');
19
+
20
+ function setLimitMB(mb: number): void {
21
+ mockSettingsRow = {
22
+ key: 'system:settings',
23
+ value: JSON.stringify({ maxFileSizeMB: mb }),
24
+ updated_at: ''
25
+ };
26
+ }
27
+
28
+ function writeU32(buf: Uint8Array, off: number, val: number): void {
29
+ buf[off] = val & 0xff;
30
+ buf[off + 1] = (val >>> 8) & 0xff;
31
+ buf[off + 2] = (val >>> 16) & 0xff;
32
+ buf[off + 3] = (val >>> 24) & 0xff;
33
+ }
34
+
35
+ function readU32(buf: Uint8Array, off: number): number {
36
+ return (buf[off] | (buf[off + 1] << 8) | (buf[off + 2] << 16) | (buf[off + 3] << 24)) >>> 0;
37
+ }
38
+
39
+ // Overwrite the uncompressed-size fields in a single-file zip's local and
40
+ // central headers with a forged (tiny) value, leaving the compressed data and
41
+ // compressed-size fields intact. Models an attacker lying about extracted size
42
+ // to slip past any check that trusts the zip metadata. Assumes no archive
43
+ // comment (true for fflate's zipSync output).
44
+ function forgeUncompressedSizes(zip: Uint8Array, fakeSize: number): Uint8Array {
45
+ const out = zip.slice();
46
+ const eocd = out.length - 22;
47
+ const cdOffset = readU32(out, eocd + 16);
48
+ writeU32(out, cdOffset + 24, fakeSize); // central directory header
49
+ writeU32(out, 22, fakeSize); // local file header (single file at offset 0)
50
+ return out;
51
+ }
52
+
53
+ describe('extractZipOperation — output-size cap', () => {
54
+ let testDir: string;
55
+
56
+ beforeEach(async () => {
57
+ mockSettingsRow = null;
58
+ testDir = join(tmpdir(), `clopen-archive-test-${Date.now()}-${Math.random().toString(36).slice(2)}`);
59
+ await mkdir(testDir, { recursive: true });
60
+ });
61
+
62
+ afterEach(async () => {
63
+ mockSettingsRow = null;
64
+ await rm(testDir, { recursive: true, force: true });
65
+ });
66
+
67
+ test('extracts a normal archive and writes its contents', async () => {
68
+ const { zipSync } = await import('fflate');
69
+ const zip = zipSync(
70
+ {
71
+ 'file1.txt': new TextEncoder().encode('Hello world, this is a test file'),
72
+ 'file2.txt': new TextEncoder().encode('Another test file with some content')
73
+ },
74
+ { level: 6 }
75
+ );
76
+ const archivePath = join(testDir, 'normal.zip');
77
+ const extractDir = join(testDir, 'extracted');
78
+ await Bun.write(archivePath, zip);
79
+
80
+ const result = await extractZipOperation(archivePath, extractDir);
81
+
82
+ expect(result.entries).toBe(2);
83
+ expect(await Bun.file(join(extractDir, 'file1.txt')).text()).toBe('Hello world, this is a test file');
84
+ expect(await Bun.file(join(extractDir, 'file2.txt')).text()).toBe('Another test file with some content');
85
+ });
86
+
87
+ test('rejects when actual decompressed output exceeds the limit', async () => {
88
+ // 4MB of zeros compresses to a few KB, so the compressed archive sails
89
+ // past the compressed-size guard — only the streaming output cap catches it.
90
+ setLimitMB(1);
91
+ const { zipSync } = await import('fflate');
92
+ const zip = zipSync({ 'big.bin': new Uint8Array(4 * 1024 * 1024) }, { level: 9 });
93
+ const archivePath = join(testDir, 'big.zip');
94
+ await Bun.write(archivePath, zip);
95
+
96
+ expect(zip.byteLength).toBeLessThan(1024 * 1024); // compressed archive is under the limit
97
+
98
+ await expect(extractZipOperation(archivePath, join(testDir, 'out'))).rejects.toThrow(
99
+ /exceeds maximum allowed size/
100
+ );
101
+ });
102
+
103
+ test('rejects even when the zip metadata forges a tiny uncompressed size', async () => {
104
+ // The whole point of the reshape: the cap counts ACTUAL decompressed
105
+ // bytes, so lying about the size in the central directory cannot bypass it.
106
+ setLimitMB(1);
107
+ const { zipSync } = await import('fflate');
108
+ const honest = zipSync({ 'bomb.bin': new Uint8Array(4 * 1024 * 1024) }, { level: 9 });
109
+ const forged = forgeUncompressedSizes(honest, 10);
110
+
111
+ const eocd = forged.length - 22;
112
+ const cdOffset = readU32(forged, eocd + 16);
113
+ expect(readU32(forged, cdOffset + 24)).toBe(10); // metadata now claims 10 bytes
114
+
115
+ const archivePath = join(testDir, 'forged.zip');
116
+ await Bun.write(archivePath, forged);
117
+
118
+ await expect(extractZipOperation(archivePath, join(testDir, 'out'))).rejects.toThrow(
119
+ /exceeds maximum allowed size/
120
+ );
121
+ });
122
+
123
+ test('rejects path-traversal entries before writing them', async () => {
124
+ const { zipSync } = await import('fflate');
125
+ const zip = zipSync({ '../escape.txt': new TextEncoder().encode('nope') }, { level: 6 });
126
+ const archivePath = join(testDir, 'traversal.zip');
127
+ await Bun.write(archivePath, zip);
128
+
129
+ await expect(extractZipOperation(archivePath, join(testDir, 'out'))).rejects.toThrow(/Unsafe path/);
130
+ });
131
+ });