@myrialabs/clopen 0.4.17 → 0.4.19

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 (91) hide show
  1. package/README.md +3 -3
  2. package/backend/auth/auth-service.ts +265 -13
  3. package/backend/auth/permissions.ts +3 -0
  4. package/backend/auth/rate-limiter.ts +1 -0
  5. package/backend/auth/session-cleanup.ts +5 -0
  6. package/backend/auth/tokens.ts +8 -1
  7. package/backend/chat/stream-manager.ts +8 -0
  8. package/backend/database/migrations/060_create_device_codes_table.ts +38 -0
  9. package/backend/database/migrations/061_add_session_device_metadata.ts +42 -0
  10. package/backend/database/migrations/062_add_session_source.ts +43 -0
  11. package/backend/database/migrations/063_add_invite_project_ids.ts +42 -0
  12. package/backend/database/migrations/064_create_messages_fts.ts +71 -0
  13. package/backend/database/migrations/index.ts +35 -0
  14. package/backend/database/queries/auth-queries.ts +100 -6
  15. package/backend/database/queries/message-queries.ts +44 -0
  16. package/backend/database/queries/session-queries.ts +117 -12
  17. package/backend/engine/README.md +21 -4
  18. package/backend/engine/adapters/claude/stream.ts +4 -2
  19. package/backend/engine/adapters/cline/agent-tool.ts +3 -2
  20. package/backend/engine/adapters/cline/ask-question-tool.ts +3 -2
  21. package/backend/engine/adapters/cline/credential.ts +2 -1
  22. package/backend/engine/adapters/cline/mcp-tools.ts +2 -1
  23. package/backend/engine/adapters/cline/models.ts +3 -1
  24. package/backend/engine/adapters/cline/presets.ts +5 -3
  25. package/backend/engine/adapters/cline/stream.ts +10 -7
  26. package/backend/engine/adapters/codex/stream.ts +3 -1
  27. package/backend/engine/adapters/copilot/stream.ts +8 -1
  28. package/backend/engine/adapters/cursor/environment.ts +4 -2
  29. package/backend/engine/adapters/cursor/models.ts +2 -1
  30. package/backend/engine/adapters/cursor/stream.ts +5 -3
  31. package/backend/engine/adapters/opencode/server.ts +2 -1
  32. package/backend/engine/adapters/pi/presets.ts +3 -1
  33. package/backend/engine/adapters/pi/session-fork.ts +3 -1
  34. package/backend/engine/adapters/pi/stream.ts +11 -8
  35. package/backend/engine/adapters/qwen/stream.ts +10 -8
  36. package/backend/engine/bootstrap-default-engine.ts +69 -0
  37. package/backend/engine/docs/adding-an-engine.md +29 -6
  38. package/backend/engine/docs/frontend-and-chat.md +21 -5
  39. package/backend/engine/docs/lessons-learned.md +41 -0
  40. package/backend/engine/docs/quick-reference.md +3 -2
  41. package/backend/engine/docs/system-tools.md +65 -9
  42. package/backend/engine/docs/websocket-routes.md +4 -3
  43. package/backend/engine/engine-setup.ts +72 -0
  44. package/backend/engine/install-recipes.ts +82 -77
  45. package/backend/engine/install-runner.ts +27 -2
  46. package/backend/engine/sdk-loader.ts +180 -0
  47. package/backend/engine/version-check.ts +6 -6
  48. package/backend/http/files-upload.test.ts +4 -1
  49. package/backend/index.ts +32 -2
  50. package/backend/mcp/README.md +26 -8
  51. package/backend/mcp/index.ts +2 -2
  52. package/backend/mcp/internal/config.ts +54 -63
  53. package/backend/mcp/internal/remote-server.test.ts +4 -1
  54. package/backend/mcp/internal/servers/helper.ts +4 -34
  55. package/backend/mcp/internal/servers/index.ts +4 -13
  56. package/backend/tunnel/public-origin.ts +118 -0
  57. package/backend/utils/ws.ts +126 -1
  58. package/backend/ws/auth/device.ts +239 -0
  59. package/backend/ws/auth/index.ts +8 -0
  60. package/backend/ws/auth/invites.ts +16 -6
  61. package/backend/ws/auth/login.test.ts +2 -2
  62. package/backend/ws/auth/login.ts +12 -6
  63. package/backend/ws/engine/claude/status.ts +4 -4
  64. package/backend/ws/engine/cline/accounts.ts +3 -2
  65. package/backend/ws/engine/cline/status.ts +4 -12
  66. package/backend/ws/engine/codex/status.ts +4 -12
  67. package/backend/ws/engine/copilot/status.ts +5 -12
  68. package/backend/ws/engine/cursor/accounts.ts +2 -1
  69. package/backend/ws/engine/cursor/status.ts +5 -12
  70. package/backend/ws/engine/opencode/status.ts +4 -4
  71. package/backend/ws/engine/pi/status.ts +4 -12
  72. package/backend/ws/engine/qwen/status.ts +5 -12
  73. package/backend/ws/sessions/crud.ts +29 -4
  74. package/backend/ws/settings/crud.ts +10 -1
  75. package/backend/ws/system/operations.ts +34 -18
  76. package/backend/ws/system-tools/install.ts +3 -0
  77. package/backend/ws/system-tools/status.ts +7 -2
  78. package/backend/ws/tunnel/index.ts +3 -1
  79. package/backend/ws/tunnel/share.ts +27 -0
  80. package/bin/clopen.ts +1 -1
  81. package/dist/assets/{index-kME3THy5.js → index-BqBxKeAv.js} +1 -1
  82. package/dist/assets/{index-Bu5loFQE.js → index-DdrcY5TE.js} +1 -1
  83. package/dist/assets/{main-HirJLquI.js → main-BBxAj17T.js} +337 -330
  84. package/dist/assets/main-Cry3pLcl.css +1 -0
  85. package/dist/index.html +2 -2
  86. package/package.json +15 -14
  87. package/shared/constants/engines.ts +39 -40
  88. package/shared/constants/tool-icons.ts +49 -0
  89. package/shared/types/stores/settings.ts +9 -0
  90. package/shared/utils/logger.ts +1 -0
  91. package/dist/assets/main-D7ATW8pp.css +0 -1
@@ -63,17 +63,22 @@ modelStore // models[], fetchModels(engine), refreshModels(engin
63
63
  // getByEngine(engine), getById(modelId)
64
64
  ```
65
65
 
66
- ### 5.2 Settings → System Tools
66
+ ### 5.2 Settings → Stack
67
+
68
+ The panel is displayed as **Stack** (its internal section id / WS route stays
69
+ `system-tools`).
67
70
 
68
71
  Files:
69
72
  - `frontend/components/settings/system-tools/SystemToolsSettings.svelte`
70
73
  - `frontend/components/settings/system-tools/ToolInstallCard.svelte`
71
74
 
72
- `SystemToolsSettings` renders one `ToolInstallCard` per tool (`git`,
73
- `claude`, `opencode`, `chrome`, `cloudflared`). `ToolInstallCard`:
75
+ `SystemToolsSettings` renders one `ToolInstallCard` per tool — host tools
76
+ (`git`, `chrome`, `cloudflared`) plus every engine SDK (`claude`, `opencode`,
77
+ `copilot`, `codex`, `qwen`, `pi`, `cline`, `cursor`). `ToolInstallCard`:
74
78
 
75
79
  1. Calls `system-tools:status` on mount.
76
- 2. Renders: status (installed/version/source), an "Install" button if
80
+ 2. Renders: status (installed/version/source; engines also carry
81
+ `requiredVersion` + `needsUpdate`), an "Install" button if
77
82
  `recipe.autoInstallable`, otherwise a "Manual install" dialog.
78
83
  3. While installing: `system-tools:install-start` → subscribe to
79
84
  `system-tools:install-stream` (per-line) → render in xterm + show
@@ -81,7 +86,15 @@ Files:
81
86
  4. The session survives navigation: if `activeSession` exists on refresh,
82
87
  re-attach to the same session id.
83
88
 
84
- To add a new tool (e.g. `goose`):
89
+ Engine cards differ from host-tool cards:
90
+ - The SDK installs on demand into `~/.clopen/stack/engines` (managed dir), not
91
+ the machine's PATH; there is no manual command to run.
92
+ - The **"Check for Updates"** button is hidden — engine versions are pinned in
93
+ `package.json` and move in lockstep with clopen, so there is no upstream to
94
+ check. When the installed version ≠ the pinned version, the card shows
95
+ **"Update required"** and an `Update → <version>` button instead.
96
+
97
+ To add a new **host** tool (e.g. `goose`):
85
98
  1. Add the literal to `ToolId` (`backend/engine/install-recipes.ts`).
86
99
  2. Add `resolveGooseRecipe()` + a case in `resolveRecipe()`.
87
100
  3. Add the literal to `TOOL_UNION` (`backend/ws/system-tools/status.ts`
@@ -91,6 +104,9 @@ To add a new tool (e.g. `goose`):
91
104
  5. (Optional) expose detection in the `engine:<name>-status` handler so
92
105
  Settings → Engines can show an "Installed" badge.
93
106
 
107
+ For a new **engine SDK**, you declare the pinned package instead of a resolver —
108
+ see [system-tools](./system-tools.md) §7.7.
109
+
94
110
  ---
95
111
 
96
112
  ## 6. Chat integration — model picker & stream
@@ -1065,3 +1065,44 @@ and socket errors to clear user messages in `error-handler.ts`.
1065
1065
  > `ContextIndicator.svelte` handles an unknown max context. When an engine's data
1066
1066
  > exposes a UI bug, fix it in the shared component, not the adapter.
1067
1067
 
1068
+ ---
1069
+
1070
+ ### 10.21 The SDK is not bundled — lazy-load it and never top-level-import it
1071
+
1072
+ Engine SDKs are **not** runtime dependencies. They live in `package.json`
1073
+ `devDependencies` (pinned exact — the single source of truth) and are installed
1074
+ **on demand** into the clopen-managed dir `~/.clopen/stack/engines`
1075
+ (`getStackEnginesDir()`), never the user's global bun store or their project.
1076
+ This is what fixed `bun add -g @myrialabs/clopen` aborting on Windows: bundling
1077
+ the SDKs dragged 200–300 MB of native CLI binaries into the global install, and
1078
+ one failed tarball extraction killed the whole thing.
1079
+
1080
+ Consequences for an adapter:
1081
+
1082
+ - **Reference SDK types only via `import type`.** A plain `import { Foo } from
1083
+ '<pkg>'` forces Bun to resolve the package at module-load time — which throws
1084
+ for every user who hasn't installed that engine yet, crashing the backend on
1085
+ boot. `import type` is erased at runtime, so it's safe. Resolve the real module
1086
+ at point of use with
1087
+ `loadEngineSdk<typeof import('<pkg>')>('newengine', '<pkg>')` from
1088
+ `backend/engine/sdk-loader.ts` (which does `Bun.resolveSync(pkg, stackDir)` +
1089
+ dynamic import, cached).
1090
+
1091
+ - **Loading is version-guarded.** `loadEngineSdk` refuses an SDK whose installed
1092
+ version ≠ the pinned version, throwing `EngineNotReadyError`
1093
+ (`reason: 'not-installed' | 'needs-update'`). The stream-manager surfaces that
1094
+ message in the chat error surface, telling the user to install/update the
1095
+ engine in Settings → Stack. Don't catch-and-swallow it — the readable message
1096
+ is the UX.
1097
+
1098
+ - **Detection reads the stack dir, not PATH.** `readEngineSdkVersion(pkg)` (used
1099
+ by both `getToolStatus` in the Stack panel and every engine picker
1100
+ `status.ts`) checks the SDK's version inside `~/.clopen/stack/engines` — there
1101
+ is no CLI-on-PATH probe for engines anymore. `ToolStatus` also carries
1102
+ `requiredVersion` + `needsUpdate` so the UI can show "Update required".
1103
+
1104
+ The same lazy-load applies to the one non-adapter consumer of the Claude SDK:
1105
+ `backend/mcp/index.ts::getEnabledMcpServers()` is `async` and lazy-loads
1106
+ `@anthropic-ai/claude-agent-sdk` only on the Claude path (see
1107
+ `backend/mcp/README.md`).
1108
+
@@ -33,12 +33,13 @@
33
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. |
34
34
  | Error normalisation | `claude/error-handler.ts`, `copilot/error-handler.ts`, `opencode/error-handler.ts`, `qwen/error-handler.ts`, `codex/error-handler.ts` |
35
35
  | DB provider/account access | `backend/database/queries/engine-queries.ts` |
36
- | Per-platform install recipe | `backend/engine/install-recipes.ts` |
36
+ | Host-tool + engine-SDK install recipes | `backend/engine/install-recipes.ts` |
37
+ | On-demand engine-SDK loader (managed dir) | `backend/engine/sdk-loader.ts` (`getStackEnginesDir`, `loadEngineSdk`) |
37
38
  | Streaming install logs | `backend/engine/install-runner.ts` |
38
39
  | Frontend account/provider stores | `frontend/stores/features/{claude-accounts,copilot-accounts,opencode-providers}.svelte.ts` |
39
40
  | Frontend chat-model state | `frontend/stores/ui/chat-model.svelte.ts` |
40
41
  | Settings UI (Engines) | `frontend/components/settings/engines/AIEnginesSettings.svelte` (shell + grid) + `engines/panels/*Panel.svelte` (one per engine) |
41
- | Settings UI (System Tools) | `frontend/components/settings/system-tools/{SystemToolsSettings,ToolInstallCard}.svelte` |
42
+ | Settings UI (Stack; id stays `system-tools`) | `frontend/components/settings/system-tools/{SystemToolsSettings,ToolInstallCard}.svelte` |
42
43
  | Chat picker (engine + model + account) | `frontend/components/chat/input/components/EngineModelPicker.svelte` |
43
44
  | Chat send → backend | `frontend/services/chat/chat.service.ts` (`ws.emit('chat:stream', …)`), `backend/ws/chat/stream.ts` |
44
45
  | Stream-manager (`EngineOutput` routing) | `backend/chat/stream-manager.ts` |
@@ -1,9 +1,24 @@
1
1
  [← Engine adapter guide](../README.md)
2
2
 
3
- ## 7. Registering a binary in System Tools (`install-recipes.ts`)
3
+ ## 7. Registering a tool in Stack (`install-recipes.ts`)
4
4
 
5
5
  `install-recipes.ts` is a **declarative** registry of install commands.
6
- `install-runner.ts` is what actually runs them.
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`).
9
+
10
+ Two kinds of `ToolId` live here:
11
+
12
+ - **Host tools** (`git`, `chrome`, `cloudflared`) — real binaries installed on
13
+ the machine's PATH via the platform's package manager. Detected by resolving
14
+ the binary + running `--version`.
15
+ - **Engine SDKs** (`claude`, `opencode`, `copilot`, `codex`, `qwen`, `pi`,
16
+ `cline`, `cursor`) — npm packages clopen installs **on demand** into the
17
+ managed stack dir `~/.clopen/stack/engines` (`getStackEnginesDir()`), NOT the
18
+ user's global bun store and NOT a global CLI on PATH. Their exact versions are
19
+ pinned in `package.json` (the single source of truth). `pi`, `cline`, and
20
+ `cursor` are now installable here too (they were previously read-only
21
+ InfoCards).
7
22
 
8
23
  ### 7.1 Anatomy of a `Recipe`
9
24
 
@@ -23,9 +38,11 @@ interface Recipe {
23
38
  }
24
39
  ```
25
40
 
26
- ### 7.2 Per-platform pattern
41
+ ### 7.2 Per-platform pattern (host tools)
27
42
 
28
- `resolveRecipe(tool)` switches to a per-tool resolver. Each resolver:
43
+ This applies to **host tools** only; engine SDKs use the single
44
+ `resolveEngineRecipe` path in §7.3. `resolveRecipe(tool)` switches to a per-tool
45
+ resolver. Each host-tool resolver:
29
46
  1. Builds `base: Recipe` with full `manualInstructions` (always provide a
30
47
  fallback for users on unsupported OSes).
31
48
  2. Checks platform (`process.platform`) and package manager:
@@ -41,14 +58,33 @@ interface Recipe {
41
58
  or leaves it `false` with `unavailableReason` so the UI renders manual
42
59
  instructions only.
43
60
 
44
- ### 7.3 Status detection
61
+ ### 7.3 Engine-SDK recipes
62
+
63
+ `resolveEngineRecipe(tool)` handles every engine `ToolId`. It maps the engine to
64
+ its pinned SDK package(s) (`ENGINE_PACKAGES`, versions read from `package.json`
65
+ via `getRequiredSdkVersion`) and installs them with `bun add <pkg>@<version>`
66
+ run with `recipe.cwd = getStackEnginesDir()`, so they land in
67
+ `~/.clopen/stack/engines` instead of the global store. Installing the SDK also
68
+ pulls whatever CLI binary it bundles; the drifting Copilot CLI is pinned exact
69
+ (`@github/copilot`). Because everything is fully clopen-managed, engine recipes
70
+ carry **no** `manualInstructions` — there is no command for the user to run by
71
+ hand. `install-runner.ts` bootstraps the stack dir + a minimal `package.json`
72
+ before the first `bun add`.
45
73
 
46
- `getToolStatus(tool)` returns `{ tool, installed, version, source }`:
74
+ ### 7.4 Status detection
75
+
76
+ `getToolStatus(tool)` returns `{ tool, installed, version, source }` (engines
77
+ additionally carry `requiredVersion` + `needsUpdate`):
47
78
  - `chrome` has a special path (puppeteer cache scan + system Chrome).
48
79
  - `cloudflared` at `~/.clopen/bin/cloudflared` is marked `source: 'clopen'`.
80
+ - **Engine SDKs** are detected by `readEngineSdkVersion(pkg)` — the SDK's
81
+ version inside the stack dir, NOT a CLI on PATH. `source` is the stack dir;
82
+ `needsUpdate` is true when the installed version ≠ the pinned
83
+ `requiredVersion`. The engine-picker `status.ts` handlers use the same
84
+ `readEngineSdkVersion` seam.
49
85
  - Otherwise `resolveBinaryWithRefresh(tool)` + `runVersion(resolved)`.
50
86
 
51
- ### 7.4 Runner
87
+ ### 7.5 Runner
52
88
 
53
89
  `install-runner.ts::startInstall(tool, userId)`:
54
90
  1. Verifies no other session is active for this tool
@@ -66,11 +102,11 @@ interface Recipe {
66
102
  Exit-code hints (`explainFailure(137|143, cancelled)`) explain SIGKILL OOM
67
103
  or SIGTERM with actual total/free memory readings.
68
104
 
69
- ### 7.5 Adding a new tool
105
+ ### 7.6 Adding a new host tool
70
106
 
71
107
  1. Add the literal to `ToolId` (`'goose'`).
72
108
  2. Write `resolveGooseRecipe(): Promise<Recipe>` following the
73
- `resolveOpenCodeRecipe` pattern.
109
+ `resolveGitRecipe` pattern.
74
110
  3. Add a case in `resolveRecipe(tool)`.
75
111
  4. Add the literal to `TOOL_UNION` (`status.ts`, `install.ts`).
76
112
  5. Add `<ToolInstallCard tool="goose" ... />` in
@@ -78,5 +114,25 @@ or SIGTERM with actual total/free memory readings.
78
114
  6. (Optional) detect in `engine:<engine>-status` so Settings → Engines
79
115
  knows the binary is installed.
80
116
 
117
+ ### 7.7 Adding a new engine SDK
118
+
119
+ Engine SDKs don't need a hand-written resolver. When you add an engine
120
+ (see [adding-an-engine](./adding-an-engine.md) Stage 7):
121
+
122
+ 1. Add the engine literal to `ToolId`.
123
+ 2. Add its pinned SDK package(s) to `ENGINE_PACKAGES` (first entry = the SDK
124
+ clopen imports and detects install-state from; extras pin a transitive CLI
125
+ the SDK would otherwise float). Add the same packages to `package.json`
126
+ `devDependencies` at an exact version — that is the single source of truth.
127
+ 3. `resolveEngineRecipe(tool)` handles the rest automatically (installs into the
128
+ stack dir at the pinned version).
129
+ 4. Add the literal to `TOOL_UNION` (`status.ts`, `install.ts`).
130
+ 5. Add `<ToolInstallCard tool="newengine" ... />` in `SystemToolsSettings.svelte`.
131
+
132
+ There is no "Check for Updates" for engines — their versions move in lockstep
133
+ with clopen releases, so `version-check.ts` has no update source for them. The
134
+ Stack card instead shows **Update required** whenever the installed version ≠
135
+ the pinned version, driven by `ToolStatus.needsUpdate`.
136
+
81
137
  ---
82
138
 
@@ -130,14 +130,15 @@ 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 System Tools — `system-tools:*`
133
+ ### 4.4 Stack — `system-tools:*`
134
134
 
135
- `backend/ws/system-tools/`:
135
+ Surfaced in Settings as the **Stack** panel; the WS route id stays
136
+ `system-tools`. `backend/ws/system-tools/`:
136
137
 
137
138
  | Event | Purpose |
138
139
  |------------------------------------|---------------------------------------------|
139
140
  | `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:status-all` | Hardcoded list `['git','claude','opencode','copilot','codex','qwen','pi','cline','cursor','chrome']` (host tools + on-demand engine SDKs) |
141
142
  | `system-tools:install-start` | Spawn the recipe via `install-runner` |
142
143
  | `system-tools:install-cancel` | |
143
144
  | `system-tools:install-session` | Snapshot session (for re-attach) |
@@ -0,0 +1,72 @@
1
+ /**
2
+ * Pre-stream engine readiness check.
3
+ *
4
+ * Before an engine streams, verify it is actually usable and, when it is not,
5
+ * return an actionable message that routes the user to the right place:
6
+ * - SDK missing or version-mismatched → Settings → Stack (install / update)
7
+ * - required account not set up → Settings → Engines (sign in)
8
+ *
9
+ * SDK readiness is checked first, so a not-installed engine is fixed before an
10
+ * account is asked for. The message text embeds the literal "Settings → Stack" /
11
+ * "Settings → Engines" phrases; the chat error renderer
12
+ * (`frontend/components/chat/formatters/ErrorMessage.svelte`) turns those into
13
+ * clickable buttons that open the matching settings section.
14
+ */
15
+
16
+ import type { EngineType } from '$shared/types/unified';
17
+ import { readEngineSdkVersion, getRequiredSdkVersion } from './sdk-loader';
18
+
19
+ /** Primary SDK package clopen imports for each engine. */
20
+ const ENGINE_SDK: Record<EngineType, string> = {
21
+ 'claude-code': '@anthropic-ai/claude-agent-sdk',
22
+ opencode: '@opencode-ai/sdk',
23
+ copilot: '@github/copilot-sdk',
24
+ codex: '@openai/codex-sdk',
25
+ qwen: '@qwen-code/sdk',
26
+ pi: '@earendil-works/pi-coding-agent',
27
+ cline: '@cline/sdk',
28
+ cursor: '@cursor/sdk',
29
+ };
30
+
31
+ /**
32
+ * Engines that require a signed-in account/credential before use. OpenCode
33
+ * ships built-in providers and works without one, so it is exempt.
34
+ */
35
+ const ENGINES_WITHOUT_ACCOUNT = new Set<EngineType>(['opencode']);
36
+
37
+ export interface EngineSetupIssue {
38
+ reason: 'not-installed' | 'needs-update' | 'needs-account';
39
+ message: string;
40
+ }
41
+
42
+ /**
43
+ * Returns null when the engine is ready to stream, or an actionable issue.
44
+ * @param accountId the resolved account id for this request (0 = none selected).
45
+ */
46
+ export function checkEngineSetup(engine: EngineType, accountId: number): EngineSetupIssue | null {
47
+ const sdkPkg = ENGINE_SDK[engine];
48
+ const installed = readEngineSdkVersion(sdkPkg);
49
+ const required = getRequiredSdkVersion(sdkPkg);
50
+
51
+ if (installed === null) {
52
+ return {
53
+ reason: 'not-installed',
54
+ message: `Engine "${engine}" is not installed. Open Settings → Stack to install it before using this engine.`
55
+ };
56
+ }
57
+ if (required !== null && installed !== required) {
58
+ return {
59
+ reason: 'needs-update',
60
+ message:
61
+ `Engine "${engine}" needs an update (installed ${installed}, required ${required}). ` +
62
+ `Open Settings → Stack to update it before using this engine.`
63
+ };
64
+ }
65
+ if (!ENGINES_WITHOUT_ACCOUNT.has(engine) && accountId === 0) {
66
+ return {
67
+ reason: 'needs-account',
68
+ message: `Engine "${engine}" has no account set up. Open Settings → Engines to sign in before using this engine.`
69
+ };
70
+ }
71
+ return null;
72
+ }
@@ -19,8 +19,9 @@ import { isElevated } from '$backend/utils/privilege';
19
19
  import { getClopenDir } from '$backend/utils/paths';
20
20
  import { resolveBinary, resolveBinaryWithRefresh } from '$backend/utils/cli';
21
21
  import { resolveStaticCurlAsset } from '$backend/utils/static-curl';
22
+ import { getStackEnginesDir, readEngineSdkVersion, getRequiredSdkVersion } from './sdk-loader';
22
23
 
23
- export type ToolId = 'git' | 'claude' | 'opencode' | 'copilot' | 'codex' | 'qwen' | 'chrome';
24
+ export type ToolId = 'git' | 'claude' | 'opencode' | 'copilot' | 'codex' | 'qwen' | 'pi' | 'cline' | 'cursor' | 'chrome';
24
25
 
25
26
  export interface ManualInstruction {
26
27
  label: string;
@@ -35,6 +36,8 @@ export interface Recipe {
35
36
  unavailableReason?: string;
36
37
  /** Spawn arg vector when autoInstallable. */
37
38
  command?: string[];
39
+ /** Working directory for the spawned install (e.g. the managed stack dir for engines). */
40
+ cwd?: string;
38
41
  /** Optional shell to wrap command (e.g. sh -c for pipe chains). */
39
42
  shell?: { program: string; args: string[] };
40
43
  /**
@@ -68,8 +71,48 @@ export interface ToolStatus {
68
71
  version: string | null;
69
72
  /** Where the binary was found (e.g. "/usr/bin/git", "system", "~/.clopen/bin"). */
70
73
  source: string | null;
74
+ /** Version clopen pins for this engine SDK (engines only); omitted for host tools. */
75
+ requiredVersion?: string | null;
76
+ /** True when the engine SDK is installed but at a different version than required. */
77
+ needsUpdate?: boolean;
71
78
  }
72
79
 
80
+ // ─────────────────────────────────────────────────────────────────────────────
81
+ // Engine SDK packages (SSOT: versions read from package.json)
82
+ // ─────────────────────────────────────────────────────────────────────────────
83
+
84
+ /**
85
+ * Engine → the npm package(s) clopen must install to run that engine on demand.
86
+ * The FIRST entry is the SDK clopen imports (used for install-state detection);
87
+ * any extras pin a transitive CLI the SDK would otherwise float (e.g. copilot).
88
+ * Versions are read from package.json (the single source of truth), so an
89
+ * on-demand install always matches the exact version clopen was tested against.
90
+ */
91
+ const ENGINE_PACKAGES: Partial<Record<ToolId, string[]>> = {
92
+ claude: ['@anthropic-ai/claude-agent-sdk'],
93
+ opencode: ['@opencode-ai/sdk'],
94
+ copilot: ['@github/copilot-sdk', '@github/copilot'],
95
+ codex: ['@openai/codex-sdk'],
96
+ qwen: ['@qwen-code/sdk'],
97
+ pi: ['@earendil-works/pi-coding-agent', '@earendil-works/pi-ai', '@earendil-works/pi-agent-core'],
98
+ cline: ['@cline/sdk', '@cline/agents'],
99
+ cursor: ['@cursor/sdk'],
100
+ };
101
+
102
+ function isEngineTool(tool: ToolId): boolean {
103
+ return tool in ENGINE_PACKAGES;
104
+ }
105
+
106
+ /** `bun add` arg vector for an engine: each package pinned to its package.json version. */
107
+ function engineInstallArgs(tool: ToolId): string[] {
108
+ const packages = ENGINE_PACKAGES[tool] ?? [];
109
+ return packages.map(name => {
110
+ const v = getRequiredSdkVersion(name);
111
+ return v ? `${name}@${v}` : name;
112
+ });
113
+ }
114
+
115
+
73
116
  // ─────────────────────────────────────────────────────────────────────────────
74
117
  // Package manager detection
75
118
  // ─────────────────────────────────────────────────────────────────────────────
@@ -204,6 +247,18 @@ export async function getToolStatus(tool: ToolId): Promise<ToolStatus> {
204
247
  return { tool, installed: true, version, source };
205
248
  }
206
249
 
250
+ if (isEngineTool(tool)) {
251
+ // Engines are detected by the presence of their SDK in the clopen-managed
252
+ // stack dir (installed on demand there), NOT by a CLI binary on PATH — the
253
+ // SDK is what the engine adapter actually needs.
254
+ const sdkPkg = ENGINE_PACKAGES[tool]![0];
255
+ const version = readEngineSdkVersion(sdkPkg);
256
+ const requiredVersion = getRequiredSdkVersion(sdkPkg);
257
+ if (!version) return { tool, installed: false, version: null, source: null, requiredVersion, needsUpdate: false };
258
+ const needsUpdate = requiredVersion !== null && version !== requiredVersion;
259
+ return { tool, installed: true, version, source: getStackEnginesDir(), requiredVersion, needsUpdate };
260
+ }
261
+
207
262
  const resolved = await resolveBinaryWithRefresh(tool);
208
263
  if (!resolved) return { tool, installed: false, version: null, source: null };
209
264
  const version = await runVersion(resolved);
@@ -342,80 +397,26 @@ function attachCurlRequirement(base: Recipe, toolLabel: string): boolean {
342
397
  return true;
343
398
  }
344
399
 
345
- async function resolveClaudeRecipe(): Promise<Recipe> {
346
- return {
347
- tool: 'claude',
348
- autoInstallable: true,
349
- missingPrereqs: [],
350
- manualInstructions: [{
351
- label: 'bun',
352
- command: 'bun add -g @anthropic-ai/claude-code',
353
- docs: 'https://code.claude.com/docs/en/setup'
354
- }],
355
- command: ['bun', 'add', '-g', '@anthropic-ai/claude-code'],
356
- displayCommand: 'bun add -g @anthropic-ai/claude-code'
357
- };
358
- }
359
-
360
- async function resolveOpenCodeRecipe(): Promise<Recipe> {
361
- const base: Recipe = {
362
- tool: 'opencode',
363
- autoInstallable: true,
364
- missingPrereqs: [],
365
- manualInstructions: [{
366
- label: 'bun',
367
- command: 'bun add -g opencode-ai',
368
- docs: 'https://opencode.ai/docs'
369
- }],
370
- command: ['bun', 'add', '-g', 'opencode-ai'],
371
- displayCommand: 'bun add -g opencode-ai'
372
- };
373
- return base;
374
- }
375
-
376
- async function resolveCopilotRecipe(): Promise<Recipe> {
377
- const base: Recipe = {
378
- tool: 'copilot',
379
- autoInstallable: true,
380
- missingPrereqs: [],
381
- manualInstructions: [{
382
- label: 'bun',
383
- command: 'bun add -g @github/copilot',
384
- docs: 'https://docs.github.com/en/copilot/how-tos/copilot-cli/set-up-copilot-cli/install-copilot-cli'
385
- }],
386
- command: ['bun', 'add', '-g', '@github/copilot'],
387
- displayCommand: 'bun add -g @github/copilot'
388
- };
389
- return base;
390
- }
391
-
392
- async function resolveQwenRecipe(): Promise<Recipe> {
393
- return {
394
- tool: 'qwen',
395
- autoInstallable: true,
396
- missingPrereqs: [],
397
- manualInstructions: [{
398
- label: 'bun',
399
- command: 'bun add -g @qwen-code/qwen-code',
400
- docs: 'https://qwen.ai/qwencode'
401
- }],
402
- command: ['bun', 'add', '-g', '@qwen-code/qwen-code'],
403
- displayCommand: 'bun add -g @qwen-code/qwen-code'
404
- };
405
- }
406
-
407
- async function resolveCodexRecipe(): Promise<Recipe> {
400
+ /**
401
+ * Engine install recipe — installs the exact engine SDK package(s) declared in
402
+ * package.json (the single source of truth) into the clopen-managed stack dir
403
+ * (`~/.clopen/stack/engines`), NOT the user's global bun store. Installing the
404
+ * SDK also pulls whatever CLI binary the SDK bundles. Versions are pinned,
405
+ * never floated to `latest`.
406
+ */
407
+ function resolveEngineRecipe(tool: ToolId): Recipe {
408
+ const args = engineInstallArgs(tool);
409
+ const displayCommand = `bun add ${args.join(' ')}`;
408
410
  return {
409
- tool: 'codex',
411
+ tool,
410
412
  autoInstallable: true,
411
413
  missingPrereqs: [],
412
- manualInstructions: [{
413
- label: 'bun',
414
- command: 'bun add -g @openai/codex',
415
- docs: 'https://developers.openai.com/codex/quickstart'
416
- }],
417
- command: ['bun', 'add', '-g', '@openai/codex'],
418
- displayCommand: 'bun add -g @openai/codex'
414
+ // Engine installs are fully clopen-managed (into ~/.clopen/stack/engines),
415
+ // so there is no separate manual command for the user to run.
416
+ manualInstructions: [],
417
+ command: ['bun', 'add', ...args],
418
+ cwd: getStackEnginesDir(),
419
+ displayCommand
419
420
  };
420
421
  }
421
422
 
@@ -579,11 +580,15 @@ function pickLinuxChromeStrategy(
579
580
  export async function resolveRecipe(tool: ToolId): Promise<Recipe> {
580
581
  switch (tool) {
581
582
  case 'git': return resolveGitRecipe();
582
- case 'claude': return resolveClaudeRecipe();
583
- case 'opencode': return resolveOpenCodeRecipe();
584
- case 'copilot': return resolveCopilotRecipe();
585
- case 'codex': return resolveCodexRecipe();
586
- case 'qwen': return resolveQwenRecipe();
587
583
  case 'chrome': return resolveChromeRecipe();
584
+ case 'claude':
585
+ case 'opencode':
586
+ case 'copilot':
587
+ case 'codex':
588
+ case 'qwen':
589
+ case 'pi':
590
+ case 'cline':
591
+ case 'cursor':
592
+ return resolveEngineRecipe(tool);
588
593
  }
589
594
  }
@@ -18,6 +18,8 @@
18
18
  */
19
19
 
20
20
  import { freemem, totalmem } from 'node:os';
21
+ import { existsSync, mkdirSync, writeFileSync } from 'node:fs';
22
+ import { join } from 'node:path';
21
23
  import { debug } from '$shared/utils/logger';
22
24
  import { ws } from '$backend/utils/ws';
23
25
  import { getCleanSpawnEnv } from '$backend/utils/env';
@@ -29,6 +31,24 @@ import { resolveRecipe } from './install-recipes';
29
31
  const RING_BUFFER_LINES = 10_000;
30
32
  const RETENTION_MS = 5 * 60 * 1000;
31
33
 
34
+ /**
35
+ * Ensure a recipe's working directory exists as a minimal bun project before
36
+ * `bun add` runs there. Engine recipes install into the clopen-managed stack
37
+ * dir (`~/.clopen/stack/engines`); a package.json must exist so `bun add`
38
+ * treats it as a project root instead of walking up to some parent.
39
+ */
40
+ function ensureRecipeCwd(recipe: Recipe): void {
41
+ if (!recipe.cwd) return;
42
+ mkdirSync(recipe.cwd, { recursive: true });
43
+ const pkgJsonPath = join(recipe.cwd, 'package.json');
44
+ if (!existsSync(pkgJsonPath)) {
45
+ writeFileSync(
46
+ pkgJsonPath,
47
+ JSON.stringify({ name: 'clopen-stack-engines', private: true, version: '0.0.0' }, null, 2) + '\n'
48
+ );
49
+ }
50
+ }
51
+
32
52
  export type SessionStatus = 'running' | 'success' | 'failed' | 'cancelled';
33
53
 
34
54
  interface RingBuffer {
@@ -257,14 +277,19 @@ async function runInstall(session: Session, env: Record<string, string>): Promis
257
277
  ? [recipe.shell.program, ...recipe.shell.args, ...recipe.command!]
258
278
  : recipe.command!;
259
279
 
260
- debug.log('path', `[install:${session.id}] Spawning: ${spawnArgs.join(' ')}`);
280
+ // Engine recipes install into a clopen-managed directory (recipe.cwd);
281
+ // make sure it exists as a minimal bun project before `bun add` runs.
282
+ ensureRecipeCwd(recipe);
283
+
284
+ debug.log('path', `[install:${session.id}] Spawning: ${spawnArgs.join(' ')}${recipe.cwd ? ` (cwd: ${recipe.cwd})` : ''}`);
261
285
 
262
286
  try {
263
287
  proc = Bun.spawn(spawnArgs, {
264
288
  stdout: 'pipe',
265
289
  stderr: 'pipe',
266
290
  stdin: 'ignore',
267
- env
291
+ env,
292
+ ...(recipe.cwd ? { cwd: recipe.cwd } : {})
268
293
  });
269
294
  } catch (err) {
270
295
  emitStream(session, 'stderr', `spawn failed: ${err instanceof Error ? err.message : String(err)}\n`);