@myrialabs/clopen 0.4.17 → 0.4.18

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 (89) 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/pi/presets.ts +3 -1
  32. package/backend/engine/adapters/pi/session-fork.ts +3 -1
  33. package/backend/engine/adapters/pi/stream.ts +11 -8
  34. package/backend/engine/bootstrap-default-engine.ts +69 -0
  35. package/backend/engine/docs/adding-an-engine.md +29 -6
  36. package/backend/engine/docs/frontend-and-chat.md +21 -5
  37. package/backend/engine/docs/lessons-learned.md +41 -0
  38. package/backend/engine/docs/quick-reference.md +3 -2
  39. package/backend/engine/docs/system-tools.md +65 -9
  40. package/backend/engine/docs/websocket-routes.md +4 -3
  41. package/backend/engine/engine-setup.ts +72 -0
  42. package/backend/engine/install-recipes.ts +82 -77
  43. package/backend/engine/install-runner.ts +27 -2
  44. package/backend/engine/sdk-loader.ts +180 -0
  45. package/backend/engine/version-check.ts +6 -6
  46. package/backend/http/files-upload.test.ts +4 -1
  47. package/backend/index.ts +32 -2
  48. package/backend/mcp/README.md +26 -8
  49. package/backend/mcp/index.ts +2 -2
  50. package/backend/mcp/internal/config.ts +54 -63
  51. package/backend/mcp/internal/remote-server.test.ts +4 -1
  52. package/backend/mcp/internal/servers/helper.ts +4 -34
  53. package/backend/mcp/internal/servers/index.ts +4 -13
  54. package/backend/tunnel/public-origin.ts +118 -0
  55. package/backend/utils/ws.ts +126 -1
  56. package/backend/ws/auth/device.ts +239 -0
  57. package/backend/ws/auth/index.ts +8 -0
  58. package/backend/ws/auth/invites.ts +16 -6
  59. package/backend/ws/auth/login.test.ts +2 -2
  60. package/backend/ws/auth/login.ts +12 -6
  61. package/backend/ws/engine/claude/status.ts +4 -4
  62. package/backend/ws/engine/cline/accounts.ts +3 -2
  63. package/backend/ws/engine/cline/status.ts +4 -12
  64. package/backend/ws/engine/codex/status.ts +4 -12
  65. package/backend/ws/engine/copilot/status.ts +5 -12
  66. package/backend/ws/engine/cursor/accounts.ts +2 -1
  67. package/backend/ws/engine/cursor/status.ts +5 -12
  68. package/backend/ws/engine/opencode/status.ts +4 -4
  69. package/backend/ws/engine/pi/status.ts +4 -12
  70. package/backend/ws/engine/qwen/status.ts +5 -12
  71. package/backend/ws/sessions/crud.ts +29 -4
  72. package/backend/ws/settings/crud.ts +10 -1
  73. package/backend/ws/system/operations.ts +34 -18
  74. package/backend/ws/system-tools/install.ts +3 -0
  75. package/backend/ws/system-tools/status.ts +7 -2
  76. package/backend/ws/tunnel/index.ts +3 -1
  77. package/backend/ws/tunnel/share.ts +27 -0
  78. package/bin/clopen.ts +1 -1
  79. package/dist/assets/{index-kME3THy5.js → index-Cz8HVhsm.js} +1 -1
  80. package/dist/assets/{index-Bu5loFQE.js → index-SI4Gcd0p.js} +1 -1
  81. package/dist/assets/main-Cry3pLcl.css +1 -0
  82. package/dist/assets/{main-HirJLquI.js → main-Dlba-fXF.js} +337 -330
  83. package/dist/index.html +2 -2
  84. package/package.json +15 -14
  85. package/shared/constants/engines.ts +39 -40
  86. package/shared/constants/tool-icons.ts +49 -0
  87. package/shared/types/stores/settings.ts +9 -0
  88. package/shared/utils/logger.ts +1 -0
  89. package/dist/assets/main-D7ATW8pp.css +0 -1
@@ -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`);
@@ -0,0 +1,180 @@
1
+ /**
2
+ * Engine SDK lazy loader
3
+ *
4
+ * Engine SDKs (Claude Agent SDK, Copilot SDK, Codex SDK, …) are NOT bundled
5
+ * into the clopen global install. They are installed on demand into a directory
6
+ * clopen manages — `~/.clopen/stack/engines` — which keeps them:
7
+ * - out of the user's global bun store (no PATH pollution, no version clashes),
8
+ * - out of the user's projects (never touches their package.json/node_modules),
9
+ * - isolated to clopen and surviving clopen reinstalls.
10
+ * This is the runtime half of the "Stack" concept (Settings → Stack).
11
+ *
12
+ * package.json (devDependencies) remains the single source of truth for the
13
+ * exact pinned version each engine installs; this module only resolves and
14
+ * loads whatever is present in the managed directory. When an SDK is not
15
+ * installed the import throws a typed `EngineSdkNotInstalledError` so a missing
16
+ * engine degrades to "not installed" in the UI instead of crashing the backend.
17
+ */
18
+
19
+ import { join } from 'node:path';
20
+ import { existsSync, readFileSync } from 'node:fs';
21
+ import { getClopenDir } from '$backend/utils/paths';
22
+ import { debug } from '$shared/utils/logger';
23
+
24
+ export type EngineSdkId =
25
+ | 'claude-code'
26
+ | 'copilot'
27
+ | 'codex'
28
+ | 'qwen'
29
+ | 'opencode'
30
+ | 'pi'
31
+ | 'cline'
32
+ | 'cursor';
33
+
34
+ /**
35
+ * Thrown when an engine's SDK package cannot be resolved at runtime — i.e. the
36
+ * engine has not been installed on demand yet. Carries the engine id and the
37
+ * npm package name so callers can render an actionable "install this engine"
38
+ * message rather than surfacing a raw module-resolution error.
39
+ */
40
+ export type EngineSetupReason = 'not-installed' | 'needs-update';
41
+
42
+ /**
43
+ * Thrown when an engine cannot be used because its SDK is not ready in the
44
+ * managed stack dir: either not installed, or installed at a version other than
45
+ * the one clopen pins (a mandatory update). Carries enough for the UI to render
46
+ * an actionable prompt; the message is also human-readable for the chat error
47
+ * surface. `reason` drives the wording and the target action.
48
+ */
49
+ export class EngineNotReadyError extends Error {
50
+ readonly engine: EngineSdkId;
51
+ readonly packageName: string;
52
+ readonly reason: EngineSetupReason;
53
+ readonly installedVersion: string | null;
54
+ readonly requiredVersion: string | null;
55
+
56
+ constructor(
57
+ engine: EngineSdkId,
58
+ packageName: string,
59
+ reason: EngineSetupReason,
60
+ installedVersion: string | null,
61
+ requiredVersion: string | null,
62
+ cause?: unknown
63
+ ) {
64
+ const detail = reason === 'needs-update'
65
+ ? `needs an update (installed ${installedVersion ?? 'unknown'}, ` +
66
+ `required ${requiredVersion ?? 'unknown'}). Open Settings → Stack to ` +
67
+ `update it before using this engine.`
68
+ : `is not installed. Open Settings → Stack to install it.`;
69
+ super(`Engine "${engine}" ${detail}`);
70
+ this.name = 'EngineNotReadyError';
71
+ this.engine = engine;
72
+ this.packageName = packageName;
73
+ this.reason = reason;
74
+ this.installedVersion = installedVersion;
75
+ this.requiredVersion = requiredVersion;
76
+ if (cause !== undefined) (this as { cause?: unknown }).cause = cause;
77
+ }
78
+ }
79
+
80
+ /**
81
+ * The clopen-managed directory that on-demand engine SDKs are installed into.
82
+ * It is a self-contained bun project (`node_modules` + a minimal package.json),
83
+ * so a globally-installed clopen never has to touch the user's global store.
84
+ */
85
+ export function getStackEnginesDir(): string {
86
+ return join(getClopenDir(), 'stack', 'engines');
87
+ }
88
+
89
+ /** Absolute path of an installed engine package inside the managed dir. */
90
+ function stackPackageDir(packageName: string): string {
91
+ return join(getStackEnginesDir(), 'node_modules', packageName);
92
+ }
93
+
94
+ /**
95
+ * Exact versions clopen pins for its dependencies (read from package.json —
96
+ * the single source of truth). An engine SDK installed in the stack dir must
97
+ * match its pinned version, or it is considered out of date and must be updated.
98
+ */
99
+ let cachedRequiredVersions: Record<string, string> | null = null;
100
+ function requiredVersions(): Record<string, string> {
101
+ if (cachedRequiredVersions) return cachedRequiredVersions;
102
+ try {
103
+ const pkgPath = join(import.meta.dir, '..', '..', 'package.json');
104
+ const pkg = JSON.parse(readFileSync(pkgPath, 'utf8')) as {
105
+ dependencies?: Record<string, string>;
106
+ devDependencies?: Record<string, string>;
107
+ };
108
+ cachedRequiredVersions = { ...(pkg.dependencies ?? {}), ...(pkg.devDependencies ?? {}) };
109
+ } catch {
110
+ cachedRequiredVersions = {};
111
+ }
112
+ return cachedRequiredVersions;
113
+ }
114
+
115
+ /** The exact version clopen pins for an SDK package (from package.json), or null. */
116
+ export function getRequiredSdkVersion(packageName: string): string | null {
117
+ return requiredVersions()[packageName] ?? null;
118
+ }
119
+
120
+ /** Resolved-module cache so repeat loads of the same SDK are cheap. */
121
+ const moduleCache = new Map<string, unknown>();
122
+
123
+ /**
124
+ * Dynamically import an engine SDK from the managed stack directory, caching the
125
+ * module. Throws `EngineSdkNotInstalledError` when the package is not installed.
126
+ *
127
+ * Type the result via the `T` parameter using `typeof import('<pkg>')`, e.g.:
128
+ * const { CopilotClient } = await loadEngineSdk<typeof import('@github/copilot-sdk')>(
129
+ * 'copilot', '@github/copilot-sdk'
130
+ * );
131
+ * Keep all compile-time type references on `import type` so they are erased at
132
+ * runtime and never force resolution of an absent package.
133
+ */
134
+ export async function loadEngineSdk<T>(engine: EngineSdkId, packageName: string): Promise<T> {
135
+ const cached = moduleCache.get(packageName);
136
+ if (cached !== undefined) return cached as T;
137
+
138
+ // Guard readiness before loading: not installed, or installed at a version
139
+ // other than the one clopen pins (a mandatory update).
140
+ const installed = readEngineSdkVersion(packageName);
141
+ const required = getRequiredSdkVersion(packageName);
142
+ if (installed === null) {
143
+ throw new EngineNotReadyError(engine, packageName, 'not-installed', null, required);
144
+ }
145
+ if (required !== null && installed !== required) {
146
+ throw new EngineNotReadyError(engine, packageName, 'needs-update', installed, required);
147
+ }
148
+
149
+ try {
150
+ // Resolve the package's entry point (respecting its `exports`/`main`) from
151
+ // the managed dir, then import by absolute path.
152
+ const entry = Bun.resolveSync(packageName, getStackEnginesDir());
153
+ const mod = (await import(entry)) as T;
154
+ moduleCache.set(packageName, mod);
155
+ return mod;
156
+ } catch (error) {
157
+ debug.warn('engine', `Engine SDK "${packageName}" (${engine}) failed to load`, error);
158
+ throw new EngineNotReadyError(engine, packageName, 'not-installed', installed, required, error);
159
+ }
160
+ }
161
+
162
+ /**
163
+ * Installed version of an engine SDK in the managed stack dir, or null when not
164
+ * installed. Reads package.json directly (bypassing any `exports` map that would
165
+ * hide `./package.json`), so detection is robust across packages.
166
+ */
167
+ export function readEngineSdkVersion(packageName: string): string | null {
168
+ try {
169
+ const pkgJsonPath = join(stackPackageDir(packageName), 'package.json');
170
+ const json = JSON.parse(readFileSync(pkgJsonPath, 'utf8')) as { version?: string };
171
+ return json.version ?? null;
172
+ } catch {
173
+ return null;
174
+ }
175
+ }
176
+
177
+ /** Whether an engine's SDK package is installed in the managed stack dir. */
178
+ export function isEngineSdkInstalled(packageName: string): boolean {
179
+ return existsSync(join(stackPackageDir(packageName), 'package.json'));
180
+ }