@myrialabs/clopen 0.4.21 → 0.4.23

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 (86) hide show
  1. package/README.md +2 -1
  2. package/backend/artifacts/generate.ts +11 -5
  3. package/backend/auth/permissions.ts +8 -8
  4. package/backend/engine/README.md +11 -8
  5. package/backend/engine/adapters/codex/error-handler.ts +1 -1
  6. package/backend/engine/adapters/qwen/error-handler.ts +1 -1
  7. package/backend/engine/docs/adapter-contract.md +66 -2
  8. package/backend/engine/docs/adding-an-engine.md +46 -7
  9. package/backend/engine/docs/frontend-and-chat.md +80 -17
  10. package/backend/engine/docs/lessons-learned.md +126 -7
  11. package/backend/engine/docs/quick-reference.md +12 -3
  12. package/backend/engine/docs/{system-tools.md → stack.md} +35 -6
  13. package/backend/engine/docs/websocket-routes.md +54 -15
  14. package/backend/engine/install-runner.ts +4 -4
  15. package/backend/engine/resolve-model.ts +87 -0
  16. package/backend/engine/structured-helpers.test.ts +64 -0
  17. package/backend/engine/structured-helpers.ts +105 -13
  18. package/backend/mcp/README.md +32 -11
  19. package/backend/mcp/internal/config.ts +3 -20
  20. package/backend/mcp/internal/servers/browser-automation/actions/console.ts +65 -0
  21. package/backend/mcp/internal/servers/browser-automation/actions/dom-analyze.ts +202 -0
  22. package/backend/mcp/internal/servers/browser-automation/actions/index.ts +31 -0
  23. package/backend/mcp/internal/servers/browser-automation/actions/input.ts +332 -0
  24. package/backend/mcp/internal/servers/browser-automation/actions/inspect.ts +158 -0
  25. package/backend/mcp/internal/servers/browser-automation/actions/navigation.ts +157 -0
  26. package/backend/mcp/internal/servers/browser-automation/actions/shared.ts +60 -0
  27. package/backend/mcp/internal/servers/browser-automation/actions/tabs.ts +157 -0
  28. package/backend/mcp/internal/servers/browser-automation/actions/types.ts +79 -0
  29. package/backend/mcp/internal/servers/browser-automation/context.ts +100 -0
  30. package/backend/mcp/internal/servers/browser-automation/description.ts +60 -0
  31. package/backend/mcp/internal/servers/browser-automation/format.ts +62 -0
  32. package/backend/mcp/internal/servers/browser-automation/index.ts +36 -784
  33. package/backend/mcp/internal/servers/browser-automation/paths.ts +71 -0
  34. package/backend/mcp/internal/servers/browser-automation/runner.ts +269 -0
  35. package/backend/mcp/internal/servers/browser-automation/schema.ts +26 -0
  36. package/backend/preview/browser/browser-console-manager.ts +310 -156
  37. package/backend/preview/browser/browser-dialog-handler.ts +45 -16
  38. package/backend/preview/browser/browser-host-bridge.ts +471 -0
  39. package/backend/preview/browser/browser-interaction-handler.ts +868 -297
  40. package/backend/preview/browser/browser-mcp-control.ts +7 -2
  41. package/backend/preview/browser/browser-native-ui-handler.ts +455 -81
  42. package/backend/preview/browser/browser-navigation-tracker.ts +56 -0
  43. package/backend/preview/browser/browser-pool.ts +83 -9
  44. package/backend/preview/browser/browser-preview-service.ts +432 -53
  45. package/backend/preview/browser/browser-tab-manager.ts +16 -16
  46. package/backend/preview/browser/browser-video-capture.ts +1334 -386
  47. package/backend/preview/browser/capture-profile.ts +213 -0
  48. package/backend/preview/browser/element-locator.ts +357 -0
  49. package/backend/preview/browser/frame-targeting.ts +92 -0
  50. package/backend/preview/browser/scripts/audio-stream.ts +258 -78
  51. package/backend/preview/browser/scripts/host-bridge.ts +1277 -0
  52. package/backend/preview/browser/scripts/video-stream.ts +803 -177
  53. package/backend/preview/browser/types.ts +397 -37
  54. package/backend/utils/cli.ts +1 -1
  55. package/backend/utils/path-enrich.ts +2 -2
  56. package/backend/ws/README.md +1 -1
  57. package/backend/ws/artifacts/generate.ts +2 -1
  58. package/backend/ws/engine/codex/accounts.ts +1 -1
  59. package/backend/ws/engine/codex/status.ts +1 -1
  60. package/backend/ws/git/branch-name.ts +11 -5
  61. package/backend/ws/git/commit-message.ts +11 -5
  62. package/backend/ws/index.ts +3 -3
  63. package/backend/ws/preview/browser/host.ts +95 -0
  64. package/backend/ws/preview/browser/interact.ts +204 -10
  65. package/backend/ws/preview/browser/native-ui.ts +31 -1
  66. package/backend/ws/preview/browser/tab-info.ts +10 -1
  67. package/backend/ws/preview/browser/tab.ts +43 -0
  68. package/backend/ws/preview/browser/webcodecs.ts +180 -53
  69. package/backend/ws/preview/index.ts +58 -1
  70. package/backend/ws/{system-tools → stack}/access.ts +1 -1
  71. package/backend/ws/stack/index.ts +16 -0
  72. package/backend/ws/{system-tools → stack}/install.ts +7 -7
  73. package/backend/ws/{system-tools → stack}/status.ts +7 -7
  74. package/dist/assets/{index-CEGW8vEt.js → index-DH_GO0Lf.js} +1 -1
  75. package/dist/assets/{index-B8YRz8wG.js → index-igSQ3JaM.js} +1 -1
  76. package/dist/assets/main-BD3-qPfT.css +1 -0
  77. package/dist/assets/{main-D-2ByODy.js → main-D-d8SFfW.js} +384 -358
  78. package/dist/assets/preview-video.worker-DcpDhCWL.js +1 -0
  79. package/dist/index.html +2 -2
  80. package/package.json +1 -1
  81. package/shared/types/stores/settings.ts +6 -0
  82. package/backend/mcp/internal/servers/browser-automation/actions.ts +0 -159
  83. package/backend/mcp/internal/servers/browser-automation/browser.ts +0 -375
  84. package/backend/mcp/internal/servers/browser-automation/inspection.ts +0 -495
  85. package/backend/ws/system-tools/index.ts +0 -16
  86. package/dist/assets/main-D8I0MfRQ.css +0 -1
@@ -695,10 +695,12 @@ Pi equivalents) for the reference implementation.
695
695
 
696
696
  ### 10.16 `generateStructured` — schema strictness & part-extraction fallback
697
697
 
698
- `generateStructured` powers the AI commit-message generator (and any
699
- future one-shot JSON callers). Each adapter satisfies the same
700
- `StructuredGenerationOptions → Promise<T>` contract, but the SDKs split
701
- sharply on whether they accept a schema natively:
698
+ `generateStructured` powers three one-shot JSON callers: the AI
699
+ commit-message generator, the branch-name generator, and artifact
700
+ authoring (Skills/Commands/Subagents/Instructions from a purpose). Each
701
+ adapter satisfies the same `StructuredGenerationOptions → Promise<T>`
702
+ contract, but the SDKs split sharply on whether they accept a schema
703
+ natively:
702
704
 
703
705
  | Engine | Strategy | Mechanism |
704
706
  |--------------|-----------------|--------------------------------------------------------------|
@@ -707,6 +709,13 @@ sharply on whether they accept a schema natively:
707
709
  | OpenCode | Prompt | `client.session.prompt({ tools: {}, … })`, parse text/reasoning parts |
708
710
  | Copilot | Prompt | `createSession({ availableTools: [], streaming: false })` + `sendAndWait` |
709
711
  | Qwen | Prompt | `query({ coreTools: [], maxSessionTurns: 1 })`, read `SDKResultMessageSuccess.result` |
712
+ | Pi | Prompt | tool-less in-memory `createAgentSession`, parse final assistant text |
713
+ | Cline | Prompt | tool-less `Agent`, parse final assistant text |
714
+ | Cursor | Prompt | `Agent.send(buildJsonPrompt(...))` → `run.wait().result` (local agents always carry the built-in tools, so the prompt is the only lever) |
715
+
716
+ **Test on a prompt-engineered engine.** Three of the four bugs in this
717
+ section only reproduce off the native path. Claude Code is the worst
718
+ possible smoke test for `generateStructured`.
710
719
 
711
720
  **Two cross-cutting gotchas you will hit.**
712
721
 
@@ -757,11 +766,33 @@ OpenCode adapter:
757
766
  Filter out `ignored`/`synthetic` parts so the SDK's own scratch text
758
767
  doesn't leak into the JSON parser. Log the part-type breakdown in the
759
768
  error message so the next failure is diagnosable.
760
- - **Extract JSON tolerantly.** `extractJson()` tries, in order: a
761
- ` ```json ` fenced block, the first balanced `{ … }`, then the raw
762
- trimmed text. Models routinely ignore the "no markdown fences"
769
+ - **Extract JSON tolerantly.** `extractJson()` tries, in order: every
770
+ ` ```json ` fenced block, every top-level balanced `{ … }`, a greedy
771
+ first-brace-to-last-brace slice, then the raw trimmed text — parsing
772
+ each one twice, the second time with control characters inside string
773
+ literals escaped. Models routinely ignore the "no markdown fences"
763
774
  instruction; the parser should not.
764
775
 
776
+ Two failure modes justify the balanced scan and the repair pass, and
777
+ both are covered by `structured-helpers.test.ts`:
778
+
779
+ - **Trailing commentary.** A model that emits the object and then adds
780
+ "Let me know if you want changes!" produces JSC's
781
+ `Unable to parse JSON string` (its message for *valid JSON followed
782
+ by anything*), and the old first-`{`-to-last-`}` slice broke too
783
+ whenever that commentary contained a brace. Brace counting must be
784
+ string-aware or a `}` inside a value closes the object early.
785
+ - **Raw newlines in string values.** JSON forbids a literal newline
786
+ inside a string, but any field holding Markdown (an artifact body, a
787
+ commit body) attracts them — which is why artifact generation broke
788
+ on models that git commit generation, with its short single-line
789
+ fields, never tripped.
790
+
791
+ A truncated response still throws rather than half-parsing: a draft
792
+ missing half its body is worse than a clear failure. The error preview
793
+ shows both ends of the text so truncation and trailing prose are
794
+ distinguishable from the log alone.
795
+
765
796
  The native engines (Claude, Codex) skip these — Claude exposes
766
797
  `structured_output` on the `result` message and Codex's
767
798
  `Turn.finalResponse` is already the JSON string. They only fall through
@@ -775,6 +806,30 @@ hands its `signal` to whatever the SDK exposes (Codex
775
806
  The contract is the same as `streamQuery`: aborting cancels the in-flight
776
807
  request, not just the await.
777
808
 
809
+ **3. Never trust a caller-supplied `providerSlug`.** The adapters split
810
+ again on whether they read it at all: Claude, Codex, Qwen, Copilot, and
811
+ Cursor key off `modelId` alone, while OpenCode passes it as
812
+ `model.providerID` and Pi/Cline resolve their account by it. A client
813
+ that persists engine/provider/model as separate fields and updates only
814
+ some of them therefore fails on exactly three engines and silently
815
+ "works" on the other five — which is how a `commitGenerator.provider`
816
+ stuck at its `'anthropic'` seed surfaced as `OpenCode returned empty
817
+ response` while Claude Code was fine.
818
+
819
+ The engine catalog is the only source of truth for which provider (and
820
+ account) a model belongs to, so every `generateStructured` call site
821
+ routes through `resolveGenerationTarget(engine, modelId, providerHint)`
822
+ in `backend/engine/resolve-model.ts` first. It reads the registry
823
+ (filled by `models:list`, fetching the catalog only on a miss), returns
824
+ the catalog's provider, and throws a "pick it again in Settings →
825
+ Models" error when the model belongs to no provider the engine offers.
826
+ It also forwards the model's `accountId` when the catalog carries a real
827
+ one — today every adapter reports `account.id: 0` (account is a separate
828
+ per-chat dimension, and these routes have no account picker), so engines
829
+ keep falling back to their active account. New engines are covered
830
+ without touching a call site; do not reintroduce `providerSlug:
831
+ data.providerSlug`.
832
+
778
833
  **Engine-not-implemented errors.** `backend/ws/git/commit-message.ts`
779
834
  guards on `engine.generateStructured` — if you add an engine that can't
780
835
  implement structured output, leave the property `undefined` and the WS
@@ -1088,6 +1143,17 @@ Consequences for an adapter:
1088
1143
  `backend/engine/sdk-loader.ts` (which does `Bun.resolveSync(pkg, stackDir)` +
1089
1144
  dynamic import, cached).
1090
1145
 
1146
+ - **Audit *every* file in the adapter, not just `stream.ts`.** This is the one
1147
+ rule that reliably survives the conversion and then gets violated again,
1148
+ because a leftover value import is **invisible in development**: the repo's
1149
+ own `node_modules` has the devDependency, so `import { query } from
1150
+ '@qwen-code/sdk'` resolves fine locally and only fails for end users, whose
1151
+ stack dir is the only copy. Two shipped adapters had exactly this — Qwen's
1152
+ `stream.ts` (`query`) and OpenCode's `server.ts`
1153
+ (`createOpencodeClient`) — both converted after the fact. A plain
1154
+ `await import('<pkg>')` is the same bug: it resolves from the process's own
1155
+ paths, not the stack dir. `loadEngineSdk` is the only correct seam.
1156
+
1091
1157
  - **Loading is version-guarded.** `loadEngineSdk` refuses an SDK whose installed
1092
1158
  version ≠ the pinned version, throwing `EngineNotReadyError`
1093
1159
  (`reason: 'not-installed' | 'needs-update'`). The stream-manager surfaces that
@@ -1106,3 +1172,56 @@ The same lazy-load applies to the one non-adapter consumer of the Claude SDK:
1106
1172
  `@anthropic-ai/claude-agent-sdk` only on the Claude path (see
1107
1173
  `backend/mcp/README.md`).
1108
1174
 
1175
+ ### 10.22 Reasoning effort — keep it native, keep it capability-driven
1176
+
1177
+ Five of the eight engines expose a reasoning/thinking knob and **no two
1178
+ call it the same thing**: Claude has `thinking` *and* `effort`, Codex has
1179
+ `modelReasoningEffort`, Copilot has `SessionConfig.reasoningEffort`, Pi
1180
+ has `thinkingLevel`, and Cursor has no dedicated field at all — it's one
1181
+ entry in a generic `ModelSelection.params[]`. Their vocabularies don't
1182
+ line up either (`minimal` exists only on Codex; `max`/`xhigh` only on
1183
+ some Claude models; Pi's set is per-model).
1184
+
1185
+ The obvious design — normalize everything to `low | medium | high` —
1186
+ loses information in both directions: it can't express `off`, and it
1187
+ either hides levels a model does support or offers levels it doesn't.
1188
+ So the token stays **native and opaque** end to end. `EngineQueryOptions.
1189
+ reasoningEffort` is a `string` that only the adapter which produced it
1190
+ (in its `models.ts`) knows how to read (in its `stream.ts`); the
1191
+ stream-manager, the WS layer, the session row, and the frontend all just
1192
+ carry it.
1193
+
1194
+ Three consequences worth internalizing:
1195
+
1196
+ **The model advertises, the UI obeys.** `EngineModel.capabilities.
1197
+ reasoningControl` (`{ levels, default }`) is the entire contract. The
1198
+ picker renders a pill when it's present and nothing when it's absent —
1199
+ which is how Qwen, OpenCode, and Cline stay knob-less without a single
1200
+ engine name appearing in the frontend. Prefer deriving the level list
1201
+ from the SDK's own payload (Copilot's `supportedReasoningEfforts`, Pi's
1202
+ `getSupportedThinkingLevels`, Cursor's `ModelParameterDefinition`) over
1203
+ hardcoding; only static catalogs (Claude, Codex) spell it out.
1204
+
1205
+ **Clamp on the way in.** The token reaching `streamQuery` may be stale —
1206
+ persisted on a session whose model has since changed, or restored from a
1207
+ `reasoningDefaults` entry written by an older catalog. Every adapter
1208
+ validates against its own set and falls back to the engine default
1209
+ instead of forwarding garbage to the SDK (`clampThinkingLevel` for Pi, a
1210
+ literal `Set` for Claude/Codex/Copilot, a `::`-shape check for Cursor).
1211
+
1212
+ **Encode structure in the value, not in new fields.** Cursor needs a
1213
+ parameter *id* alongside the level, so its tokens are
1214
+ `"<paramId>::<value>"` and `buildCursorModelSelection` splits them back
1215
+ apart. That keeps `EngineQueryOptions` at one string no matter how
1216
+ baroque the next SDK's knob turns out to be. Resist adding a second
1217
+ field for the sixth engine.
1218
+
1219
+ The frontend keeps `chatModelState.reasoningEffort` at the **effective**
1220
+ level rather than "only what the user explicitly picked" — an `$effect`
1221
+ re-seeds it on every model change from `settings.reasoningDefaults[modelId]`
1222
+ → `reasoningControl.default`, and nulls it for knob-less models. That
1223
+ costs one effect and buys two things: the value sent with the turn always
1224
+ matches what actually ran (so `MessageEngine.reasoningEffort` in the Raw
1225
+ view is truthful), and a level valid for the previous model can never
1226
+ leak into a request for the next one.
1227
+
@@ -30,17 +30,26 @@
30
30
  | Permission enforcement (runtime hook) | `backend/permissions/service.ts::resolvePermissionsFromDb` + `isToolAllowed` (see §8.4) |
31
31
  | Auth-blob swap into shared CLI dotfile | Pattern only (no implementation yet); see §3.3 callout + §10.13 |
32
32
  | Restart-Server pattern (long-lived engines) | `backend/ws/engine/opencode/providers.ts::engine:opencode-server-restart`, `frontend/components/chat/input/components/EngineModelPicker.svelte::restartOCServer`, `engines/panels/OpenCodePanel.svelte::handleRestartServer`/`forceRestartServer` |
33
- | `generateStructured` (no tools, JSON) | `claude/stream.ts::generateStructured` (native `outputFormat`), `codex/stream.ts::generateStructured` (native `outputSchema`), `opencode/stream.ts::generateStructured` + `copilot/stream.ts::generateStructured` + `qwen/stream.ts::generateStructured` (prompt-engineered via `backend/engine/structured-helpers.ts`). See §10.16 for the strict-schema + part-fallback gotchas. |
33
+ | `generateStructured` (no tools, JSON) | `claude/stream.ts::generateStructured` (native `outputFormat`), `codex/stream.ts::generateStructured` (native `outputSchema`); `opencode` / `copilot` / `qwen` / `pi` / `cline` / `cursor` are prompt-engineered via `backend/engine/structured-helpers.ts` (`buildJsonPrompt` + `extractJson`). See §10.16 for the strict-schema + part-fallback gotchas. |
34
+ | Resolve provider/account for a one-shot call | `backend/engine/resolve-model.ts::resolveGenerationTarget` — catalog is truth, caller's `providerSlug` is a hint (§10.16 point 3) |
35
+ | Tolerant JSON extraction (fences, trailing prose, raw newlines) | `backend/engine/structured-helpers.ts::extractJson` + `structured-helpers.test.ts` |
36
+ | Keep engine/provider/model from drifting apart | `frontend/utils/model-override.ts::modelFieldsOf` (spread it when persisting a generator override) |
37
+ | Reasoning-effort levels a model offers | `EngineModel.capabilities.reasoningControl` built in `<engine>/models.ts` via `toReasoningOptions` (`shared/constants/engines.ts`); §2.4a |
38
+ | Apply the chosen reasoning level to the SDK | `claude/stream.ts` (`thinking` + `effort`), `codex/stream.ts` (`modelReasoningEffort`), `copilot/stream.ts` (`reasoningEffort`), `pi/stream.ts` (`thinkingLevel` + `clampThinkingLevel`), `cursor/stream.ts::buildCursorModelSelection` (`params[]`); §10.22 |
39
+ | Per-session reasoning persistence + collab sync | `chat_sessions.reasoning_effort` (migration `065`), `sessionQueries.updateReasoning`, `chat:reasoning-sync` in `backend/ws/chat/stream.ts` |
34
40
  | Error normalisation | `claude/error-handler.ts`, `copilot/error-handler.ts`, `opencode/error-handler.ts`, `qwen/error-handler.ts`, `codex/error-handler.ts` |
35
41
  | DB provider/account access | `backend/database/queries/engine-queries.ts` |
36
42
  | Host-tool + engine-SDK install recipes | `backend/engine/install-recipes.ts` |
37
43
  | On-demand engine-SDK loader (managed dir) | `backend/engine/sdk-loader.ts` (`getStackEnginesDir`, `loadEngineSdk`) |
38
44
  | Streaming install logs | `backend/engine/install-runner.ts` |
45
+ | Fresh-install default engine (auto OpenCode)| `backend/engine/bootstrap-default-engine.ts::ensureDefaultEngineInstalled`, called from `backend/bootstrap.ts::bootstrapAfterDbInit` (startup **and** Clear All Data); §7.8 |
46
+ | Engine + host-tool brand icons (SSOT) | `shared/constants/tool-icons.ts::TOOL_ICONS` (referenced by `ENGINES` and the Stack cards) |
39
47
  | Frontend account/provider stores | `frontend/stores/features/{claude-accounts,copilot-accounts,opencode-providers}.svelte.ts` |
40
48
  | Frontend chat-model state | `frontend/stores/ui/chat-model.svelte.ts` |
41
49
  | Settings UI (Engines) | `frontend/components/settings/engines/AIEnginesSettings.svelte` (shell + grid) + `engines/panels/*Panel.svelte` (one per engine) |
42
- | Settings UI (Stack; id stays `system-tools`) | `frontend/components/settings/system-tools/{SystemToolsSettings,ToolInstallCard}.svelte` |
43
- | Chat picker (engine + model + account) | `frontend/components/chat/input/components/EngineModelPicker.svelte` |
50
+ | Settings UI (Stack) | `frontend/components/settings/stack/{StackSettings,ToolInstallCard}.svelte` |
51
+ | Chat picker (engine + model + account + reasoning) | `frontend/components/chat/input/components/EngineModelPicker.svelte` |
52
+ | Settings → Models (catalog + per-model reasoning defaults) | `frontend/components/settings/model/EngineModelPicker.svelte` (mounted by `AssistantSettings` / `GitSettings` / `ArtifactsSettings`); `setReasoningDefault` in `frontend/stores/features/settings.svelte.ts` |
44
53
  | Chat send → backend | `frontend/services/chat/chat.service.ts` (`ws.emit('chat:stream', …)`), `backend/ws/chat/stream.ts` |
45
54
  | Stream-manager (`EngineOutput` routing) | `backend/chat/stream-manager.ts` |
46
55
 
@@ -4,8 +4,9 @@
4
4
 
5
5
  `install-recipes.ts` is a **declarative** registry of install commands.
6
6
  `install-runner.ts` is what actually runs them. The Settings panel that
7
- surfaces these is displayed as **Stack** (its internal WS route/section id is
8
- still `system-tools`).
7
+ surfaces these is **Stack** — the name is consistent all the way down: the WS
8
+ namespace is `stack:*` (`backend/ws/stack/`), the settings section id is
9
+ `stack`, and the UI lives in `frontend/components/settings/stack/`.
9
10
 
10
11
  Two kinds of `ToolId` live here:
11
12
 
@@ -95,8 +96,8 @@ additionally carry `requiredVersion` + `needsUpdate`):
95
96
  pinned static-curl if needed, prepends its dir to PATH).
96
97
  4. `Bun.spawn(spawnArgs, { stdout: 'pipe', stderr: 'pipe', stdin: 'ignore', env })`.
97
98
  5. Streams stdout/stderr per-line into a ring buffer (10k lines) + emits
98
- `system-tools:install-stream` to the user room.
99
- 6. On exit: emits `system-tools:install-finished` + retains the session
99
+ `stack:install-stream` to the user room.
100
+ 6. On exit: emits `stack:install-finished` + retains the session
100
101
  for 5 minutes for re-attach.
101
102
 
102
103
  Exit-code hints (`explainFailure(137|143, cancelled)`) explain SIGKILL OOM
@@ -110,7 +111,7 @@ or SIGTERM with actual total/free memory readings.
110
111
  3. Add a case in `resolveRecipe(tool)`.
111
112
  4. Add the literal to `TOOL_UNION` (`status.ts`, `install.ts`).
112
113
  5. Add `<ToolInstallCard tool="goose" ... />` in
113
- `SystemToolsSettings.svelte`.
114
+ `StackSettings.svelte`.
114
115
  6. (Optional) detect in `engine:<engine>-status` so Settings → Engines
115
116
  knows the binary is installed.
116
117
 
@@ -127,12 +128,40 @@ Engine SDKs don't need a hand-written resolver. When you add an engine
127
128
  3. `resolveEngineRecipe(tool)` handles the rest automatically (installs into the
128
129
  stack dir at the pinned version).
129
130
  4. Add the literal to `TOOL_UNION` (`status.ts`, `install.ts`).
130
- 5. Add `<ToolInstallCard tool="newengine" ... />` in `SystemToolsSettings.svelte`.
131
+ 5. Add `<ToolInstallCard tool="newengine" ... />` in `StackSettings.svelte`.
131
132
 
132
133
  There is no "Check for Updates" for engines — their versions move in lockstep
133
134
  with clopen releases, so `version-check.ts` has no update source for them. The
134
135
  Stack card instead shows **Update required** whenever the installed version ≠
135
136
  the pinned version, driven by `ToolStatus.needsUpdate`.
136
137
 
138
+ ### 7.8 Default-engine bootstrap (fresh install)
139
+
140
+ Since no SDK ships in the package, a brand-new install has **zero** working
141
+ engines — a dead-end first run. `backend/engine/bootstrap-default-engine.ts`
142
+ closes that gap: `ensureDefaultEngineInstalled()` runs the `opencode` recipe in
143
+ the background (OpenCode is the one free, no-account engine) and no-ops the
144
+ moment **any** engine SDK is present, so it never fights a user who
145
+ deliberately removed it. Failures are non-fatal — everything stays installable
146
+ from Settings → Stack.
147
+
148
+ Two details that were bugs before they were rules:
149
+
150
+ - **Gate on the in-flight promise, not an "already started" latch.** A permanent
151
+ boolean would correctly de-dupe concurrent callers but then wrongly skip a
152
+ *legitimate* reinstall later in the same process. Holding the promise and
153
+ clearing it in `.finally()` de-dupes while it runs and lets the next caller
154
+ re-evaluate `isEngineSdkInstalled` once it settles.
155
+ - **It is not startup-only.** The call lives in
156
+ `backend/bootstrap.ts::bootstrapAfterDbInit()`, shared by `startServer()` and
157
+ the **Clear All Data** handler (`backend/ws/system/operations.ts`). Clear-data
158
+ wipes `~/.clopen` — including the stack dir — and re-runs only migrations +
159
+ seeders on the *same live process*, so anything established outside that
160
+ pipeline silently vanishes until the next restart. `bootstrapAfterDbInit()` is
161
+ where code-synced built-ins are re-established (today: internal MCP servers +
162
+ the default engine). **Add any future startup-synced built-in there**, not in
163
+ `startServer()` — but keep long-lived schedulers out of it, since they'd
164
+ double-run when invoked on the live process.
165
+
137
166
  ---
138
167
 
@@ -10,7 +10,7 @@ in `backend/ws/index.ts`. Four groups are relevant for engines:
10
10
  | `engine:claude-*` | `backend/ws/engine/claude/` | Status + Claude account CRUD |
11
11
  | `engine:opencode-*` | `backend/ws/engine/opencode/` | Status + provider/account CRUD + restart |
12
12
  | `engine:copilot-*` | `backend/ws/engine/copilot/` | Status + Copilot account CRUD |
13
- | `system-tools:*` | `backend/ws/system-tools/` | Detect/install binaries |
13
+ | `stack:*` | `backend/ws/stack/` | Detect/install binaries |
14
14
  | `models:list`, `chat:stream` | `backend/ws/settings/crud.ts`, `backend/ws/chat/stream.ts` | Model fetch + stream start |
15
15
 
16
16
  ### 4.1 Claude — `engine:claude-*`
@@ -130,21 +130,20 @@ because `CopilotClient` takes the PAT at construction time. Account
130
130
  add / remove / switch flips a `needsRestart` flag in the UI that surfaces
131
131
  a "Restart Server" button in both Settings → Engines and Chat Input.
132
132
 
133
- ### 4.4 Stack — `system-tools:*`
133
+ ### 4.4 Stack — `stack:*`
134
134
 
135
- Surfaced in Settings as the **Stack** panel; the WS route id stays
136
- `system-tools`. `backend/ws/system-tools/`:
135
+ Surfaced in Settings as the **Stack** panel. `backend/ws/stack/`:
137
136
 
138
137
  | Event | Purpose |
139
138
  |------------------------------------|---------------------------------------------|
140
- | `system-tools:status` | Detect a single tool: `{ status, recipe, activeSession }` |
141
- | `system-tools:status-all` | Hardcoded list `['git','claude','opencode','copilot','codex','qwen','pi','cline','cursor','chrome']` (host tools + on-demand engine SDKs) |
142
- | `system-tools:install-start` | Spawn the recipe via `install-runner` |
143
- | `system-tools:install-cancel` | |
144
- | `system-tools:install-session` | Snapshot session (for re-attach) |
145
- | `system-tools:install-started` (emit) | Session begun |
146
- | `system-tools:install-stream` (emit) | Per-line stdout/stderr |
147
- | `system-tools:install-finished` (emit) | exit code + final status |
139
+ | `stack:status` | Detect a single tool: `{ status, recipe, activeSession }` |
140
+ | `stack:status-all` | Hardcoded list `['git','claude','opencode','copilot','codex','qwen','pi','cline','cursor','chrome']` (host tools + on-demand engine SDKs) |
141
+ | `stack:install-start` | Spawn the recipe via `install-runner` |
142
+ | `stack:install-cancel` | |
143
+ | `stack:install-session` | Snapshot session (for re-attach) |
144
+ | `stack:install-started` (emit) | Session begun |
145
+ | `stack:install-stream` (emit) | Per-line stdout/stderr |
146
+ | `stack:install-finished` (emit) | exit code + final status |
148
147
 
149
148
  ### 4.5 `models:list` (in `backend/ws/settings/crud.ts`)
150
149
 
@@ -180,12 +179,23 @@ Each engine owns its model catalog in `backend/engine/adapters/<engine>/models.t
180
179
  | `copilot` | dynamic | `client.listModels()` via `fetchCopilotModels` |
181
180
  | `opencode` | dynamic | `client.config.providers()` via `fetchOpenCodeModels`|
182
181
  | `qwen` | dynamic | OpenAI-compatible `/models` via `fetchQwenModels` |
182
+ | `pi` | dynamic | pi-ai runtime catalog via `fetchPiModels` |
183
+ | `cline` | dynamic | `Llms.getModelsForProvider()` per stored account, via `fetchClineModels` |
184
+ | `cursor` | dynamic | `Cursor.models.list()` via `fetchCursorModels` (falls back to `CURSOR_FALLBACK_MODEL_IDS`) |
183
185
 
184
186
  Failure-mode contract (dynamic engines): return `EngineModel[]` and use
185
187
  `[]` as the failure sentinel — never `null` (see §2.6). The picker then
186
188
  renders an empty list rather than a stale cached catalog. `fetchOpenCodeModels`
187
189
  and `fetchQwenModels` already follow this; new dynamic fetchers must too.
188
190
 
191
+ `models.ts` is also where a model advertises its reasoning knob
192
+ (`capabilities.reasoningControl` — §2.4a). Dynamic catalogs derive the level
193
+ list from the SDK payload (Copilot's `supportedReasoningEfforts`, Pi's
194
+ `getSupportedThinkingLevels`, Cursor's model parameters); static catalogs
195
+ attach a shared constant. Because the registry is what `resolveGenerationTarget`
196
+ reads, `registerModels(...)` here is also what keeps one-shot
197
+ `generateStructured` calls from having to re-fetch a catalog.
198
+
189
199
  ### 4.6 Engine-specific config (presets — multi-provider / multi-region)
190
200
 
191
201
  Anything else an engine needs that the frontend has to render — provider
@@ -227,15 +237,44 @@ types flow through `$shared`.
227
237
  projectPath: string,
228
238
  prompt: UserMessage,
229
239
  engine: { type, provider, model: { id, name }, account: { id, name } },
230
- sender: { id, name }
240
+ sender: { id, name },
241
+ profileId?: number | null, // null = explicit none; absent = project default
242
+ reasoningEffort?: string | null // native level token; null/absent = engine default
231
243
  }
232
244
  ```
233
245
 
234
246
  The handler calls `streamManager.startStream(...)`, which then:
235
247
  1. Resolves `getProjectEngine(projectId, engine.type)`
236
- 2. Calls `engine.streamQuery({ projectPath, prompt, providerSlug, modelId, accountId, mcpContext, ... })`
237
- 3. Iterates over `EngineOutput` and emits each one to the chat session room
248
+ 2. Persists the per-session choices that outlive the turn — engine, model,
249
+ account, `profile_id`, `reasoning_effort` — onto the `chat_sessions` row
250
+ (`sessionQueries.updateReasoning`, migration `065`). `undefined` leaves the
251
+ stored value untouched; `null` clears it.
252
+ 3. Calls `engine.streamQuery({ projectPath, prompt, providerSlug, modelId, reasoningEffort, accountId, mcpContext, ... })`
253
+ 4. Iterates over `EngineOutput` and emits each one to the chat session room
238
254
  via `ws.emit.chatSession(...)`.
239
255
 
256
+ The turn's reasoning level is also stamped onto `MessageEngine.reasoningEffort`
257
+ by `enrichMessageEngine`, so it shows up in the Raw Message view. It is omitted
258
+ (not `null`) when the engine exposes no knob.
259
+
260
+ #### Collaborative per-session sync events
261
+
262
+ Choosing a model, account, profile, or reasoning level is a **run choice**, not
263
+ an admin mutation — so each one has a matching broadcast-and-persist event that
264
+ any session member may send. They are structurally identical; copy the nearest
265
+ one when adding a fifth.
266
+
267
+ | Event | Persists to |
268
+ |------------------------|------------------------------------|
269
+ | `chat:model-sync` | `chat_sessions` engine/model/account |
270
+ | `chat:profile-sync` | `chat_sessions.profile_id` |
271
+ | `chat:reasoning-sync` | `chat_sessions.reasoning_effort` |
272
+
273
+ Each handler calls `requireSessionAccess(conn, chatSessionId)`, writes through
274
+ `sessionQueries`, then re-emits to the room via `ws.emit.chatSession(...)`.
275
+ Every one of these must be declared in **both** the `.on(...)` block and the
276
+ `.emit(...)` schema block at the bottom of `backend/ws/chat/stream.ts` — an
277
+ event that is only `.on`'d is received but never broadcast.
278
+
240
279
  ---
241
280
 
@@ -118,7 +118,7 @@ function emitStream(session: Session, stream: 'stdout' | 'stderr', chunk: string
118
118
  session.pending[stream] = parts.pop() ?? '';
119
119
  for (const line of parts) {
120
120
  pushLine(session.buffer, line);
121
- ws.emit.user(session.startedBy, 'system-tools:install-stream', {
121
+ ws.emit.user(session.startedBy, 'stack:install-stream', {
122
122
  sessionId: session.id,
123
123
  tool: session.tool,
124
124
  type: stream,
@@ -132,7 +132,7 @@ function flushPending(session: Session): void {
132
132
  const remaining = session.pending[stream];
133
133
  if (remaining) {
134
134
  pushLine(session.buffer, remaining);
135
- ws.emit.user(session.startedBy, 'system-tools:install-stream', {
135
+ ws.emit.user(session.startedBy, 'stack:install-stream', {
136
136
  sessionId: session.id,
137
137
  tool: session.tool,
138
138
  type: stream,
@@ -191,7 +191,7 @@ function finalizeSession(session: Session, preferredStatus: SessionStatus, exitC
191
191
 
192
192
  debug.log('path', `[install:${session.id}] Finished status=${session.status} exit=${exitCode}`);
193
193
 
194
- ws.emit.user(session.startedBy, 'system-tools:install-finished', {
194
+ ws.emit.user(session.startedBy, 'stack:install-finished', {
195
195
  sessionId: session.id,
196
196
  tool: session.tool,
197
197
  status: session.status,
@@ -349,7 +349,7 @@ export async function startInstall(tool: ToolId, userId: string): Promise<Sessio
349
349
  emitStream(session, 'stdout', banner + '\n');
350
350
 
351
351
  // Broadcast the session-started event so clients that subscribe mid-run can attach.
352
- ws.emit.user(userId, 'system-tools:install-started', {
352
+ ws.emit.user(userId, 'stack:install-started', {
353
353
  sessionId: id,
354
354
  tool,
355
355
  displayCommand: recipe.displayCommand ?? '',
@@ -0,0 +1,87 @@
1
+ /**
2
+ * Generation target resolution.
3
+ *
4
+ * One-shot `generateStructured` callers (git commit/branch generator, artifact
5
+ * authoring) take engine + provider + model as three loose strings chosen
6
+ * client-side. Whenever those are persisted as separate fields they can drift:
7
+ * a UI that updates `engine`/`modelId` but forgets `provider` leaves a provider
8
+ * belonging to a completely different engine.
9
+ *
10
+ * That drift is invisible on engines that ignore `providerSlug` (Claude, Codex,
11
+ * Qwen, Copilot, Cursor — they key off `modelId` alone) and fatal on the ones
12
+ * that don't: OpenCode passes it as `model.providerID` (→ "OpenCode returned
13
+ * empty response"), Pi and Cline look their account up by provider (→ "no
14
+ * account for provider X").
15
+ *
16
+ * The engine's own catalog is the only source of truth for which provider and
17
+ * account a model belongs to, so resolve against it and treat the caller's
18
+ * `providerSlug` as a hint. Keeping this in one place means a new engine is
19
+ * covered without touching any call site.
20
+ */
21
+
22
+ import { getModelsByEngine, registerModels } from '$shared/constants/engines';
23
+ import { debug } from '$shared/utils/logger';
24
+ import type { EngineModel } from '$shared/types/unified';
25
+ import type { AIEngine } from './types';
26
+
27
+ /** Engine-verified coordinates for a one-shot generation call. */
28
+ export interface GenerationTarget {
29
+ providerSlug: string;
30
+ modelId: string;
31
+ /** Account owning the model; omitted for engines with a single implicit account. */
32
+ accountId?: number;
33
+ }
34
+
35
+ /**
36
+ * Resolve `providerSlug` (and the owning account) for `modelId` from the
37
+ * engine's catalog. `providerHint` is the caller-supplied slug — used only when
38
+ * the catalog can't answer.
39
+ *
40
+ * Throws when the model belongs to no provider this engine offers, which is a
41
+ * far more actionable error than the engine-specific failure it would become.
42
+ */
43
+ export async function resolveGenerationTarget(
44
+ engine: AIEngine,
45
+ modelId: string,
46
+ providerHint?: string
47
+ ): Promise<GenerationTarget> {
48
+ const engineType = engine.name;
49
+ const byId = (models: EngineModel[]) => models.find(m => m.engine.model.id === modelId);
50
+
51
+ // The registry is filled by `models:list`; only pay for a catalog fetch when
52
+ // this process hasn't seen the engine (or the model) yet.
53
+ let catalog = getModelsByEngine(engineType);
54
+ let match = byId(catalog);
55
+
56
+ if (!match) {
57
+ try {
58
+ catalog = await engine.getAvailableModels();
59
+ registerModels(engineType, catalog);
60
+ match = byId(catalog);
61
+ } catch (error) {
62
+ debug.warn('engine', `Catalog fetch failed for ${engineType}; using caller provider "${providerHint ?? ''}" for ${modelId}:`, error);
63
+ return { providerSlug: providerHint ?? '', modelId };
64
+ }
65
+ }
66
+
67
+ if (match) {
68
+ if (providerHint && providerHint !== match.engine.provider) {
69
+ debug.warn('engine', `Ignoring stale provider "${providerHint}" for ${engineType}/${modelId} — catalog says "${match.engine.provider}"`);
70
+ }
71
+ const accountId = match.engine.account.id;
72
+ return {
73
+ providerSlug: match.engine.provider,
74
+ modelId: match.engine.model.id,
75
+ ...(accountId ? { accountId } : {})
76
+ };
77
+ }
78
+
79
+ // Unknown model: only trust the hint if this engine actually serves that
80
+ // provider, otherwise it is drift and would fail deep inside the adapter.
81
+ if (providerHint && catalog.some(m => m.engine.provider === providerHint)) {
82
+ debug.warn('engine', `Model "${modelId}" missing from ${engineType} catalog; falling back to caller provider "${providerHint}"`);
83
+ return { providerSlug: providerHint, modelId };
84
+ }
85
+
86
+ throw new Error(`Model "${modelId}" is not available for engine "${engineType}". Pick it again in Settings → Models.`);
87
+ }
@@ -0,0 +1,64 @@
1
+ import { describe, expect, test } from 'bun:test';
2
+
3
+ import { extractJson } from './structured-helpers';
4
+
5
+ interface Draft {
6
+ name: string;
7
+ body?: string;
8
+ meta?: { a: { b: number } };
9
+ }
10
+
11
+ // Every case here is a real shape a prompt-engineered engine has produced —
12
+ // the parser is the last line of defence before a generation fails, so each
13
+ // tolerance it grants gets a regression test.
14
+ describe('extractJson', () => {
15
+ test('parses a clean object', () => {
16
+ const parsed = extractJson<Draft>('{"name": "X", "body": "b"}');
17
+ expect(parsed).toEqual({ name: 'X', body: 'b' });
18
+ });
19
+
20
+ test('ignores commentary appended after the object, braces and all', () => {
21
+ const response = `{"name": "90s Retro", "body": "# Retro"}
22
+
23
+ This skill applies { retro } styling. Let me know if you want changes!`;
24
+ expect(extractJson<Draft>(response).name).toBe('90s Retro');
25
+ });
26
+
27
+ test('ignores prose before the object', () => {
28
+ const parsed = extractJson<Draft>('Here is the JSON:\n{"name": "X"}\nDone.');
29
+ expect(parsed).toEqual({ name: 'X' });
30
+ });
31
+
32
+ test('unwraps a fenced block followed by commentary', () => {
33
+ const parsed = extractJson<Draft>('```json\n{"name": "X"}\n```\n\nHope that helps!');
34
+ expect(parsed).toEqual({ name: 'X' });
35
+ });
36
+
37
+ test('repairs raw newlines and tabs inside string values', () => {
38
+ const response = '{"name": "X", "body": "line1\nline2\n\tindented"}';
39
+ expect(extractJson<Draft>(response).body).toBe('line1\nline2\n\tindented');
40
+ });
41
+
42
+ test('keeps braces that live inside string values', () => {
43
+ const response = '{"name": "X", "body": "use ${var} and }{ weird"} trailing prose';
44
+ expect(extractJson<Draft>(response).body).toBe('use ${var} and }{ weird');
45
+ });
46
+
47
+ test('handles nested objects with trailing text', () => {
48
+ const parsed = extractJson<Draft>('{"name": "X", "meta": {"a": {"b": 1}}} and then some prose');
49
+ expect(parsed).toEqual({ name: 'X', meta: { a: { b: 1 } } });
50
+ });
51
+
52
+ test('throws on a truncated response rather than half-parsing it', () => {
53
+ expect(() => extractJson('{"name": "X", "body": "unterminated…')).toThrow(/did not contain valid JSON/);
54
+ });
55
+
56
+ test('throws on an empty response', () => {
57
+ expect(() => extractJson(' ')).toThrow(/Empty response/);
58
+ });
59
+
60
+ test('previews both ends of a long unparseable response', () => {
61
+ const response = `no json here ${'x'.repeat(600)} tail-marker`;
62
+ expect(() => extractJson(response)).toThrow(/tail-marker/);
63
+ });
64
+ });