@myrialabs/clopen 0.4.30 → 0.4.32
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/auth/permissions.test.ts +0 -1
- package/backend/auth/permissions.ts +0 -4
- package/backend/chat/stream-manager.ts +28 -12
- package/backend/database/migrations/068_create_engine_config_revision.test.ts +121 -0
- package/backend/database/migrations/068_create_engine_config_revision.ts +117 -0
- package/backend/database/migrations/index.ts +7 -0
- package/backend/engine/README.md +16 -0
- package/backend/engine/adapters/claude/stream.ts +89 -49
- package/backend/engine/adapters/cline/stream.ts +62 -24
- package/backend/engine/adapters/codex/stream.ts +51 -21
- package/backend/engine/adapters/copilot/stream.ts +96 -52
- package/backend/engine/adapters/cursor/stream.ts +74 -34
- package/backend/engine/adapters/opencode/server.ts +512 -126
- package/backend/engine/adapters/opencode/stream.ts +131 -79
- package/backend/engine/adapters/pi/stream.ts +63 -24
- package/backend/engine/adapters/qwen/stream.ts +91 -58
- package/backend/engine/adapters/run-registry.test.ts +75 -0
- package/backend/engine/adapters/run-registry.ts +63 -0
- package/backend/engine/bootstrap-default-engine.ts +67 -38
- package/backend/engine/config-revision.ts +150 -0
- package/backend/engine/docs/adapter-contract.md +40 -9
- package/backend/engine/docs/adding-an-engine.md +8 -0
- package/backend/engine/docs/frontend-and-chat.md +39 -0
- package/backend/engine/docs/lessons-learned.md +70 -0
- package/backend/engine/docs/quick-reference.md +3 -1
- package/backend/engine/engine-cli.ts +313 -0
- package/backend/engine/engine-setup.ts +40 -3
- package/backend/engine/hot-reload.ts +99 -0
- package/backend/engine/index.ts +96 -24
- 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/engine/types.ts +17 -5
- package/backend/git/git-executor.ts +22 -3
- package/backend/git/git-service.ts +1 -1
- package/backend/git/nested-repos.test.ts +121 -0
- package/backend/git/nested-repos.ts +301 -0
- package/backend/index.ts +7 -0
- package/backend/snapshot/gitignore.ts +10 -174
- package/backend/utils/path-enrich.ts +2 -0
- package/backend/ws/chat/stream.ts +24 -0
- package/backend/ws/engine/claude/accounts.ts +9 -4
- package/backend/ws/engine/codex/accounts.ts +8 -17
- package/backend/ws/engine/codex/status.ts +10 -17
- package/backend/ws/engine/copilot/accounts.ts +0 -10
- package/backend/ws/engine/cursor/accounts.ts +0 -10
- package/backend/ws/engine/index.ts +17 -2
- package/backend/ws/engine/opencode/providers.ts +0 -52
- package/backend/ws/files/read.ts +1 -1
- package/backend/ws/git/conflict.ts +1 -1
- package/backend/ws/git/diff.ts +1 -1
- package/backend/ws/git/staging.ts +1 -1
- package/backend/ws/git/status.ts +1 -1
- package/backend/ws/settings/crud.ts +1 -1
- package/backend/ws/stack/access.ts +5 -2
- package/dist/assets/{index-DYwQ5bP8.js → index-DSvGoxp2.js} +1 -1
- package/dist/assets/{index-DUc5T21e.js → index-hu17G6tX.js} +1 -1
- package/dist/assets/main-BccclZsC.js +1031 -0
- package/dist/assets/{main-VgdjTBLR.css → main-Ciuw0wF0.css} +1 -1
- package/dist/index.html +2 -2
- package/package.json +1 -1
- package/backend/ws/engine/restart.ts +0 -54
- package/dist/assets/main-r0iv2PDz.js +0 -1044
|
@@ -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',
|
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Applying engine config changes without anyone pressing anything.
|
|
3
|
+
*
|
|
4
|
+
* This is the piece that replaced the "Restart Server" button. The button asked
|
|
5
|
+
* the user to understand something they should never have had to: that Open Code
|
|
6
|
+
* runs as a process which froze its configuration at boot, and that their edit
|
|
7
|
+
* would quietly do nothing until they told the server to start again. Worse, the
|
|
8
|
+
* button's only implementation was destructive — it aborted every running chat,
|
|
9
|
+
* which is why it had to ask for confirmation, which is why new users learned to
|
|
10
|
+
* be afraid of it.
|
|
11
|
+
*
|
|
12
|
+
* What happens instead, driven entirely by the config revision:
|
|
13
|
+
*
|
|
14
|
+
* nothing is streaming → a replacement server is spawned and health-checked
|
|
15
|
+
* NOW, and only once it is up does the old one go. The
|
|
16
|
+
* user's next message costs nothing.
|
|
17
|
+
*
|
|
18
|
+
* something is streaming → nothing is touched. The running turn finishes under
|
|
19
|
+
* the config it started with; the next stream resolves
|
|
20
|
+
* the new config on its own and binds to a new server,
|
|
21
|
+
* and the old one is reaped when its last stream lets
|
|
22
|
+
* go of it.
|
|
23
|
+
*
|
|
24
|
+
* Both cases are the same mechanism — the pool keys servers by a hash of the
|
|
25
|
+
* config they were spawned with — so this module only decides WHEN to pay the
|
|
26
|
+
* spawn cost, never whether the right config is used. That part cannot be got
|
|
27
|
+
* wrong by anything here.
|
|
28
|
+
*/
|
|
29
|
+
|
|
30
|
+
import { streamManager } from '../chat';
|
|
31
|
+
import { onEngineConfigChanged } from './config-revision';
|
|
32
|
+
import { retireAllEngines } from './index';
|
|
33
|
+
import {
|
|
34
|
+
acquireServer,
|
|
35
|
+
pooledScopeKeys,
|
|
36
|
+
reconcileServerHolders,
|
|
37
|
+
DEFAULT_SCOPE_KEY,
|
|
38
|
+
} from './adapters/opencode/server';
|
|
39
|
+
import { debug } from '$shared/utils/logger';
|
|
40
|
+
|
|
41
|
+
let started = false;
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* Re-warm the Open Code pool for the scopes that are actually in use.
|
|
45
|
+
*
|
|
46
|
+
* Only the default (no-Profile) scope can be warmed blind: a Profile scope's
|
|
47
|
+
* spec is built from that Profile's connector and subagent set at stream start,
|
|
48
|
+
* and reconstructing it here would duplicate that resolution. Profile servers
|
|
49
|
+
* therefore respawn lazily on their next stream, which is the correct trade —
|
|
50
|
+
* they are the rarer case, and the cost is one spawn on a turn that was going to
|
|
51
|
+
* talk to a server anyway.
|
|
52
|
+
*/
|
|
53
|
+
async function warmDefaultScope(): Promise<void> {
|
|
54
|
+
if (!pooledScopeKeys().includes(DEFAULT_SCOPE_KEY)) return;
|
|
55
|
+
try {
|
|
56
|
+
await acquireServer({});
|
|
57
|
+
debug.log('engine', 'Open Code default server re-warmed for the new config');
|
|
58
|
+
} catch (error) {
|
|
59
|
+
// Deliberately silent to the user. A config that cannot start is a real
|
|
60
|
+
// problem, but the honest place to report it is the turn that needs it —
|
|
61
|
+
// where the error is actionable and in context — not a background toast
|
|
62
|
+
// about a server the user was never told about.
|
|
63
|
+
debug.warn('engine', 'Open Code warm-up failed; keeping the current server until a turn needs the new config', error);
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* Start reacting to engine config changes. Idempotent.
|
|
69
|
+
*/
|
|
70
|
+
export function startEngineHotReload(): void {
|
|
71
|
+
if (started) return;
|
|
72
|
+
started = true;
|
|
73
|
+
|
|
74
|
+
onEngineConfigChanged(revision => {
|
|
75
|
+
// Holder bookkeeping is reconciled against the live stream set first, so
|
|
76
|
+
// "is anything running" and "is this server still needed" are answered from
|
|
77
|
+
// the same source of truth rather than from two drifting counters.
|
|
78
|
+
const liveStreams = streamManager.getActiveStreams();
|
|
79
|
+
reconcileServerHolders(new Set(liveStreams.map(s => s.streamId)));
|
|
80
|
+
|
|
81
|
+
// Engines other than Open Code hold no baked config, but they DO cache
|
|
82
|
+
// credentialed clients. Retiring evicts those without touching a stream
|
|
83
|
+
// that is mid-answer.
|
|
84
|
+
retireAllEngines();
|
|
85
|
+
|
|
86
|
+
if (liveStreams.length > 0) {
|
|
87
|
+
debug.log(
|
|
88
|
+
'engine',
|
|
89
|
+
`Engine config now at revision ${revision}; ${liveStreams.length} stream(s) in flight — ` +
|
|
90
|
+
'applying it to the next turn and draining the old server behind them'
|
|
91
|
+
);
|
|
92
|
+
return;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
void warmDefaultScope();
|
|
96
|
+
});
|
|
97
|
+
|
|
98
|
+
debug.log('engine', 'Engine hot-reload active');
|
|
99
|
+
}
|
package/backend/engine/index.ts
CHANGED
|
@@ -8,10 +8,16 @@
|
|
|
8
8
|
* Used for non-streaming operations like models:list, settings, etc.
|
|
9
9
|
*
|
|
10
10
|
* - Per-project instances (getProjectEngine / initializeProjectEngine):
|
|
11
|
-
* Used by stream-manager for chat streaming.
|
|
12
|
-
*
|
|
13
|
-
*
|
|
14
|
-
*
|
|
11
|
+
* Used by stream-manager for chat streaming. Cancelling Project A's stream
|
|
12
|
+
* never affects Project B.
|
|
13
|
+
*
|
|
14
|
+
* Per project, NOT per chat session: every chat session of a project shares
|
|
15
|
+
* one instance, and several of them stream at once. Isolation between those
|
|
16
|
+
* streams is the adapter's job, not this cache's — each keeps its per-stream
|
|
17
|
+
* state in an `EngineRuns` registry (backend/engine/adapters/run-registry.ts)
|
|
18
|
+
* and `cancel(owner)` stops exactly the run it was handed. Adding per-stream
|
|
19
|
+
* state to an adapter INSTANCE reintroduces "Stop this chat" stopping a
|
|
20
|
+
* different one.
|
|
15
21
|
*
|
|
16
22
|
* Adapters are loaded on first use, never at boot. This registry used to import
|
|
17
23
|
* all eight statically, which coupled every user's startup to every adapter: one
|
|
@@ -133,6 +139,84 @@ export async function disposeEngine(type: EngineType): Promise<void> {
|
|
|
133
139
|
}
|
|
134
140
|
}
|
|
135
141
|
|
|
142
|
+
// ============================================================================
|
|
143
|
+
// Retirement — replacing an engine without killing what it is doing
|
|
144
|
+
// ============================================================================
|
|
145
|
+
|
|
146
|
+
/**
|
|
147
|
+
* Engines removed from a cache but still mid-stream, awaiting a quiet moment.
|
|
148
|
+
*
|
|
149
|
+
* Disposing an engine tears down its SDK process and aborts whatever query it is
|
|
150
|
+
* running. That is right at shutdown and wrong everywhere else: switching a
|
|
151
|
+
* Copilot account or editing a connector used to call `dispose()` immediately,
|
|
152
|
+
* which killed any chat that happened to be streaming at that moment — silently,
|
|
153
|
+
* from the user's point of view, since nothing in the UI connects "I changed a
|
|
154
|
+
* setting" to "that answer stopped halfway".
|
|
155
|
+
*
|
|
156
|
+
* Retiring instead evicts the instance from the cache so the next stream builds a
|
|
157
|
+
* fresh one, and disposes the old one once it goes idle. New work gets the new
|
|
158
|
+
* config; work already in flight finishes under the config it started with.
|
|
159
|
+
*/
|
|
160
|
+
const retired = new Set<AIEngine>();
|
|
161
|
+
/** How often retired instances are re-checked for idleness. */
|
|
162
|
+
const RETIRE_POLL_MS = 2000;
|
|
163
|
+
let retireTimer: ReturnType<typeof setInterval> | null = null;
|
|
164
|
+
|
|
165
|
+
function disposeWhenIdle(engine: AIEngine, label: string): void {
|
|
166
|
+
if (!engine.isActive) {
|
|
167
|
+
void engine.dispose().catch(error => debug.error('engine', `Error disposing ${label}:`, error));
|
|
168
|
+
debug.log('engine', `Engine disposed: ${label}`);
|
|
169
|
+
return;
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
retired.add(engine);
|
|
173
|
+
debug.log('engine', `Engine retired while busy, will dispose when idle: ${label}`);
|
|
174
|
+
if (retireTimer) return;
|
|
175
|
+
|
|
176
|
+
retireTimer = setInterval(() => {
|
|
177
|
+
for (const candidate of [...retired]) {
|
|
178
|
+
if (candidate.isActive) continue;
|
|
179
|
+
retired.delete(candidate);
|
|
180
|
+
void candidate.dispose().catch(error => debug.error('engine', 'Error disposing retired engine:', error));
|
|
181
|
+
debug.log('engine', `Retired engine disposed after going idle: ${candidate.name}`);
|
|
182
|
+
}
|
|
183
|
+
if (retired.size === 0 && retireTimer) {
|
|
184
|
+
clearInterval(retireTimer);
|
|
185
|
+
retireTimer = null;
|
|
186
|
+
}
|
|
187
|
+
}, RETIRE_POLL_MS);
|
|
188
|
+
retireTimer.unref?.();
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
/**
|
|
192
|
+
* Evict every instance of an engine type — global and per-project — so the next
|
|
193
|
+
* stream rebuilds it, without interrupting any stream currently using one.
|
|
194
|
+
*
|
|
195
|
+
* This is what account switches, credential edits and config changes call.
|
|
196
|
+
*/
|
|
197
|
+
export function retireEnginesByType(type: EngineType): void {
|
|
198
|
+
const slot = engines.get(type);
|
|
199
|
+
if (slot) {
|
|
200
|
+
engines.delete(type);
|
|
201
|
+
if (slot.instance) disposeWhenIdle(slot.instance, `global ${type}`);
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
for (const [projectId, projectMap] of projectEngines) {
|
|
205
|
+
const projectSlot = projectMap.get(type);
|
|
206
|
+
if (!projectSlot) continue;
|
|
207
|
+
projectMap.delete(type);
|
|
208
|
+
if (projectSlot.instance) disposeWhenIdle(projectSlot.instance, `${type} for project ${projectId.slice(0, 8)}`);
|
|
209
|
+
if (projectMap.size === 0) projectEngines.delete(projectId);
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
/** Evict every engine of every type, letting in-flight streams finish. */
|
|
214
|
+
export function retireAllEngines(): void {
|
|
215
|
+
for (const type of new Set<EngineType>([...engines.keys(), ...[...projectEngines.values()].flatMap(m => [...m.keys()])])) {
|
|
216
|
+
retireEnginesByType(type);
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
|
|
136
220
|
/**
|
|
137
221
|
* Dispose all global engines (used on server shutdown).
|
|
138
222
|
*/
|
|
@@ -160,8 +244,10 @@ const projectEngines = new Map<string, Map<EngineType, EngineSlot>>();
|
|
|
160
244
|
|
|
161
245
|
/**
|
|
162
246
|
* Get (or create) an engine instance scoped to a specific project.
|
|
163
|
-
*
|
|
164
|
-
*
|
|
247
|
+
*
|
|
248
|
+
* Scoped per project, so one project's streams never reach another's. Within a
|
|
249
|
+
* project the instance is SHARED by every chat session — see the note at the
|
|
250
|
+
* top of this file for what that means for adapters.
|
|
165
251
|
*/
|
|
166
252
|
export async function getProjectEngine(projectId: string, type: EngineType): Promise<AIEngine> {
|
|
167
253
|
let engines = projectEngines.get(projectId);
|
|
@@ -241,26 +327,12 @@ export async function disposeProjectEngines(projectId: string): Promise<void> {
|
|
|
241
327
|
* Dispose all instances of a given engine type across all projects, plus the
|
|
242
328
|
* global singleton. Call when an account/credential change requires every
|
|
243
329
|
* client to re-initialise (e.g. Copilot account switch).
|
|
330
|
+
*
|
|
331
|
+
* Retires rather than tears down — see `retireEnginesByType`. Kept async so the
|
|
332
|
+
* many `await`ing call sites read unchanged.
|
|
244
333
|
*/
|
|
245
334
|
export async function disposeAllProjectEnginesByType(type: EngineType): Promise<void> {
|
|
246
|
-
|
|
247
|
-
const slot = engines.get(type);
|
|
248
|
-
if (slot) {
|
|
249
|
-
engines.delete(type);
|
|
250
|
-
try {
|
|
251
|
-
if (slot.instance) await slot.instance.dispose();
|
|
252
|
-
debug.log('engine', `Project engine disposed: ${type} for project ${projectId.slice(0, 8)}`);
|
|
253
|
-
} catch (error) {
|
|
254
|
-
debug.error('engine', `Error disposing project engine ${type} for ${projectId.slice(0, 8)}:`, error);
|
|
255
|
-
}
|
|
256
|
-
}
|
|
257
|
-
if (engines.size === 0) {
|
|
258
|
-
projectEngines.delete(projectId);
|
|
259
|
-
}
|
|
260
|
-
}
|
|
261
|
-
|
|
262
|
-
// Also drop the global singleton so the next non-streaming op rebuilds it.
|
|
263
|
-
await disposeEngine(type);
|
|
335
|
+
retireEnginesByType(type);
|
|
264
336
|
}
|
|
265
337
|
|
|
266
338
|
/**
|