@myrialabs/clopen 0.4.30 → 0.4.31

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.
@@ -815,7 +815,7 @@ class StreamManager extends EventEmitter {
815
815
  // exact fix (Stack to install/update, Engines to sign in). Thrown here
816
816
  // so the processStream catch surfaces it as a chat error, which the
817
817
  // ErrorMessage renderer turns into a one-click action.
818
- const setupIssue = checkEngineSetup(requestEngine.type, requestEngine.account.id);
818
+ const setupIssue = await checkEngineSetup(requestEngine.type, requestEngine.account.id);
819
819
  if (setupIssue) throw new Error(setupIssue.message);
820
820
 
821
821
  // Stream EngineOutput events through the engine adapter
@@ -26,7 +26,7 @@ import type { AIEngine, EngineQueryOptions, StructuredGenerationOptions } from '
26
26
  import { extractJson } from '../../structured-helpers';
27
27
  import { engineQueries } from '$backend/database/queries/engine-queries';
28
28
  import { resolveOsPath } from '$backend/utils/paths';
29
- import { resolveBinary } from '$backend/utils/cli';
29
+ import { resolveEngineCli } from '$backend/engine/engine-cli';
30
30
  import { getCleanSpawnEnv } from '$backend/utils/index.js';
31
31
  import { getCodexMcpConfig } from '../../../mcp';
32
32
  import { artifactFilter } from '$backend/profiles';
@@ -104,7 +104,10 @@ export class CodexEngine implements AIEngine {
104
104
  // option is passed directly; no filesystem mutation.
105
105
  applyAccountAuth(account);
106
106
 
107
- const codexBinary = resolveBinary('codex');
107
+ // Prefer the binary clopen manages (vendored in the SDK's platform package
108
+ // inside the stack dir) over an older copy on the user's PATH — the SDK
109
+ // would otherwise be pinned while the process it spawns drifts.
110
+ const codexCli = await resolveEngineCli('codex');
108
111
  const mcpConfig = getCodexMcpConfig(mcpProfileFilter);
109
112
 
110
113
  // Codex SDK takes config at construction. We pass `show_raw_agent_reasoning`
@@ -123,7 +126,7 @@ export class CodexEngine implements AIEngine {
123
126
  const { Codex } = await loadEngineSdk<typeof import('@openai/codex-sdk')>('codex', '@openai/codex-sdk');
124
127
  this.codex = new Codex({
125
128
  apiKey: credential.kind === 'api_key' ? credential.apiKey : undefined,
126
- ...(codexBinary ? { codexPathOverride: codexBinary } : {}),
129
+ ...(codexCli ? { codexPathOverride: codexCli.path } : {}),
127
130
  env: { ...getCleanSpawnEnv(), CODEX_HOME: getCodexHomeDir() },
128
131
  config: {
129
132
  show_raw_agent_reasoning: true,
@@ -28,7 +28,7 @@ import { getOpenCodeMcpConfig } from '../../../mcp';
28
28
  import { engineQueries, settingsQueries } from '../../../database/queries';
29
29
  import { generateOpenCodeProviderConfig, parseCredentialMap } from './config';
30
30
  import type { OpenCodeInlineAgent } from '$backend/subagents';
31
- import { resolveBinaryWithRefresh } from '$backend/utils/cli';
31
+ import { resolveEngineCli } from '$backend/engine/engine-cli';
32
32
  import { loadEngineSdk } from '$backend/engine/sdk-loader';
33
33
  import { getEngineUserConfigDir } from '$backend/utils/paths';
34
34
  import { debug } from '$shared/utils/logger';
@@ -164,9 +164,18 @@ async function spawnServer(key: string, spec: ServerConfigSpec): Promise<ServerI
164
164
  ? configDir
165
165
  : join(configDir, 'pool', Buffer.from(key).toString('base64url'));
166
166
 
167
- const command = await resolveBinaryWithRefresh('opencode');
168
- if (!command) throw new Error('opencode binary not found on PATH');
169
- const args = [command, 'serve', `--hostname=${OPENCODE_HOST}`, '--port=0'];
167
+ // The CLI lives in clopen's managed stack dir (or, failing that, on the
168
+ // user's PATH); `resolveEngineCli` is the same lookup Settings → Stack
169
+ // reports, so an engine shown as installed is always one we can spawn.
170
+ // The literal "Settings → Stack" routes the chat/model-picker error to the
171
+ // one place that fixes it.
172
+ const cli = await resolveEngineCli('opencode');
173
+ if (!cli) {
174
+ throw new Error(
175
+ 'Open Code is missing its CLI. Open Settings → Stack to install it before using this engine.'
176
+ );
177
+ }
178
+ const args = [cli.path, 'serve', `--hostname=${OPENCODE_HOST}`, '--port=0'];
170
179
 
171
180
  // MCP: only inject remote servers whose endpoint is reachable — an unreachable
172
181
  // remote can stall startup. stdio/local servers (no `url`) always survive.
@@ -1,20 +1,36 @@
1
1
  /**
2
- * Fresh-install default engine bootstrap.
2
+ * Fresh-install default engine bootstrap & repair.
3
3
  *
4
- * On a machine where NO engine SDK is installed yet, auto-install OpenCode —
5
- * the one free, no-account engine — into the managed stack dir so first-time
6
- * users have a working default without any manual setup (wizard or otherwise).
7
- * Runs in the background at startup; failures are non-fatal (engines remain
8
- * installable from Settings → Stack). Skipped as soon as ANY engine is present,
9
- * so it never fights a user who intentionally removed OpenCode.
4
+ * Two jobs, both aimed at a user who should never have to know any of this
5
+ * exists:
6
+ *
7
+ * 1. Bootstrap — on a machine where NO engine SDK is installed yet,
8
+ * auto-install OpenCode (the one free, no-account engine) into the managed
9
+ * stack dir so first-time users have a working default without any manual
10
+ * setup. Skipped as soon as ANY engine is present, so it never fights a
11
+ * user who intentionally removed OpenCode.
12
+ *
13
+ * 2. Repair — OpenCode needs an external CLI binary on top of its SDK
14
+ * (see engine-cli.ts). Earlier builds installed only the SDK, so machines
15
+ * bootstrapped by them carry a half-installed engine: Settings → Stack
16
+ * reported it as ready while the adapter could not spawn it at all. Those
17
+ * installs are clopen's own doing, so clopen finishes them rather than
18
+ * asking the user to. The repair is deliberately narrow — the SDK must
19
+ * already be there and only its CLI missing — so it never pulls in an
20
+ * engine nobody asked for.
21
+ *
22
+ * Both run in the background at startup through the normal install runner, so
23
+ * the work shows up as a live session in Settings → Stack instead of a silent
24
+ * download; failures are non-fatal (engines stay installable by hand).
10
25
  */
11
26
 
12
- import { existsSync, mkdirSync, writeFileSync } from 'node:fs';
13
- import { join } from 'node:path';
14
27
  import { debug } from '$shared/utils/logger';
15
- import { getCleanSpawnEnv } from '$backend/utils/env';
16
28
  import { isEngineSdkInstalled } from './sdk-loader';
17
- import { resolveRecipe } from './install-recipes';
29
+ import { ENGINE_PACKAGES } from './install-recipes';
30
+ import { getRequiredEngineCliSpec, resolveEngineCli } from './engine-cli';
31
+ import { awaitInstall, InstallAlreadyRunningError, startInstall, SYSTEM_INSTALL_USER } from './install-runner';
32
+
33
+ const DEFAULT_ENGINE = 'opencode' as const;
18
34
 
19
35
  const ENGINE_SDK_PACKAGES = [
20
36
  '@anthropic-ai/claude-agent-sdk',
@@ -37,9 +53,10 @@ const ENGINE_SDK_PACKAGES = [
37
53
  let inFlight: Promise<void> | null = null;
38
54
 
39
55
  /**
40
- * Install OpenCode on a fresh machine (no engine SDK present). Idempotent and
41
- * safe to call at every startup and after a data wipe; it no-ops once any engine
42
- * exists, and de-dupes concurrent calls via the in-flight promise.
56
+ * Install the default engine on a fresh machine, or finish a half-installed one.
57
+ * Idempotent and safe to call at every startup and after a data wipe; it no-ops
58
+ * once the default engine is fully usable, and de-dupes concurrent calls via the
59
+ * in-flight promise.
43
60
  */
44
61
  export function ensureDefaultEngineInstalled(): Promise<void> {
45
62
  if (inFlight) return inFlight;
@@ -49,34 +66,46 @@ export function ensureDefaultEngineInstalled(): Promise<void> {
49
66
  return inFlight;
50
67
  }
51
68
 
52
- async function runDefaultEngineInstall(): Promise<void> {
53
- if (ENGINE_SDK_PACKAGES.some(isEngineSdkInstalled)) return;
69
+ /**
70
+ * Why the default engine needs installing, or null when nothing is to be done.
71
+ * "repair" covers the SDK-without-CLI state older builds left behind.
72
+ */
73
+ async function pendingInstallReason(): Promise<'bootstrap' | 'repair' | null> {
74
+ if (!ENGINE_SDK_PACKAGES.some(isEngineSdkInstalled)) return 'bootstrap';
54
75
 
55
- const recipe = await resolveRecipe('opencode');
56
- if (!recipe.command || !recipe.cwd) return;
76
+ // Some engine is installed, so the fresh-machine bootstrap is done. The
77
+ // default engine may still be half-installed, though — and only its own SDK
78
+ // tells us whether clopen ever installed it in the first place.
79
+ const sdkPkg = ENGINE_PACKAGES[DEFAULT_ENGINE]?.[0];
80
+ if (!sdkPkg || !isEngineSdkInstalled(sdkPkg)) return null;
81
+ if (!getRequiredEngineCliSpec(DEFAULT_ENGINE)) return null;
57
82
 
58
- // Ensure the managed dir is a minimal bun project before `bun add` runs.
59
- mkdirSync(recipe.cwd, { recursive: true });
60
- const pkgJsonPath = join(recipe.cwd, 'package.json');
61
- if (!existsSync(pkgJsonPath)) {
62
- writeFileSync(
63
- pkgJsonPath,
64
- JSON.stringify({ name: 'clopen-stack-engines', private: true, version: '0.0.0' }, null, 2) + '\n'
65
- );
66
- }
83
+ return (await resolveEngineCli(DEFAULT_ENGINE)) ? null : 'repair';
84
+ }
85
+
86
+ async function runDefaultEngineInstall(): Promise<void> {
87
+ const reason = await pendingInstallReason();
88
+ if (!reason) return;
89
+
90
+ debug.log(
91
+ 'engine',
92
+ reason === 'bootstrap'
93
+ ? `No engine installed — auto-installing the default engine (${DEFAULT_ENGINE})`
94
+ : `Default engine (${DEFAULT_ENGINE}) is missing its CLI — repairing the install`
95
+ );
67
96
 
68
- debug.log('engine', `Auto-installing default engine (OpenCode): ${recipe.displayCommand}`);
69
97
  try {
70
- const proc = Bun.spawn(recipe.command, {
71
- cwd: recipe.cwd,
72
- env: getCleanSpawnEnv(),
73
- stdout: 'ignore',
74
- stderr: 'ignore',
75
- stdin: 'ignore',
76
- });
77
- const code = await proc.exited;
78
- debug.log('engine', `Default engine (OpenCode) auto-install exited with code ${code}`);
98
+ const session = await startInstall(DEFAULT_ENGINE, SYSTEM_INSTALL_USER);
99
+ // Callers chain work that needs a usable engine (memory picks its
100
+ // extraction model from the engine's catalog), so wait for the run to
101
+ // settle rather than returning as soon as it is spawned.
102
+ await awaitInstall(session.id);
103
+ debug.log('engine', `Default engine ${reason} finished with status "${session.status}"`);
79
104
  } catch (error) {
80
- debug.warn('engine', 'Default engine auto-install failed (non-fatal)', error);
105
+ if (error instanceof InstallAlreadyRunningError) {
106
+ debug.log('engine', `Default engine ${reason} skipped — an install is already running`);
107
+ return;
108
+ }
109
+ debug.warn('engine', `Default engine ${reason} failed (non-fatal)`, error);
81
110
  }
82
111
  }
@@ -0,0 +1,313 @@
1
+ /**
2
+ * Engine CLI binaries
3
+ *
4
+ * Several engines are not pure SDKs: behind the npm package sits a real
5
+ * executable that clopen (or the SDK itself) has to spawn. Those binaries live
6
+ * inside the managed stack dir — never on PATH — which is where clopen kept
7
+ * getting this wrong. Code that needed one reached for `Bun.which`, found
8
+ * nothing on a machine without a global install, and reported an engine as
9
+ * missing that Settings → Stack had just installed:
10
+ *
11
+ * - Open Code: `@opencode-ai/sdk` is an HTTP client with no binary at all, so
12
+ * the adapter could not spawn `opencode serve` and NO model could be picked.
13
+ * Its CLI ships as a separate package, installed alongside the SDK.
14
+ * - Codex and Claude Code: their SDKs bundle a CLI as an optional platform
15
+ * dependency and locate it themselves, so streaming works — but clopen's own
16
+ * sign-in flows (`codex login`, `claude setup-token`) and the Codex engine
17
+ * status card looked on PATH and declared the CLI missing.
18
+ *
19
+ * This module is the single source of truth for that second artifact: which
20
+ * package carries the binary, where it lands, and which version it must match.
21
+ * Status, the readiness gate, the adapters and the sign-in flows all resolve
22
+ * through `resolveEngineCli`, so what clopen reports is what clopen can run.
23
+ *
24
+ * Resolution order (first candidate that actually runs wins):
25
+ * 1. the binary inside the managed stack dir — version-matched to the pinned
26
+ * SDK, so it is preferred over anything else,
27
+ * 2. the platform package one level down — the same binary, reached when a
28
+ * postinstall was blocked and the package's own `bin/` holds a stub,
29
+ * 3. whatever is on PATH — a CLI the user installed themselves.
30
+ *
31
+ * Every candidate is verified by running `--version` before it is handed out:
32
+ * a postinstall stub exits 1, and a plain x64 build on a pre-AVX2 CPU dies on
33
+ * startup. Both must fall through rather than reach a spawn site.
34
+ */
35
+
36
+ import { existsSync } from 'node:fs';
37
+ import { join } from 'node:path';
38
+ import { debug } from '$shared/utils/logger';
39
+ import { resolveBinaryWithRefresh } from '$backend/utils/cli';
40
+ import { getStackEnginesDir, getRequiredSdkVersion } from './sdk-loader';
41
+ import type { ToolId } from './install-recipes';
42
+
43
+ /** How long a candidate gets to answer `--version` before it is discarded. */
44
+ const PROBE_TIMEOUT_MS = 15_000;
45
+
46
+ export interface EngineCliSpec {
47
+ /** Binary name as it appears on PATH. */
48
+ binaryName: string;
49
+ /**
50
+ * Package whose pinned version governs this CLI's version. For a bundled CLI
51
+ * that is the SDK itself; for Open Code it is the SDK the separate CLI
52
+ * package is released in lockstep with.
53
+ */
54
+ versionSource: string;
55
+ /**
56
+ * Extra package `bun add` must install for this CLI, when the SDK does not
57
+ * bring the binary itself. Omitted for CLIs bundled as a platform optional
58
+ * dependency of the SDK — those arrive with the engine install already.
59
+ */
60
+ installPackage?: string;
61
+ /**
62
+ * True when the engine cannot run at all without this binary. Such an engine
63
+ * counts as installed only once the CLI resolves. A bundled CLI is false:
64
+ * the SDK locates it internally through its own module graph, so a failure
65
+ * to find it here only affects clopen's own spawn sites.
66
+ */
67
+ required: boolean;
68
+ /** Candidate paths inside the stack dir's node_modules, best first. */
69
+ candidates: (modulesDir: string) => string[];
70
+ }
71
+
72
+ const isWindows = process.platform === 'win32';
73
+
74
+ /** `<name>` on posix, `<name>.exe` on Windows. */
75
+ function exe(name: string): string {
76
+ return isWindows ? `${name}.exe` : name;
77
+ }
78
+
79
+ // ─── Open Code ───────────────────────────────────────────────────────────────
80
+
81
+ const OPENCODE_PLATFORMS: Record<string, string> = {
82
+ darwin: 'darwin',
83
+ linux: 'linux',
84
+ win32: 'windows'
85
+ };
86
+
87
+ /**
88
+ * Open Code's platform packages, in the order its own postinstall would pick
89
+ * them. bun installs the plain build matching our `os`/`cpu`/`libc`, so that is
90
+ * normally the only one present; the `-baseline` (no AVX2) and `-musl` variants
91
+ * are listed because the postinstall pulls them in on hosts where the plain
92
+ * build cannot run, and we must find them there too.
93
+ */
94
+ function opencodePlatformPackages(): string[] {
95
+ const platform = OPENCODE_PLATFORMS[process.platform] ?? process.platform;
96
+ const arch = process.arch;
97
+ const base = `opencode-${platform}-${arch}`;
98
+
99
+ if (platform === 'linux') {
100
+ return arch === 'x64'
101
+ ? [base, `${base}-baseline`, `${base}-musl`, `${base}-baseline-musl`]
102
+ : [base, `${base}-musl`];
103
+ }
104
+ return arch === 'x64' ? [base, `${base}-baseline`] : [base];
105
+ }
106
+
107
+ // ─── Codex ───────────────────────────────────────────────────────────────────
108
+
109
+ /** Rust target triples Codex vendors its binary under, keyed by platform-arch. */
110
+ const CODEX_TARGET_TRIPLES: Record<string, string> = {
111
+ 'linux-x64': 'x86_64-unknown-linux-musl',
112
+ 'linux-arm64': 'aarch64-unknown-linux-musl',
113
+ 'darwin-x64': 'x86_64-apple-darwin',
114
+ 'darwin-arm64': 'aarch64-apple-darwin',
115
+ 'win32-x64': 'x86_64-pc-windows-msvc',
116
+ 'win32-arm64': 'aarch64-pc-windows-msvc'
117
+ };
118
+
119
+ /** `@openai/codex-<platform>-<arch>/vendor/<triple>/bin/codex` — the CLI's own layout. */
120
+ function codexCandidates(modules: string): string[] {
121
+ const key = `${process.platform}-${process.arch}`;
122
+ const triple = CODEX_TARGET_TRIPLES[key];
123
+ if (!triple) return [];
124
+ return [join(modules, '@openai', `codex-${key}`, 'vendor', triple, 'bin', exe('codex'))];
125
+ }
126
+
127
+ // ─── Claude Code ─────────────────────────────────────────────────────────────
128
+
129
+ /**
130
+ * `@anthropic-ai/claude-agent-sdk-<platform>-<arch>[-musl]/claude`. The musl
131
+ * build is a separate package on Linux and is the one bun installs on Alpine,
132
+ * so both names are tried.
133
+ */
134
+ function claudeCandidates(modules: string): string[] {
135
+ const base = `claude-agent-sdk-${process.platform}-${process.arch}`;
136
+ const names = process.platform === 'linux' ? [base, `${base}-musl`] : [base];
137
+ return names.map(name => join(modules, '@anthropic-ai', name, exe('claude')));
138
+ }
139
+
140
+ /**
141
+ * Engines whose runtime needs an executable, and where to find it. Engines
142
+ * absent from this registry run entirely in process (Cline, Pi, Cursor) or let
143
+ * their SDK spawn a bundled entrypoint clopen never has to locate (Copilot,
144
+ * Qwen, both resolved module-relative inside the stack dir).
145
+ */
146
+ export const ENGINE_CLI: Partial<Record<ToolId, EngineCliSpec>> = {
147
+ opencode: {
148
+ binaryName: 'opencode',
149
+ versionSource: '@opencode-ai/sdk',
150
+ installPackage: 'opencode-ai',
151
+ // Without it the adapter cannot spawn `opencode serve`, so the engine is
152
+ // unusable — this is the one CLI that gates the engine's install state.
153
+ required: true,
154
+ candidates: modules => [
155
+ // The postinstall writes `bin/opencode.exe` on every platform, not just
156
+ // Windows — the extension is part of the shipped layout, not a guess.
157
+ join(modules, 'opencode-ai', 'bin', 'opencode.exe'),
158
+ ...opencodePlatformPackages().map(pkg => join(modules, pkg, 'bin', exe('opencode')))
159
+ ]
160
+ },
161
+ codex: {
162
+ binaryName: 'codex',
163
+ versionSource: '@openai/codex-sdk',
164
+ required: false,
165
+ candidates: codexCandidates
166
+ },
167
+ claude: {
168
+ binaryName: 'claude',
169
+ versionSource: '@anthropic-ai/claude-agent-sdk',
170
+ required: false,
171
+ candidates: claudeCandidates
172
+ }
173
+ };
174
+
175
+ /** The CLI spec for a tool, or null when the engine needs no external binary. */
176
+ export function getEngineCliSpec(tool: ToolId): EngineCliSpec | null {
177
+ return ENGINE_CLI[tool] ?? null;
178
+ }
179
+
180
+ /** The CLI spec only when a missing binary makes the engine unusable. */
181
+ export function getRequiredEngineCliSpec(tool: ToolId): EngineCliSpec | null {
182
+ const spec = ENGINE_CLI[tool];
183
+ return spec?.required ? spec : null;
184
+ }
185
+
186
+ /**
187
+ * Packages whose postinstall must be allowed to run inside the managed stack
188
+ * dir. bun blocks lifecycle scripts for untrusted dependencies, and a CLI
189
+ * package can ship a stub whose postinstall copies the real binary into place.
190
+ */
191
+ export function engineCliTrustedPackages(): string[] {
192
+ return Object.values(ENGINE_CLI)
193
+ .map(spec => spec.installPackage)
194
+ .filter((pkg): pkg is string => pkg !== undefined);
195
+ }
196
+
197
+ /** Version this CLI must match — the pin its version source carries. */
198
+ export function getRequiredCliVersion(spec: EngineCliSpec): string | null {
199
+ return getRequiredSdkVersion(spec.versionSource);
200
+ }
201
+
202
+ /** `<package>@<version>` install argument, or null when the SDK bundles the CLI. */
203
+ export function engineCliInstallArg(spec: EngineCliSpec): string | null {
204
+ if (!spec.installPackage) return null;
205
+ const version = getRequiredCliVersion(spec);
206
+ return version ? `${spec.installPackage}@${version}` : spec.installPackage;
207
+ }
208
+
209
+ export interface ResolvedEngineCli {
210
+ /** Absolute path of a binary that answered `--version`. */
211
+ path: string;
212
+ /** Version it reported, or null when the output was unparseable. */
213
+ version: string | null;
214
+ /** Where it came from: clopen's managed stack dir, or the user's PATH. */
215
+ source: 'stack' | 'path';
216
+ }
217
+
218
+ const resolved = new Map<ToolId, ResolvedEngineCli>();
219
+ const inFlight = new Map<ToolId, Promise<ResolvedEngineCli | null>>();
220
+
221
+ /**
222
+ * Drop cached resolutions. Only needed when a binary is replaced in place at a
223
+ * path that already resolved — a missing file is detected on the next call.
224
+ */
225
+ export function invalidateEngineCliCache(tool?: ToolId): void {
226
+ if (tool) resolved.delete(tool);
227
+ else resolved.clear();
228
+ }
229
+
230
+ /** Run `<binary> --version`; returns null when it cannot run or exits non-zero. */
231
+ async function probeBinary(path: string): Promise<{ version: string | null } | null> {
232
+ const controller = new AbortController();
233
+ const timer = setTimeout(() => controller.abort(), PROBE_TIMEOUT_MS);
234
+ try {
235
+ const proc = Bun.spawn([path, '--version'], {
236
+ stdout: 'pipe',
237
+ stderr: 'ignore',
238
+ stdin: 'ignore',
239
+ signal: controller.signal
240
+ });
241
+ const [stdout, exitCode] = await Promise.all([
242
+ new Response(proc.stdout).text(),
243
+ proc.exited
244
+ ]);
245
+ if (exitCode !== 0) return null;
246
+ const first = stdout.trim().split('\n')[0]?.trim() ?? '';
247
+ return { version: first || null };
248
+ } catch {
249
+ return null;
250
+ } finally {
251
+ clearTimeout(timer);
252
+ }
253
+ }
254
+
255
+ async function doResolve(tool: ToolId, spec: EngineCliSpec): Promise<ResolvedEngineCli | null> {
256
+ const modules = join(getStackEnginesDir(), 'node_modules');
257
+
258
+ const candidates: ResolvedEngineCli[] = spec.candidates(modules).map(path => ({
259
+ path,
260
+ version: null,
261
+ source: 'stack' as const
262
+ }));
263
+
264
+ const onPath = await resolveBinaryWithRefresh(spec.binaryName);
265
+ if (onPath) candidates.push({ path: onPath, version: null, source: 'path' });
266
+
267
+ for (const candidate of candidates) {
268
+ if (!existsSync(candidate.path)) continue;
269
+ const probe = await probeBinary(candidate.path);
270
+ if (!probe) {
271
+ debug.warn('engine', `${spec.binaryName} candidate did not run, skipping: ${candidate.path}`);
272
+ continue;
273
+ }
274
+ const hit: ResolvedEngineCli = { ...candidate, version: probe.version };
275
+ resolved.set(tool, hit);
276
+ debug.log(
277
+ 'engine',
278
+ `Resolved ${spec.binaryName} CLI from ${hit.source}: ${hit.path}` +
279
+ (hit.version ? ` (v${hit.version})` : '')
280
+ );
281
+ return hit;
282
+ }
283
+
284
+ debug.warn('engine', `No usable ${spec.binaryName} CLI found (stack dir or PATH)`);
285
+ return null;
286
+ }
287
+
288
+ /**
289
+ * Resolve a runnable CLI for an engine, or null when none is usable. Returns
290
+ * null immediately for engines that need no external binary — callers can treat
291
+ * "no spec" and "spec satisfied" alike by checking `getEngineCliSpec` first.
292
+ *
293
+ * Successful resolutions are cached (probing spawns a large binary) and
294
+ * revalidated by existence on every call; failures are not cached, so a repair
295
+ * install becomes visible as soon as it lands.
296
+ */
297
+ export async function resolveEngineCli(tool: ToolId): Promise<ResolvedEngineCli | null> {
298
+ const spec = ENGINE_CLI[tool];
299
+ if (!spec) return null;
300
+
301
+ const cached = resolved.get(tool);
302
+ if (cached) {
303
+ if (existsSync(cached.path)) return cached;
304
+ resolved.delete(tool);
305
+ }
306
+
307
+ const pending = inFlight.get(tool);
308
+ if (pending) return pending;
309
+
310
+ const p = doResolve(tool, spec).finally(() => { inFlight.delete(tool); });
311
+ inFlight.set(tool, p);
312
+ return p;
313
+ }
@@ -7,14 +7,21 @@
7
7
  * - required account not set up → Settings → Engines (sign in)
8
8
  *
9
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
10
+ * account is asked for. Engines that also need an external CLI binary (Open
11
+ * Code) are only ready once that binary resolves too — the SDK alone cannot run
12
+ * them, and waving them through would send the user off to sign in for an engine
13
+ * that fails at spawn.
14
+ *
15
+ * The message text embeds the literal "Settings → Stack" / "Settings → Engines"
16
+ * phrases; the chat error renderer
12
17
  * (`frontend/components/chat/formatters/ErrorMessage.svelte`) turns those into
13
18
  * clickable buttons that open the matching settings section.
14
19
  */
15
20
 
16
21
  import type { EngineType } from '$shared/types/unified';
17
22
  import { readEngineSdkVersion, getRequiredSdkVersion } from './sdk-loader';
23
+ import { getRequiredEngineCliSpec, resolveEngineCli } from './engine-cli';
24
+ import type { ToolId } from './install-recipes';
18
25
 
19
26
  /** Primary SDK package clopen imports for each engine. */
20
27
  export const ENGINE_SDK: Record<EngineType, string> = {
@@ -28,6 +35,22 @@ export const ENGINE_SDK: Record<EngineType, string> = {
28
35
  cursor: '@cursor/sdk',
29
36
  };
30
37
 
38
+ /**
39
+ * Engine identity in the Stack's id space. The two namespaces exist because
40
+ * Stack also manages non-engine tools (git, chrome) and spells Claude Code
41
+ * "claude"; `install-recipes.test.ts` guards this mapping against drift.
42
+ */
43
+ export const TOOL_FOR_ENGINE: Record<EngineType, ToolId> = {
44
+ 'claude-code': 'claude',
45
+ opencode: 'opencode',
46
+ copilot: 'copilot',
47
+ codex: 'codex',
48
+ qwen: 'qwen',
49
+ pi: 'pi',
50
+ cline: 'cline',
51
+ cursor: 'cursor',
52
+ };
53
+
31
54
  /**
32
55
  * Engines that require a signed-in account/credential before use. OpenCode
33
56
  * ships built-in providers and works without one, so it is exempt.
@@ -43,7 +66,7 @@ export interface EngineSetupIssue {
43
66
  * Returns null when the engine is ready to stream, or an actionable issue.
44
67
  * @param accountId the resolved account id for this request (0 = none selected).
45
68
  */
46
- export function checkEngineSetup(engine: EngineType, accountId: number): EngineSetupIssue | null {
69
+ export async function checkEngineSetup(engine: EngineType, accountId: number): Promise<EngineSetupIssue | null> {
47
70
  const sdkPkg = ENGINE_SDK[engine];
48
71
  const installed = readEngineSdkVersion(sdkPkg);
49
72
  const required = getRequiredSdkVersion(sdkPkg);
@@ -62,6 +85,20 @@ export function checkEngineSetup(engine: EngineType, accountId: number): EngineS
62
85
  `Open Settings → Stack to update it before using this engine.`
63
86
  };
64
87
  }
88
+
89
+ // A CLI the engine cannot run without is installed by the same Stack action
90
+ // as the SDK, so a missing one is the same fix for the user: install the
91
+ // engine. CLIs the SDK bundles and locates itself are not checked here.
92
+ const tool = TOOL_FOR_ENGINE[engine];
93
+ if (getRequiredEngineCliSpec(tool) && !(await resolveEngineCli(tool))) {
94
+ return {
95
+ reason: 'not-installed',
96
+ message:
97
+ `Engine "${engine}" is missing its CLI. ` +
98
+ `Open Settings → Stack to install it before using this engine.`
99
+ };
100
+ }
101
+
65
102
  if (!ENGINES_WITHOUT_ACCOUNT.has(engine) && accountId === 0) {
66
103
  return {
67
104
  reason: 'needs-account',
@@ -15,15 +15,24 @@
15
15
  * `readEngineSdkVersion` compounds it: `loadEngineSdk` only enforces a version
16
16
  * match when a required version exists, so an unpinned package also loses the
17
17
  * "needs update" check that would otherwise surface the drift in Settings → Stack.
18
+ *
19
+ * Engine CLIs (engine-cli.ts) are pinned one step removed — through their SDK's
20
+ * version, since a platform binary has no business in devDependencies — and
21
+ * they only work if bun is allowed to run their postinstall. Both of those are
22
+ * silent failures too: an unpinned CLI floats to @latest, and an untrusted one
23
+ * installs a stub that fails at the first spawn.
18
24
  */
19
25
 
20
26
  import { describe, expect, test } from 'bun:test';
21
- import { readFileSync } from 'node:fs';
27
+ import { mkdtempSync, readFileSync, writeFileSync } from 'node:fs';
28
+ import { tmpdir } from 'node:os';
22
29
  import { join } from 'node:path';
23
30
  import type { EngineType } from '$shared/types/unified';
24
- import { ENGINE_PACKAGES, type ToolId } from './install-recipes';
25
- import { ENGINE_SDK } from './engine-setup';
31
+ import { ENGINE_PACKAGES, engineInstallArgs, type ToolId } from './install-recipes';
32
+ import { ENGINE_SDK, TOOL_FOR_ENGINE } from './engine-setup';
26
33
  import { getRequiredSdkVersion } from './sdk-loader';
34
+ import { ENGINE_CLI, engineCliTrustedPackages, getRequiredCliVersion } from './engine-cli';
35
+ import { ensureStackProject } from './stack-project';
27
36
 
28
37
  const pkg = JSON.parse(
29
38
  readFileSync(join(import.meta.dir, '..', '..', 'package.json'), 'utf8')
@@ -71,7 +80,7 @@ describe('on-demand engine SDKs', () => {
71
80
  // would probe a package nobody installs — reporting an installed engine as
72
81
  // missing, or worse, waving through one that cannot load. TypeScript only
73
82
  // forces the keys to exist; the values have to be checked.
74
- const TOOL_FOR_ENGINE: Record<EngineType, ToolId> = {
83
+ const expectedToolForEngine: Record<EngineType, ToolId> = {
75
84
  'claude-code': 'claude',
76
85
  opencode: 'opencode',
77
86
  copilot: 'copilot',
@@ -82,7 +91,11 @@ describe('on-demand engine SDKs', () => {
82
91
  cursor: 'cursor',
83
92
  };
84
93
 
85
- const drift = Object.entries(TOOL_FOR_ENGINE).flatMap(([engine, tool]) => {
94
+ // The mapping ships in engine-setup (readiness and status both resolve a
95
+ // tool id through it); this independent copy is what detects a silent edit.
96
+ expect(TOOL_FOR_ENGINE).toEqual(expectedToolForEngine);
97
+
98
+ const drift = Object.entries(expectedToolForEngine).flatMap(([engine, tool]) => {
86
99
  const probed = ENGINE_SDK[engine as EngineType];
87
100
  const installed = ENGINE_PACKAGES[tool]?.[0];
88
101
  if (installed === undefined) return [`${engine}: no install recipe for tool "${tool}"`];
@@ -103,3 +116,84 @@ describe('on-demand engine SDKs', () => {
103
116
  }
104
117
  });
105
118
  });
119
+
120
+ describe('on-demand engine CLIs', () => {
121
+ const cliEntries = Object.entries(ENGINE_CLI).map(([tool, spec]) => ({ tool: tool as ToolId, spec }));
122
+
123
+ test('the registry is non-empty', () => {
124
+ // Open Code is the one engine that needs a CLI; an emptied registry would
125
+ // make every check below vacuous and re-open the bug it exists to prevent.
126
+ expect(cliEntries.length).toBeGreaterThan(0);
127
+ });
128
+
129
+ test('every CLI is pinned through a declared, exact SDK version', () => {
130
+ // A CLI is not in package.json (it is a platform binary weighing hundreds
131
+ // of megabytes), so its version rides on the SDK it ships with or is
132
+ // released in lockstep with. If that source is missing or floated, a
133
+ // separately-installed CLI lands at @latest against a pinned SDK.
134
+ const unpinned = cliEntries
135
+ .filter(({ spec }) => !/^\d+\.\d+\.\d+/.test(declared[spec.versionSource] ?? ''))
136
+ .map(({ tool, spec }) => `${tool}: pins via "${spec.versionSource}" (${declared[spec.versionSource]})`);
137
+
138
+ expect(unpinned).toEqual([]);
139
+
140
+ for (const { spec } of cliEntries) {
141
+ expect(getRequiredCliVersion(spec)).toBe(declared[spec.versionSource]!);
142
+ }
143
+ });
144
+
145
+ test('the installer installs a separate CLI alongside the SDK', () => {
146
+ // Installing the SDK alone is exactly the half-install that reported
147
+ // "installed" in Settings → Stack and then failed at the first spawn.
148
+ // CLIs bundled with their SDK need no extra package and must not add one.
149
+ for (const { tool, spec } of cliEntries) {
150
+ const args = engineInstallArgs(tool);
151
+ if (spec.installPackage) {
152
+ expect(args).toContain(`${spec.installPackage}@${declared[spec.versionSource]}`);
153
+ } else {
154
+ expect(args).toEqual(ENGINE_PACKAGES[tool]!.map(name => `${name}@${declared[name]}`));
155
+ }
156
+ }
157
+ });
158
+
159
+ test('only an engine-blocking CLI gates the install state', () => {
160
+ // `required` decides whether a missing binary makes Settings → Stack report
161
+ // the engine as not installed. Marking a bundled CLI required would flip a
162
+ // working engine to "not installed" the moment our own path guess drifts
163
+ // from the SDK's; leaving Open Code's optional would restore the original
164
+ // bug, where an unspawnable engine reported itself ready.
165
+ const required = cliEntries.filter(({ spec }) => spec.required).map(({ tool }) => tool);
166
+ expect(required).toEqual(['opencode']);
167
+ });
168
+
169
+ test('the managed dir trusts every CLI postinstall', () => {
170
+ // bun blocks postinstall scripts for untrusted packages, and these CLIs
171
+ // ship a stub whose postinstall copies the real binary into place.
172
+ const dir = mkdtempSync(join(tmpdir(), 'clopen-stack-'));
173
+ ensureStackProject(dir);
174
+
175
+ const created = JSON.parse(readFileSync(join(dir, 'package.json'), 'utf8')) as { trustedDependencies?: string[] };
176
+ expect(created.trustedDependencies).toEqual(engineCliTrustedPackages().sort());
177
+ });
178
+
179
+ test('an older managed dir is upgraded in place', () => {
180
+ // Machines bootstrapped by earlier builds already have a package.json
181
+ // without the field; merging (not just creating) is what repairs them.
182
+ const dir = mkdtempSync(join(tmpdir(), 'clopen-stack-'));
183
+ writeFileSync(
184
+ join(dir, 'package.json'),
185
+ JSON.stringify({ name: 'clopen-stack-engines', private: true, version: '0.0.0', dependencies: { '@opencode-ai/sdk': '1.18.18' } })
186
+ );
187
+
188
+ ensureStackProject(dir);
189
+
190
+ const merged = JSON.parse(readFileSync(join(dir, 'package.json'), 'utf8')) as {
191
+ dependencies?: Record<string, string>;
192
+ trustedDependencies?: string[];
193
+ };
194
+ expect(merged.dependencies).toEqual({ '@opencode-ai/sdk': '1.18.18' });
195
+ for (const pkg of engineCliTrustedPackages()) {
196
+ expect(merged.trustedDependencies).toContain(pkg);
197
+ }
198
+ });
199
+ });
@@ -20,6 +20,7 @@ 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
22
  import { getStackEnginesDir, readEngineSdkVersion, getRequiredSdkVersion } from './sdk-loader';
23
+ import { engineCliInstallArg, getEngineCliSpec, getRequiredEngineCliSpec, resolveEngineCli } from './engine-cli';
23
24
 
24
25
  export type ToolId = 'git' | 'claude' | 'opencode' | 'copilot' | 'codex' | 'qwen' | 'pi' | 'cline' | 'cursor' | 'chrome';
25
26
 
@@ -123,13 +124,23 @@ function isEngineTool(tool: ToolId): boolean {
123
124
  return tool in ENGINE_PACKAGES;
124
125
  }
125
126
 
126
- /** `bun add` arg vector for an engine: each package pinned to its package.json version. */
127
- function engineInstallArgs(tool: ToolId): string[] {
127
+ /**
128
+ * `bun add` arg vector for an engine: each package pinned to its package.json
129
+ * version, plus the engine's CLI package when it needs one (see engine-cli.ts).
130
+ * The CLI is pinned through its SDK's version instead of a package.json entry
131
+ * of its own — it is a platform binary, not something to put in devDependencies.
132
+ */
133
+ export function engineInstallArgs(tool: ToolId): string[] {
128
134
  const packages = ENGINE_PACKAGES[tool] ?? [];
129
- return packages.map(name => {
135
+ const args = packages.map(name => {
130
136
  const v = getRequiredSdkVersion(name);
131
137
  return v ? `${name}@${v}` : name;
132
138
  });
139
+
140
+ const cli = getEngineCliSpec(tool);
141
+ const cliArg = cli ? engineCliInstallArg(cli) : null;
142
+ if (cliArg) args.push(cliArg);
143
+ return args;
133
144
  }
134
145
 
135
146
 
@@ -269,14 +280,38 @@ export async function getToolStatus(tool: ToolId): Promise<ToolStatus> {
269
280
 
270
281
  if (isEngineTool(tool)) {
271
282
  // Engines are detected by the presence of their SDK in the clopen-managed
272
- // stack dir (installed on demand there), NOT by a CLI binary on PATH — the
273
- // SDK is what the engine adapter actually needs.
283
+ // stack dir (installed on demand there) — that is what the adapter loads.
274
284
  const sdkPkg = ENGINE_PACKAGES[tool]![0];
275
- const version = readEngineSdkVersion(sdkPkg);
285
+ const sdkVersion = readEngineSdkVersion(sdkPkg);
276
286
  const requiredVersion = getRequiredSdkVersion(sdkPkg);
277
- if (!version) return { tool, installed: false, version: null, source: null, requiredVersion, needsUpdate: false };
278
- const needsUpdate = requiredVersion !== null && version !== requiredVersion;
279
- return { tool, installed: true, version, source: getStackEnginesDir(), requiredVersion, needsUpdate };
287
+ if (!sdkVersion) return { tool, installed: false, version: null, source: null, requiredVersion, needsUpdate: false };
288
+ const sdkNeedsUpdate = requiredVersion !== null && sdkVersion !== requiredVersion;
289
+
290
+ // Only a CLI the engine cannot run without gates its install state; a CLI
291
+ // the SDK bundles and locates itself arrives with the engine anyway.
292
+ const cliSpec = getRequiredEngineCliSpec(tool);
293
+ if (!cliSpec) {
294
+ return { tool, installed: true, version: sdkVersion, source: getStackEnginesDir(), requiredVersion, needsUpdate: sdkNeedsUpdate };
295
+ }
296
+
297
+ // Engines that cannot run without an external CLI (Open Code) count as
298
+ // installed only when a runnable binary exists. Reporting the SDK alone is
299
+ // what let Stack show "installed" for an engine nothing could spawn.
300
+ const cli = await resolveEngineCli(tool);
301
+ if (!cli) return { tool, installed: false, version: null, source: null, requiredVersion, needsUpdate: false };
302
+
303
+ // The CLI is the artifact that actually runs, so it decides the reported
304
+ // version — a user's own older copy on PATH surfaces as "needs update"
305
+ // instead of hiding behind the pinned SDK version.
306
+ const cliNeedsUpdate = requiredVersion !== null && cli.version !== null && cli.version !== requiredVersion;
307
+ return {
308
+ tool,
309
+ installed: true,
310
+ version: cli.version ?? sdkVersion,
311
+ source: cli.path,
312
+ requiredVersion,
313
+ needsUpdate: sdkNeedsUpdate || cliNeedsUpdate
314
+ };
280
315
  }
281
316
 
282
317
  const resolved = await resolveBinaryWithRefresh(tool);
@@ -421,8 +456,9 @@ function attachCurlRequirement(base: Recipe, toolLabel: string): boolean {
421
456
  * Engine install recipe — installs the exact engine SDK package(s) declared in
422
457
  * package.json (the single source of truth) into the clopen-managed stack dir
423
458
  * (`~/.clopen/stack/engines`), NOT the user's global bun store. Installing the
424
- * SDK also pulls whatever CLI binary the SDK bundles. Versions are pinned,
425
- * never floated to `latest`.
459
+ * SDK also pulls whatever CLI binary the SDK bundles, plus — for engines whose
460
+ * SDK bundles none (Open Code) — the separate package that carries the CLI.
461
+ * Versions are pinned, never floated to `latest`.
426
462
  */
427
463
  function resolveEngineRecipe(tool: ToolId): Recipe {
428
464
  const args = engineInstallArgs(tool);
@@ -18,8 +18,6 @@
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';
23
21
  import { debug } from '$shared/utils/logger';
24
22
  import { ws } from '$backend/utils/ws';
25
23
  import { getCleanSpawnEnv } from '$backend/utils/env';
@@ -27,26 +25,21 @@ import { refreshProcessPath } from '$backend/utils/path-enrich';
27
25
  import { ensureCurlAvailable } from '$backend/utils/static-curl';
28
26
  import type { Recipe, ToolId } from './install-recipes';
29
27
  import { resolveRecipe } from './install-recipes';
28
+ import { ensureStackProject } from './stack-project';
29
+ import { invalidateEngineCliCache } from './engine-cli';
30
30
 
31
31
  const RING_BUFFER_LINES = 10_000;
32
32
  const RETENTION_MS = 5 * 60 * 1000;
33
33
 
34
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.
35
+ * Ensure a recipe's working directory is ready before `bun add` runs there.
36
+ * Engine recipes install into the clopen-managed stack dir
37
+ * (`~/.clopen/stack/engines`), whose package.json both roots the install and
38
+ * carries the `trustedDependencies` that let engine CLI postinstalls run.
39
39
  */
40
40
  function ensureRecipeCwd(recipe: Recipe): void {
41
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
- }
42
+ ensureStackProject(recipe.cwd);
50
43
  }
51
44
 
52
45
  export type SessionStatus = 'running' | 'success' | 'failed' | 'cancelled';
@@ -74,6 +67,8 @@ interface Session {
74
67
 
75
68
  const sessions = new Map<string, Session>();
76
69
  const activeByTool = new Map<ToolId, string>();
70
+ /** Run promise per session, so callers can await an install they didn't start. */
71
+ const runs = new Map<string, Promise<void>>();
77
72
 
78
73
  function newRingBuffer(): RingBuffer {
79
74
  return { lines: [], total: 0 };
@@ -91,6 +86,7 @@ function scheduleRetention(session: Session): void {
91
86
  if (session.retentionTimer) clearTimeout(session.retentionTimer);
92
87
  session.retentionTimer = setTimeout(() => {
93
88
  sessions.delete(session.id);
89
+ runs.delete(session.id);
94
90
  if (activeByTool.get(session.tool) === session.id) {
95
91
  activeByTool.delete(session.tool);
96
92
  }
@@ -189,6 +185,11 @@ function finalizeSession(session: Session, preferredStatus: SessionStatus, exitC
189
185
  session.endedAt = Date.now();
190
186
  session.proc = null;
191
187
 
188
+ // An install can replace the binary a previous resolution cached (a user's
189
+ // own older copy on PATH, or a stub swapped for the real thing at the same
190
+ // path), so the next lookup must probe again rather than trust the cache.
191
+ invalidateEngineCliCache(session.tool);
192
+
192
193
  debug.log('path', `[install:${session.id}] Finished status=${session.status} exit=${exitCode}`);
193
194
 
194
195
  ws.emit.user(session.startedBy, 'stack:install-finished', {
@@ -307,6 +308,14 @@ async function runInstall(session: Session, env: Record<string, string>): Promis
307
308
  finalizeSession(session, exitCode === 0 ? 'success' : 'failed', exitCode);
308
309
  }
309
310
 
311
+ /**
312
+ * Owner id for installs clopen starts itself (startup repair), rather than a
313
+ * user clicking Install. Sessions carry an owner so one admin cannot drive
314
+ * another's install; system-owned sessions are readable by any admin instead
315
+ * (see `requireInstallSessionAccess`) so the repair is visible and cancellable.
316
+ */
317
+ export const SYSTEM_INSTALL_USER = 'system';
318
+
310
319
  export async function startInstall(tool: ToolId, userId: string): Promise<Session> {
311
320
  await refreshProcessPath();
312
321
 
@@ -356,15 +365,24 @@ export async function startInstall(tool: ToolId, userId: string): Promise<Sessio
356
365
  startedAt: session.startedAt
357
366
  });
358
367
 
359
- runInstall(session, env).catch((err) => {
368
+ runs.set(id, runInstall(session, env).catch((err) => {
360
369
  debug.error('path', `[install:${id}] runner crash:`, err);
361
370
  emitStream(session, 'stderr', `runner crash: ${err instanceof Error ? err.message : String(err)}\n`);
362
371
  finalizeSession(session, 'failed', -1);
363
- });
372
+ }));
364
373
 
365
374
  return session;
366
375
  }
367
376
 
377
+ /**
378
+ * Resolve once the install has finished (success, failure or cancellation).
379
+ * Resolves immediately for an unknown or already-collected session, so callers
380
+ * can await without racing session retention.
381
+ */
382
+ export function awaitInstall(sessionId: string): Promise<void> {
383
+ return runs.get(sessionId) ?? Promise.resolve();
384
+ }
385
+
368
386
  export function cancelInstall(sessionId: string): boolean {
369
387
  const session = sessions.get(sessionId);
370
388
  if (!session || session.status !== 'running') return false;
@@ -0,0 +1,72 @@
1
+ /**
2
+ * Managed stack project bootstrap
3
+ *
4
+ * `~/.clopen/stack/engines` is a minimal bun project. A package.json must exist
5
+ * there before `bun add` runs, or bun walks up the tree and installs into
6
+ * whatever project happens to contain the directory.
7
+ *
8
+ * It must also declare `trustedDependencies`. bun blocks postinstall scripts
9
+ * for untrusted packages, and an engine CLI package ships only a stub — its
10
+ * real binary is copied into place by exactly that postinstall. Without the
11
+ * entry the install still reports success and leaves behind a shell script that
12
+ * prints "postinstall script was not run", which is precisely the half-installed
13
+ * state that used to reach the adapter.
14
+ *
15
+ * Both install paths (the user-triggered runner and the startup bootstrap) go
16
+ * through here, and the file is MERGED rather than only created, so a stack dir
17
+ * written by an older clopen picks the field up on its next install.
18
+ */
19
+
20
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
21
+ import { join } from 'node:path';
22
+ import { debug } from '$shared/utils/logger';
23
+ import { engineCliTrustedPackages } from './engine-cli';
24
+
25
+ interface StackPackageJson {
26
+ name?: string;
27
+ private?: boolean;
28
+ version?: string;
29
+ trustedDependencies?: string[];
30
+ [key: string]: unknown;
31
+ }
32
+
33
+ const BASE: StackPackageJson = {
34
+ name: 'clopen-stack-engines',
35
+ private: true,
36
+ version: '0.0.0'
37
+ };
38
+
39
+ function readExisting(path: string): StackPackageJson | null {
40
+ if (!existsSync(path)) return null;
41
+ try {
42
+ const parsed = JSON.parse(readFileSync(path, 'utf8')) as unknown;
43
+ if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {
44
+ return parsed as StackPackageJson;
45
+ }
46
+ } catch {
47
+ // Corrupt file: fall through and rewrite from the base template rather
48
+ // than leaving a package.json bun will choke on.
49
+ }
50
+ return null;
51
+ }
52
+
53
+ /**
54
+ * Ensure `dir` is a bun project that trusts every engine CLI package. Safe to
55
+ * call repeatedly; writes only when the file is missing or would change.
56
+ */
57
+ export function ensureStackProject(dir: string): void {
58
+ mkdirSync(dir, { recursive: true });
59
+ const path = join(dir, 'package.json');
60
+
61
+ const existing = readExisting(path);
62
+ const merged: StackPackageJson = { ...BASE, ...(existing ?? {}) };
63
+
64
+ const trusted = new Set([...(merged.trustedDependencies ?? []), ...engineCliTrustedPackages()]);
65
+ merged.trustedDependencies = [...trusted].sort();
66
+
67
+ const next = JSON.stringify(merged, null, 2) + '\n';
68
+ if (existing !== null && readFileSync(path, 'utf8') === next) return;
69
+
70
+ writeFileSync(path, next);
71
+ debug.log('engine', `Stack project package.json ${existing ? 'updated' : 'created'}: ${path}`);
72
+ }
@@ -84,6 +84,8 @@ function windowsKnownDirs(): string[] {
84
84
  join(home, '.bun', 'bin'),
85
85
  join(home, '.deno', 'bin'),
86
86
  join(home, '.cargo', 'bin'),
87
+ // install-script target (Open Code), the Windows twin of the posix entry
88
+ join(home, '.opencode', 'bin'),
87
89
  join(home, 'scoop', 'shims'),
88
90
  join(localAppData, 'Microsoft', 'WinGet', 'Links'),
89
91
  join(localAppData, 'Programs', 'Git', 'cmd'),
@@ -19,7 +19,7 @@ import { createRouter } from '$shared/utils/ws-server';
19
19
  import { ws } from '$backend/utils/ws';
20
20
  import { engineQueries } from '../../../database/queries';
21
21
  import { resetEnvironment, getClaudeUserConfigDir } from '../../../engine/adapters/claude/environment';
22
- import { resolveBinaryWithRefresh } from '../../../utils/cli';
22
+ import { resolveEngineCli } from '$backend/engine/engine-cli';
23
23
  import { debug } from '$shared/utils/logger';
24
24
  import { getCleanSpawnEnv } from '../../../utils/env';
25
25
  import { requireSetupSessionAccess } from '../access';
@@ -209,11 +209,16 @@ export const accountsHandler = createRouter()
209
209
  ptyEnv['CLAUDE_CONFIG_DIR'] = getClaudeUserConfigDir();
210
210
  ptyEnv['BROWSER'] = 'false';
211
211
 
212
- const claudeCmd = await resolveBinaryWithRefresh('claude');
213
- if (!claudeCmd) throw new Error('claude binary not found on PATH');
212
+ // The CLI ships inside the Claude Agent SDK's platform package in the
213
+ // managed stack dir, so sign-in must not demand a global install the way
214
+ // it used to — `resolveEngineCli` prefers that copy and falls back to PATH.
215
+ const claudeCli = await resolveEngineCli('claude');
216
+ if (!claudeCli) {
217
+ throw new Error('Claude Code CLI not found. Open Settings → Stack to install the engine.');
218
+ }
214
219
  let pty: ReturnType<typeof spawn>;
215
220
  try {
216
- pty = spawn(claudeCmd, ['setup-token'], {
221
+ pty = spawn(claudeCli.path, ['setup-token'], {
217
222
  name: 'xterm-256color',
218
223
  cols: 1000,
219
224
  rows: 30,
@@ -48,7 +48,7 @@ import {
48
48
  serializeCodexCredential,
49
49
  getCodexHomeDir,
50
50
  } from '../../../engine/adapters/codex/credential';
51
- import { resolveBinaryWithRefresh } from '../../../utils/cli';
51
+ import { resolveEngineCli } from '$backend/engine/engine-cli';
52
52
  import { getCleanSpawnEnv } from '../../../utils/env';
53
53
  import { debug } from '$shared/utils/logger';
54
54
  import { requireSetupSessionAccess } from '../access';
@@ -328,11 +328,14 @@ export const codexAccountsHandler = createRouter()
328
328
  const existing = userSetups.get(userId);
329
329
  if (existing) cleanupSetup(existing);
330
330
 
331
- const codexCmd = await resolveBinaryWithRefresh('codex');
332
- if (!codexCmd) {
331
+ // The CLI is vendored inside the Codex SDK's platform package in the
332
+ // managed stack dir; resolving through `resolveEngineCli` means sign-in
333
+ // works off a Stack install instead of demanding a global one.
334
+ const codexCli = await resolveEngineCli('codex');
335
+ if (!codexCli) {
333
336
  ws.emit.user(userId, 'engine:codex-account-setup-error', {
334
337
  setupId,
335
- message: 'Codex CLI not found on PATH. Install it via Settings → Stack.'
338
+ message: 'Codex CLI not found. Install the engine via Settings → Stack.'
336
339
  });
337
340
  return;
338
341
  }
@@ -352,7 +355,7 @@ export const codexAccountsHandler = createRouter()
352
355
 
353
356
  let pty: ReturnType<typeof spawn>;
354
357
  try {
355
- pty = spawn(codexCmd, args, {
358
+ pty = spawn(codexCli.path, args, {
356
359
  name: 'xterm-256color',
357
360
  cols: 1000,
358
361
  rows: 30,
@@ -1,33 +1,26 @@
1
1
  /**
2
2
  * OpenAI Codex Engine Status Handler
3
3
  *
4
- * Reports SDK availability + active account state. Codex differs from
5
- * Copilot in that the SDK does NOT bundle a CLI internally — the CLI must
6
- * be installed on PATH (Stack → Codex CLI). `installed` reflects
7
- * whether the `codex` binary resolves on the host's PATH.
4
+ * Reports SDK availability + active account state. `installed` tracks the SDK;
5
+ * `version` is the CLI's, since that is the process Codex actually runs. That
6
+ * binary is vendored inside the SDK's platform package in the managed stack dir
7
+ * (or comes from PATH when the user installed Codex themselves) — reading it
8
+ * off PATH alone left the version blank on a Stack-only install.
8
9
  */
9
10
 
10
11
  import { t } from 'elysia';
11
12
  import { createRouter } from '$shared/utils/ws-server';
12
13
  import { engineQueries } from '../../../database/queries';
13
- import { resolveBinaryWithRefresh } from '../../../utils/cli';
14
+ import { resolveEngineCli } from '$backend/engine/engine-cli';
14
15
  import { getBackendOS } from '../../../utils/os';
15
16
  import { debug } from '$shared/utils/logger';
16
17
  import { readEngineSdkVersion } from '$backend/engine/sdk-loader';
17
18
 
18
19
  async function readCliVersion(): Promise<string | null> {
19
- const bin = await resolveBinaryWithRefresh('codex');
20
- if (!bin) return null;
21
- try {
22
- const proc = Bun.spawn([bin, '--version'], { stdout: 'pipe', stderr: 'pipe' });
23
- const exitCode = await proc.exited;
24
- if (exitCode !== 0) return null;
25
- const stdout = await new Response(proc.stdout).text();
26
- const first = stdout.trim().split('\n')[0]?.trim() ?? '';
27
- return first || null;
28
- } catch {
29
- return null;
30
- }
20
+ // `resolveEngineCli` already ran `--version` on the binary it handed back,
21
+ // so the version comes for free with the resolution.
22
+ const cli = await resolveEngineCli('codex');
23
+ return cli?.version ?? null;
31
24
  }
32
25
 
33
26
  export const codexStatusHandler = createRouter()
@@ -133,7 +133,7 @@ export const crudHandler = createRouter()
133
133
  // account and has none (→ Engines). Mirrors the chat pre-stream gate so
134
134
  // the model picker reflects the same install/sign-in state as chat.
135
135
  const activeAccount = engineQueries.getActiveAccountForEngine(engineType);
136
- const setupIssue = checkEngineSetup(engineType, activeAccount?.id ?? 0);
136
+ const setupIssue = await checkEngineSetup(engineType, activeAccount?.id ?? 0);
137
137
  if (setupIssue) throw new Error(setupIssue.message);
138
138
 
139
139
  // Uniform path for every engine. Each adapter's getAvailableModels()
@@ -9,7 +9,7 @@
9
9
 
10
10
  import type { WSConnection } from '$shared/utils/ws-server';
11
11
  import { ws } from '$backend/utils/ws';
12
- import { getSession, getSessionOwner } from '$backend/engine/install-runner';
12
+ import { getSession, getSessionOwner, SYSTEM_INSTALL_USER } from '$backend/engine/install-runner';
13
13
 
14
14
  type InstallSession = NonNullable<ReturnType<typeof getSession>>;
15
15
 
@@ -21,7 +21,10 @@ type InstallSession = NonNullable<ReturnType<typeof getSession>>;
21
21
  export function requireInstallSessionAccess(conn: WSConnection, sessionId: string): InstallSession | null {
22
22
  const userId = ws.getUserId(conn);
23
23
  const owner = getSessionOwner(sessionId);
24
- if (owner && owner !== userId) {
24
+ // Installs clopen starts itself belong to no user; any admin reaching this
25
+ // guard may watch or cancel them, otherwise a startup repair would show up
26
+ // in Settings → Stack as a running session nobody is allowed to touch.
27
+ if (owner && owner !== SYSTEM_INSTALL_USER && owner !== userId) {
25
28
  throw new Error('Install session not found');
26
29
  }
27
30
  return getSession(sessionId);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@myrialabs/clopen",
3
- "version": "0.4.30",
3
+ "version": "0.4.31",
4
4
  "description": "All-in-one web workspace for AI coding agents — Claude Code, OpenCode, Codex, Copilot, Qwen Code, Pi, Cline, and Cursor — with chat, terminal, git, browser preview, database client, checkpoints, and real-time collaboration",
5
5
  "author": "Myria Labs",
6
6
  "license": "MIT",