@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.
Files changed (64) hide show
  1. package/backend/auth/permissions.test.ts +0 -1
  2. package/backend/auth/permissions.ts +0 -4
  3. package/backend/chat/stream-manager.ts +28 -12
  4. package/backend/database/migrations/068_create_engine_config_revision.test.ts +121 -0
  5. package/backend/database/migrations/068_create_engine_config_revision.ts +117 -0
  6. package/backend/database/migrations/index.ts +7 -0
  7. package/backend/engine/README.md +16 -0
  8. package/backend/engine/adapters/claude/stream.ts +89 -49
  9. package/backend/engine/adapters/cline/stream.ts +62 -24
  10. package/backend/engine/adapters/codex/stream.ts +51 -21
  11. package/backend/engine/adapters/copilot/stream.ts +96 -52
  12. package/backend/engine/adapters/cursor/stream.ts +74 -34
  13. package/backend/engine/adapters/opencode/server.ts +512 -126
  14. package/backend/engine/adapters/opencode/stream.ts +131 -79
  15. package/backend/engine/adapters/pi/stream.ts +63 -24
  16. package/backend/engine/adapters/qwen/stream.ts +91 -58
  17. package/backend/engine/adapters/run-registry.test.ts +75 -0
  18. package/backend/engine/adapters/run-registry.ts +63 -0
  19. package/backend/engine/bootstrap-default-engine.ts +67 -38
  20. package/backend/engine/config-revision.ts +150 -0
  21. package/backend/engine/docs/adapter-contract.md +40 -9
  22. package/backend/engine/docs/adding-an-engine.md +8 -0
  23. package/backend/engine/docs/frontend-and-chat.md +39 -0
  24. package/backend/engine/docs/lessons-learned.md +70 -0
  25. package/backend/engine/docs/quick-reference.md +3 -1
  26. package/backend/engine/engine-cli.ts +313 -0
  27. package/backend/engine/engine-setup.ts +40 -3
  28. package/backend/engine/hot-reload.ts +99 -0
  29. package/backend/engine/index.ts +96 -24
  30. package/backend/engine/install-recipes.test.ts +99 -5
  31. package/backend/engine/install-recipes.ts +47 -11
  32. package/backend/engine/install-runner.ts +34 -16
  33. package/backend/engine/stack-project.ts +72 -0
  34. package/backend/engine/types.ts +17 -5
  35. package/backend/git/git-executor.ts +22 -3
  36. package/backend/git/git-service.ts +1 -1
  37. package/backend/git/nested-repos.test.ts +121 -0
  38. package/backend/git/nested-repos.ts +301 -0
  39. package/backend/index.ts +7 -0
  40. package/backend/snapshot/gitignore.ts +10 -174
  41. package/backend/utils/path-enrich.ts +2 -0
  42. package/backend/ws/chat/stream.ts +24 -0
  43. package/backend/ws/engine/claude/accounts.ts +9 -4
  44. package/backend/ws/engine/codex/accounts.ts +8 -17
  45. package/backend/ws/engine/codex/status.ts +10 -17
  46. package/backend/ws/engine/copilot/accounts.ts +0 -10
  47. package/backend/ws/engine/cursor/accounts.ts +0 -10
  48. package/backend/ws/engine/index.ts +17 -2
  49. package/backend/ws/engine/opencode/providers.ts +0 -52
  50. package/backend/ws/files/read.ts +1 -1
  51. package/backend/ws/git/conflict.ts +1 -1
  52. package/backend/ws/git/diff.ts +1 -1
  53. package/backend/ws/git/staging.ts +1 -1
  54. package/backend/ws/git/status.ts +1 -1
  55. package/backend/ws/settings/crud.ts +1 -1
  56. package/backend/ws/stack/access.ts +5 -2
  57. package/dist/assets/{index-DYwQ5bP8.js → index-DSvGoxp2.js} +1 -1
  58. package/dist/assets/{index-DUc5T21e.js → index-hu17G6tX.js} +1 -1
  59. package/dist/assets/main-BccclZsC.js +1031 -0
  60. package/dist/assets/{main-VgdjTBLR.css → main-Ciuw0wF0.css} +1 -1
  61. package/dist/index.html +2 -2
  62. package/package.json +1 -1
  63. package/backend/ws/engine/restart.ts +0 -54
  64. package/dist/assets/main-r0iv2PDz.js +0 -1044
@@ -3,9 +3,10 @@
3
3
  *
4
4
  * Wraps `@qwen-code/sdk` into the AIEngine interface. The SDK manages a
5
5
  * `qwen` subprocess per `query()` call (CLI is bundled with the SDK from
6
- * v0.1.1+). We only own the per-project `Query` lifecycle, an
7
- * `AbortController`, and the single-slot `pendingAskUserQuestion` for the
8
- * blocking AskUserQuestion flow.
6
+ * v0.1.1+). We own the `Query` lifecycle, an `AbortController` and the
7
+ * `pendingAskUserQuestion` slot of the blocking AskUserQuestion flow — all of
8
+ * it per RUN, since one instance serves every chat session of a project and
9
+ * several of them can be streaming at the same time.
9
10
  *
10
11
  * Auth: paste-token only. `engine_accounts.credential` stores the
11
12
  * OpenAI-compatible API key; the active account is read on every stream
@@ -46,6 +47,7 @@ import { handleStreamError } from './error-handler';
46
47
  import { createSdkMessageConverter, toSdkUserMessage, type SdkMessageConverter } from './message-converter';
47
48
  import { fetchQwenModels } from './models';
48
49
  import { getQwenMcpConfig } from '../../../mcp';
50
+ import { EngineRuns } from '../run-registry';
49
51
  import { artifactFilter } from '$backend/profiles';
50
52
  import { syncSkills } from '$backend/skills';
51
53
  import { syncEngineArtifacts } from '$backend/engine/artifact-sync';
@@ -65,29 +67,40 @@ interface PendingAskUserQuestion {
65
67
  toolUseId: string | null;
66
68
  }
67
69
 
70
+ /**
71
+ * One stream in flight on this instance. All of it used to be instance fields,
72
+ * which only held the most recently started stream — so a second chat in the
73
+ * same project silently took over the first one's query, converter and parked
74
+ * question, and cancelling either one tore down the wrong stream.
75
+ */
76
+ interface QwenRun {
77
+ /** Identity of the run — the controller the caller passed to streamQuery. */
78
+ controller: AbortController;
79
+ query: Query | null;
80
+ /**
81
+ * Live converter for this run — used by `resolveUserAnswer` to push the
82
+ * user's answers into the converter state so the eventual AUQ tool_result
83
+ * can be rewritten with the actual answers (the Qwen SDK's `canUseTool` →
84
+ * AUQ tool execution path drops `answers` on the floor; see the comment
85
+ * block at the top of `message-converter.ts` and the analysis in
86
+ * `qwen/stream.ts::canUseTool` for AskUserQuestion).
87
+ */
88
+ converter: SdkMessageConverter | null;
89
+ pendingAskUserQuestion: PendingAskUserQuestion | null;
90
+ }
91
+
68
92
  export class QwenEngine implements AIEngine {
69
93
  readonly name = 'qwen' as const;
70
94
 
71
95
  private _isInitialized = false;
72
- private activeController: AbortController | null = null;
73
- private activeQuery: Query | null = null;
74
- private pendingAskUserQuestion: PendingAskUserQuestion | null = null;
75
- /**
76
- * Live converter for the current stream — used by `resolveUserAnswer` to
77
- * push the user's answers into the converter state so the eventual AUQ
78
- * tool_result can be rewritten with the actual answers (the Qwen SDK's
79
- * `canUseTool` → AUQ tool execution path drops `answers` on the floor; see
80
- * the comment block at the top of `message-converter.ts` and the analysis
81
- * in `qwen/stream.ts::canUseTool` for AskUserQuestion).
82
- */
83
- private activeConverter: SdkMessageConverter | null = null;
96
+ private runs = new EngineRuns<QwenRun>();
84
97
 
85
98
  get isInitialized(): boolean {
86
99
  return this._isInitialized;
87
100
  }
88
101
 
89
102
  get isActive(): boolean {
90
- return this.activeController !== null;
103
+ return this.runs.isActive;
91
104
  }
92
105
 
93
106
  async initialize(): Promise<void> {
@@ -97,8 +110,8 @@ export class QwenEngine implements AIEngine {
97
110
  }
98
111
 
99
112
  async dispose(): Promise<void> {
100
- await this.cancel();
101
- this.pendingAskUserQuestion = null;
113
+ // Shutdown/retirement: every run on this instance goes.
114
+ await this.stopRuns(this.runs.all());
102
115
  this._isInitialized = false;
103
116
  }
104
117
 
@@ -139,7 +152,9 @@ export class QwenEngine implements AIEngine {
139
152
  }
140
153
  const { env } = resolution;
141
154
 
142
- this.activeController = abortController || new AbortController();
155
+ const controller = abortController || new AbortController();
156
+ const run: QwenRun = { controller, query: null, converter: null, pendingAskUserQuestion: null };
157
+ this.runs.add(run);
143
158
  const resolvedProjectPath = resolveOsPath(projectPath);
144
159
  // Active Profile for this stream — scopes artifacts + connectors.
145
160
  const profileId = options.mcpContext?.profileId;
@@ -194,7 +209,7 @@ export class QwenEngine implements AIEngine {
194
209
  // "Qwen OAuth free tier was discontinued" even though we've
195
210
  // supplied OPENAI_API_KEY / OPENAI_BASE_URL.
196
211
  authType: 'openai',
197
- abortController: this.activeController,
212
+ abortController: controller,
198
213
  includePartialMessages,
199
214
  stderr: (msg: string) => {
200
215
  const trimmed = msg.replace(/\s+$/, '');
@@ -273,11 +288,11 @@ export class QwenEngine implements AIEngine {
273
288
  // Claude (see claude/stream.ts cancel()). Resolving
274
289
  // would prompt the SDK to write the result to a
275
290
  // subprocess that's about to die.
276
- this.pendingAskUserQuestion = null;
291
+ run.pendingAskUserQuestion = null;
277
292
  };
278
293
  ctx.signal.addEventListener('abort', onAbort, { once: true });
279
294
 
280
- this.pendingAskUserQuestion = {
295
+ run.pendingAskUserQuestion = {
281
296
  resolve: (result) => {
282
297
  ctx.signal.removeEventListener('abort', onAbort);
283
298
  resolve(result);
@@ -308,7 +323,7 @@ export class QwenEngine implements AIEngine {
308
323
 
309
324
  const { query } = await loadEngineSdk<typeof import('@qwen-code/sdk')>('qwen', '@qwen-code/sdk');
310
325
  const queryInstance = query({ prompt: promptIterable, options: sdkOptions });
311
- this.activeQuery = queryInstance;
326
+ run.query = queryInstance;
312
327
 
313
328
  const converter = createSdkMessageConverter(modelId, {
314
329
  onAskUserQuestionEmitted: (toolUseId: string) => {
@@ -317,55 +332,68 @@ export class QwenEngine implements AIEngine {
317
332
  // the pending slot here unblocks `resolveUserAnswer` even
318
333
  // when the frontend gets the toolUseId before our slot was
319
334
  // populated (rare but possible if the SDK queues events).
320
- if (this.pendingAskUserQuestion && this.pendingAskUserQuestion.toolUseId === null) {
321
- this.pendingAskUserQuestion.toolUseId = toolUseId;
335
+ if (run.pendingAskUserQuestion && run.pendingAskUserQuestion.toolUseId === null) {
336
+ run.pendingAskUserQuestion.toolUseId = toolUseId;
322
337
  }
323
338
  },
324
339
  });
325
- this.activeConverter = converter;
340
+ run.converter = converter;
326
341
  for await (const sdkMessage of queryInstance) {
327
342
  yield* converter.convert(sdkMessage);
328
343
  }
329
344
  } catch (error) {
330
345
  handleStreamError(error, stderrLines.join('\n'));
331
346
  } finally {
332
- this.activeController = null;
333
- this.activeQuery = null;
334
- this.activeConverter = null;
347
+ // Retire THIS run only — another chat session of the same project may
348
+ // still be streaming on this instance.
349
+ this.runs.remove(run);
335
350
  }
336
351
  }
337
352
 
338
- async cancel(): Promise<void> {
339
- // Drop the pending AskUserQuestion handler — same pattern as Claude
340
- // (don't resolve, just abandon, otherwise the SDK tries to write to
341
- // a subprocess that's about to die).
342
- if (this.pendingAskUserQuestion) {
343
- this.pendingAskUserQuestion.removeAbortListener();
344
- this.pendingAskUserQuestion = null;
345
- }
353
+ /**
354
+ * Cancel the run whose AbortController is `owner`, and only that run.
355
+ */
356
+ async cancel(owner: AbortController): Promise<void> {
357
+ await this.stopRuns(this.runs.select(owner));
358
+ }
359
+
360
+ /**
361
+ * Tear down the given runs. `cancel` passes the one run it was asked to
362
+ * stop; `dispose` passes them all. Nothing else may reach this.
363
+ */
364
+ private async stopRuns(targets: QwenRun[]): Promise<void> {
365
+ for (const run of targets) {
366
+ // Drop this run's pending AskUserQuestion handler — same pattern as
367
+ // Claude (don't resolve, just abandon, otherwise the SDK tries to write
368
+ // to a subprocess that's about to die). Another run's parked question
369
+ // is left alone; its subprocess is still alive and still waiting.
370
+ if (run.pendingAskUserQuestion) {
371
+ run.pendingAskUserQuestion.removeAbortListener();
372
+ run.pendingAskUserQuestion = null;
373
+ }
346
374
 
347
- if (this.activeQuery && typeof this.activeQuery.close === 'function') {
348
- try {
349
- await this.activeQuery.close();
350
- } catch {
351
- /* subprocess may already be dead */
375
+ if (run.query && typeof run.query.close === 'function') {
376
+ try {
377
+ await run.query.close();
378
+ } catch {
379
+ /* subprocess may already be dead */
380
+ }
352
381
  }
353
- }
354
382
 
355
- if (this.activeController && !this.activeController.signal.aborted) {
356
- this.activeController.abort();
383
+ if (!run.controller.signal.aborted) run.controller.abort();
384
+ this.runs.remove(run);
357
385
  }
358
- this.activeController = null;
359
- this.activeQuery = null;
360
- this.activeConverter = null;
361
386
  }
362
387
 
363
- async interrupt(): Promise<void> {
364
- if (this.activeQuery && typeof this.activeQuery.interrupt === 'function') {
365
- try {
366
- await this.activeQuery.interrupt();
367
- } catch {
368
- /* fall through to cancel */
388
+ async interrupt(owner: AbortController): Promise<void> {
389
+ const targets = this.runs.select(owner);
390
+ for (const run of targets) {
391
+ if (run.query && typeof run.query.interrupt === 'function') {
392
+ try {
393
+ await run.query.interrupt();
394
+ } catch {
395
+ /* fall through to cancel */
396
+ }
369
397
  }
370
398
  }
371
399
  }
@@ -453,8 +481,13 @@ export class QwenEngine implements AIEngine {
453
481
  }
454
482
 
455
483
  resolveUserAnswer(toolUseId: string, answers: Record<string, string>): boolean {
456
- const pending = this.pendingAskUserQuestion;
457
- if (!pending) {
484
+ // Find the run that parked this question: the one that already recorded
485
+ // this toolUseId, else the one still waiting for its id to arrive.
486
+ const running = this.runs.all();
487
+ const run = running.find(r => r.pendingAskUserQuestion?.toolUseId === toolUseId)
488
+ ?? running.find(r => r.pendingAskUserQuestion && r.pendingAskUserQuestion.toolUseId === null);
489
+ const pending = run?.pendingAskUserQuestion ?? null;
490
+ if (!run || !pending) {
458
491
  debug.warn('engine', 'Qwen resolveUserAnswer: no pending question');
459
492
  return false;
460
493
  }
@@ -474,13 +507,13 @@ export class QwenEngine implements AIEngine {
474
507
  // tool_result body is `"User has provided the following answers:\n\n"`
475
508
  // (empty). The converter intercepts that tool_result and replaces its
476
509
  // content with the proper formatted answers we just stored.
477
- this.activeConverter?.recordUserAnswer(toolUseId, answers);
510
+ run.converter?.recordUserAnswer(toolUseId, answers);
478
511
 
479
512
  pending.resolve({
480
513
  behavior: 'allow',
481
514
  updatedInput: { ...pending.input, answers },
482
515
  });
483
- this.pendingAskUserQuestion = null;
516
+ run.pendingAskUserQuestion = null;
484
517
  return true;
485
518
  }
486
519
  }
@@ -0,0 +1,75 @@
1
+ import { describe, expect, test } from 'bun:test';
2
+
3
+ import { EngineRuns } from './run-registry';
4
+
5
+ // One engine instance serves every chat session of a project, so a cancel has to
6
+ // name the stream it means. These cases are the difference between "Stop this
7
+ // chat" and "Stop whatever this engine happens to be doing" — the second one
8
+ // interrupted a different chat mid-answer.
9
+
10
+ interface Run {
11
+ controller: AbortController;
12
+ label: string;
13
+ }
14
+
15
+ function registry(...labels: string[]) {
16
+ const runs = new EngineRuns<Run>();
17
+ const byLabel: Record<string, Run> = {};
18
+ for (const label of labels) {
19
+ byLabel[label] = runs.add({ controller: new AbortController(), label });
20
+ }
21
+ return { runs, byLabel };
22
+ }
23
+
24
+ describe('EngineRuns', () => {
25
+ test('an owner selects its own run and leaves the others alone', () => {
26
+ const { runs, byLabel } = registry('a', 'b');
27
+
28
+ expect(runs.select(byLabel.a.controller).map(r => r.label)).toEqual(['a']);
29
+ expect(runs.select(byLabel.b.controller).map(r => r.label)).toEqual(['b']);
30
+ });
31
+
32
+ test('an owner that already finished selects nothing', () => {
33
+ const { runs, byLabel } = registry('a', 'b');
34
+ runs.remove(byLabel.a);
35
+
36
+ // The tempting fallback — "target not found, so stop what's left" — is
37
+ // exactly the bug: it would take down 'b', a chat the user never stopped.
38
+ expect(runs.select(byLabel.a.controller)).toEqual([]);
39
+ });
40
+
41
+ test('all() returns every run, for dispose and shutdown', () => {
42
+ const { runs } = registry('a', 'b');
43
+
44
+ expect(runs.all().map(r => r.label).sort()).toEqual(['a', 'b']);
45
+ });
46
+
47
+ test('isActive stays true until the LAST run ends', () => {
48
+ const { runs, byLabel } = registry('a', 'b');
49
+
50
+ expect(runs.isActive).toBe(true);
51
+ runs.remove(byLabel.a);
52
+ // An engine retired mid-stream is disposed once it goes idle. Reporting
53
+ // idle here would dispose it out from under 'b'.
54
+ expect(runs.isActive).toBe(true);
55
+ runs.remove(byLabel.b);
56
+ expect(runs.isActive).toBe(false);
57
+ });
58
+
59
+ test('removing a run twice is not an error', () => {
60
+ const { runs, byLabel } = registry('a');
61
+
62
+ // cancel() and the stream's own `finally` both retire the run.
63
+ runs.remove(byLabel.a);
64
+ runs.remove(byLabel.a);
65
+ expect(runs.isActive).toBe(false);
66
+ });
67
+
68
+ test('an empty registry is not an error', () => {
69
+ const runs = new EngineRuns<Run>();
70
+
71
+ expect(runs.all()).toEqual([]);
72
+ expect(runs.select(new AbortController())).toEqual([]);
73
+ expect(runs.isActive).toBe(false);
74
+ });
75
+ });
@@ -0,0 +1,63 @@
1
+ /**
2
+ * The runs an engine instance is currently serving.
3
+ *
4
+ * One instance is shared by every chat session of a project (see
5
+ * `getProjectEngine`), so at any moment it can be streaming several chats at
6
+ * once. Everything a single stream owns — its abort controller, its SDK query
7
+ * or session, its pooled server, its parked questions — therefore belongs to a
8
+ * RUN and not to the instance. An instance field holds only the most recently
9
+ * started stream, which is how "Stop this chat" came to abort a different chat
10
+ * of the same project.
11
+ *
12
+ * A run is identified by the AbortController its caller passed to
13
+ * `streamQuery`. That is the same object `StreamState.abortController` holds,
14
+ * so it is the one handle the stream-manager and the adapter already agree on —
15
+ * no ids to mint, no bookkeeping to keep in sync.
16
+ *
17
+ * Adapters own the SHAPE of a run (each SDK exposes different handles) and this
18
+ * class owns the BOOKKEEPING, so the targeting rules live in one place instead
19
+ * of eight.
20
+ */
21
+
22
+ /** The one field every adapter's run state must expose: its own controller. */
23
+ export interface EngineRun {
24
+ controller: AbortController;
25
+ }
26
+
27
+ export class EngineRuns<T extends EngineRun> {
28
+ private byController = new Map<AbortController, T>();
29
+
30
+ /** True while at least ONE run is in flight — the answer `AIEngine.isActive` owes its callers. */
31
+ get isActive(): boolean {
32
+ return this.byController.size > 0;
33
+ }
34
+
35
+ /** Register a run for the duration of one `streamQuery` call. */
36
+ add(run: T): T {
37
+ this.byController.set(run.controller, run);
38
+ return run;
39
+ }
40
+
41
+ /** Unregister a finished run. Idempotent — cancel and the stream's own `finally` both call it. */
42
+ remove(run: T): void {
43
+ this.byController.delete(run.controller);
44
+ }
45
+
46
+ /**
47
+ * The run a targeted `cancel` / `interrupt` applies to.
48
+ *
49
+ * An owner that has already finished selects NOTHING. Falling back to "the
50
+ * runs that are left" is what made Stop in one chat kill another chat of the
51
+ * same project: the caller named a stream that had ended, and the engine
52
+ * helpfully tore down whichever one it still had.
53
+ */
54
+ select(owner: AbortController): T[] {
55
+ const run = this.byController.get(owner);
56
+ return run ? [run] : [];
57
+ }
58
+
59
+ /** Every run — for `dispose()` and shutdown, the only places that may stop them all. */
60
+ all(): T[] {
61
+ return [...this.byController.values()];
62
+ }
63
+ }
@@ -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
  }