@myrialabs/clopen 0.4.29 → 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.
- package/backend/chat/stream-manager.ts +1 -1
- package/backend/database/migrations/067_add_memory_graph_layout.ts +91 -0
- package/backend/database/migrations/index.ts +7 -0
- package/backend/database/queries/graph-queries.ts +417 -32
- package/backend/db-client/drivers/mssql.ts +57 -22
- package/backend/db-client/drivers/mysql.ts +69 -48
- package/backend/db-client/drivers/postgres.ts +65 -53
- package/backend/engine/adapters/claude/stream.ts +81 -15
- package/backend/engine/adapters/codex/stream.ts +6 -3
- package/backend/engine/adapters/opencode/server.ts +13 -4
- package/backend/engine/bootstrap-default-engine.ts +67 -38
- package/backend/engine/docs/artifacts.md +1 -1
- package/backend/engine/docs/quick-reference.md +1 -1
- package/backend/engine/engine-cli.ts +313 -0
- package/backend/engine/engine-setup.ts +40 -3
- package/backend/engine/install-recipes.test.ts +99 -5
- package/backend/engine/install-recipes.ts +47 -11
- package/backend/engine/install-runner.ts +34 -16
- package/backend/engine/stack-project.ts +72 -0
- package/backend/index.ts +5 -0
- package/backend/memory/bootstrap.ts +9 -0
- package/backend/memory/layout.ts +985 -0
- package/backend/memory/notify.ts +33 -7
- package/backend/memory/view.ts +375 -69
- package/backend/permissions/index.ts +4 -2
- package/backend/permissions/resolve.ts +7 -5
- package/backend/utils/path-enrich.ts +2 -0
- package/backend/utils/process-warnings.ts +41 -0
- package/backend/ws/engine/claude/accounts.ts +9 -4
- package/backend/ws/engine/codex/accounts.ts +8 -5
- package/backend/ws/engine/codex/status.ts +10 -17
- package/backend/ws/memory/crud.ts +50 -2
- package/backend/ws/settings/crud.ts +1 -1
- package/backend/ws/stack/access.ts +5 -2
- package/dist/assets/{index-C7e5TWG3.js → index-DUc5T21e.js} +1 -1
- package/dist/assets/{index-Derlqeyy.js → index-DYwQ5bP8.js} +1 -1
- package/dist/assets/main-VgdjTBLR.css +1 -0
- package/dist/assets/{main-OGhsRKU1.js → main-r0iv2PDz.js} +393 -386
- package/dist/index.html +2 -2
- package/package.json +1 -1
- package/shared/types/memory.ts +70 -0
- package/dist/assets/main-CqzaPnux.css +0 -1
|
@@ -1,20 +1,36 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* Fresh-install default engine bootstrap.
|
|
2
|
+
* Fresh-install default engine bootstrap & repair.
|
|
3
3
|
*
|
|
4
|
-
*
|
|
5
|
-
*
|
|
6
|
-
*
|
|
7
|
-
*
|
|
8
|
-
*
|
|
9
|
-
* so
|
|
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 {
|
|
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
|
|
41
|
-
* safe to call at every startup and after a data wipe; it no-ops
|
|
42
|
-
*
|
|
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
|
-
|
|
53
|
-
|
|
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
|
-
|
|
56
|
-
|
|
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
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
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
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
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
|
-
|
|
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
|
}
|
|
@@ -98,7 +98,7 @@ reliably re-read per turn — the prompt is the one genuinely per-session channe
|
|
|
98
98
|
| **Commands** (`backend/commands/`) | custom slash commands | global, project | one `.md` per command into the engine command dir, or synthetic preamble. Profile-bundled |
|
|
99
99
|
| **Subagents** (`backend/subagents/`) | specialized delegated agents | global, project | one `.md` per subagent, or synthetic preamble. Profile-bundled |
|
|
100
100
|
| **Instructions** (`backend/instructions/`) | a shared instruction block | global, project | marker region inside the engine memory file (`CLAUDE.md` / `QWEN.md` / `AGENTS.md`). Global set always synced in full; never profile-bundled |
|
|
101
|
-
| **Permissions** (`backend/permissions/`) | per-engine tool allow/deny | global, project | **enforcement is a runtime
|
|
101
|
+
| **Permissions** (`backend/permissions/`) | per-engine tool allow/deny | global, project | **enforcement is a runtime check** (`resolvePermissionsFromDb` + `isToolAllowed`) each adapter runs at whichever surface fires for every tool call — for Claude a `PreToolUse` hook, since `bypassPermissions` auto-approves before `canUseTool` is consulted. The matrix only describes the optional on-disk file, which today only Claude reads (a managed `permissions` key merged into its isolated `settings.json`); its `deny` rules do bite even under `bypassPermissions`, an allowlist has no on-disk equivalent |
|
|
102
102
|
| **Profiles** (`backend/profiles/`) | a named bundle of slugs | per session | not materialized. Narrows which instance-global artifacts are active: effective profile = `chat_sessions.profile_id ?? projects.default_profile_id`, resolved once at stream start and threaded down as `profileId`. Only constrains the types it references (`artifactFilter` → `null` = unconstrained), so a Commands-only profile never disables every Skill |
|
|
103
103
|
|
|
104
104
|
### 8.5 Connectors (MCP)
|
|
@@ -29,7 +29,7 @@
|
|
|
29
29
|
| Materialize an artifact per engine (matrix) | `backend/artifacts/matrix.ts::resolveArtifact`, generic writer `backend/artifacts/sync.ts`, scanner `backend/artifacts/detect.ts` (see §8.2) |
|
|
30
30
|
| Per-stream artifact sync (Commands/Subagents/Instructions) | `backend/engine/artifact-sync.ts::syncEngineArtifacts` + `buildArtifactsPromptContext` — called from each `stream.ts` after `syncSkills` (see §8.3) |
|
|
31
31
|
| Profile scoping (narrow active artifacts) | `backend/profiles/service.ts::resolveActiveProfileId` + `artifactFilter` (see §8.4) |
|
|
32
|
-
| Permission enforcement (runtime
|
|
32
|
+
| Permission enforcement (runtime check) | `backend/permissions/service.ts::resolvePermissionsFromDb` + `isToolAllowed` (see §8.4); Claude wires it into a `PreToolUse` hook in `claude/stream.ts` |
|
|
33
33
|
| Auth-blob swap into shared CLI dotfile | Pattern only (no implementation yet); see §3.3 callout + §10.13 |
|
|
34
34
|
| Restart-Server pattern (long-lived engines) | `backend/ws/engine/opencode/providers.ts::engine:opencode-server-restart`, `frontend/components/chat/input/components/EngineModelPicker.svelte::restartOCServer`, `engines/panels/OpenCodePanel.svelte::handleRestartServer`/`forceRestartServer` |
|
|
35
35
|
| `generateStructured` (no tools, JSON) | `claude/stream.ts::generateStructured` (native `outputFormat`), `codex/stream.ts::generateStructured` (native `outputSchema`); `opencode` / `copilot` / `qwen` / `pi` / `cline` / `cursor` are prompt-engineered via `backend/engine/structured-helpers.ts` (`buildJsonPrompt` + `extractJson`). See §10.16 for the strict-schema + part-fallback gotchas. |
|
|
@@ -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.
|
|
11
|
-
*
|
|
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',
|