@myrialabs/clopen 0.4.31 → 0.4.33

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 (114) 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 +31 -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/069_create_ssh_client_tables.ts +116 -0
  7. package/backend/database/migrations/index.ts +14 -0
  8. package/backend/database/queries/db-client-connection-queries.ts +7 -2
  9. package/backend/database/queries/file-audit-log-queries.ts +1 -0
  10. package/backend/database/queries/index.ts +3 -0
  11. package/backend/database/queries/ssh-connection-queries.ts +244 -0
  12. package/backend/database/queries/ssh-known-host-queries.ts +67 -0
  13. package/backend/database/queries/ssh-port-forward-queries.ts +113 -0
  14. package/backend/db-client/connection-manager.ts +8 -1
  15. package/backend/engine/README.md +16 -0
  16. package/backend/engine/adapters/claude/stream.ts +89 -49
  17. package/backend/engine/adapters/cline/stream.ts +62 -24
  18. package/backend/engine/adapters/codex/message-converter.ts +18 -12
  19. package/backend/engine/adapters/codex/patch-rollout.test.ts +88 -0
  20. package/backend/engine/adapters/codex/patch-rollout.ts +120 -109
  21. package/backend/engine/adapters/codex/stream.ts +78 -22
  22. package/backend/engine/adapters/copilot/stream.ts +97 -53
  23. package/backend/engine/adapters/cursor/stream.ts +75 -35
  24. package/backend/engine/adapters/opencode/server.ts +511 -134
  25. package/backend/engine/adapters/opencode/stream.ts +131 -79
  26. package/backend/engine/adapters/pi/stream.ts +63 -24
  27. package/backend/engine/adapters/qwen/stream.ts +92 -59
  28. package/backend/engine/adapters/run-registry.test.ts +75 -0
  29. package/backend/engine/adapters/run-registry.ts +63 -0
  30. package/backend/engine/config-revision.ts +150 -0
  31. package/backend/engine/docs/adapter-contract.md +47 -9
  32. package/backend/engine/docs/adding-an-engine.md +8 -0
  33. package/backend/engine/docs/frontend-and-chat.md +39 -0
  34. package/backend/engine/docs/lessons-learned.md +70 -0
  35. package/backend/engine/docs/quick-reference.md +3 -1
  36. package/backend/engine/hot-reload.ts +99 -0
  37. package/backend/engine/index.ts +96 -24
  38. package/backend/engine/types.ts +17 -5
  39. package/backend/files/file-watcher.ts +283 -51
  40. package/backend/files/git-events.test.ts +110 -0
  41. package/backend/git/git-dirs.test.ts +132 -0
  42. package/backend/git/git-dirs.ts +0 -0
  43. package/backend/git/git-executor.ts +22 -3
  44. package/backend/git/git-service.ts +1 -1
  45. package/backend/git/nested-repos.test.ts +224 -0
  46. package/backend/git/nested-repos.ts +386 -0
  47. package/backend/http/audio.ts +5 -32
  48. package/backend/http/bearer-auth.ts +47 -0
  49. package/backend/http/files-download.test.ts +146 -0
  50. package/backend/http/files-download.ts +109 -0
  51. package/backend/http/files-upload.ts +3 -29
  52. package/backend/http/ssh-sftp.ts +133 -0
  53. package/backend/index.ts +23 -2
  54. package/backend/mcp/README.md +34 -6
  55. package/backend/mcp/index.ts +8 -8
  56. package/backend/mcp/internal/config.ts +69 -19
  57. package/backend/mcp/internal/project-context.test.ts +40 -0
  58. package/backend/mcp/internal/project-context.ts +80 -7
  59. package/backend/mcp/internal/remote-server.test.ts +17 -2
  60. package/backend/mcp/internal/remote-server.ts +36 -3
  61. package/backend/mcp/internal/servers/helper.ts +48 -18
  62. package/backend/preview/browser/browser-video-capture.ts +51 -4
  63. package/backend/snapshot/gitignore.ts +10 -174
  64. package/backend/ssh/client-pool.ts +196 -0
  65. package/backend/ssh/connect.ts +375 -0
  66. package/backend/ssh/disk-usage.test.ts +134 -0
  67. package/backend/ssh/disk-usage.ts +214 -0
  68. package/backend/ssh/forwards.ts +309 -0
  69. package/backend/ssh/health.ts +141 -0
  70. package/backend/ssh/known-hosts.ts +96 -0
  71. package/backend/ssh/pty-backend.ts +215 -0
  72. package/backend/ssh/ptykit.ts +66 -0
  73. package/backend/ssh/sftp.test.ts +242 -0
  74. package/backend/ssh/sftp.ts +967 -0
  75. package/backend/ssh/socks5.test.ts +167 -0
  76. package/backend/ssh/socks5.ts +164 -0
  77. package/backend/ssh/tunnel.ts +87 -0
  78. package/backend/ws/chat/stream.ts +24 -0
  79. package/backend/ws/db-client/connections.ts +1 -0
  80. package/backend/ws/engine/codex/accounts.ts +0 -12
  81. package/backend/ws/engine/copilot/accounts.ts +0 -10
  82. package/backend/ws/engine/cursor/accounts.ts +0 -10
  83. package/backend/ws/engine/index.ts +17 -2
  84. package/backend/ws/engine/opencode/providers.ts +0 -52
  85. package/backend/ws/files/read.ts +1 -1
  86. package/backend/ws/files/watch.ts +5 -1
  87. package/backend/ws/git/conflict.ts +1 -1
  88. package/backend/ws/git/diff.ts +1 -1
  89. package/backend/ws/git/staging.ts +1 -1
  90. package/backend/ws/git/status.ts +1 -1
  91. package/backend/ws/index.ts +4 -0
  92. package/backend/ws/ssh/access.ts +31 -0
  93. package/backend/ws/ssh/connections.ts +224 -0
  94. package/backend/ws/ssh/forwards.ts +109 -0
  95. package/backend/ws/ssh/index.ts +18 -0
  96. package/backend/ws/ssh/sftp.ts +259 -0
  97. package/backend/ws/ssh/tunnel.ts +93 -0
  98. package/dist/assets/{index-DYwQ5bP8.js → index-BF4buYmI.js} +1 -1
  99. package/dist/assets/{index-DUc5T21e.js → index-BW0DA8NV.js} +1 -1
  100. package/dist/assets/main-BbwWLJRN.js +1057 -0
  101. package/dist/assets/main-CCvRMXlP.css +1 -0
  102. package/dist/index.html +2 -2
  103. package/package.json +1 -1
  104. package/shared/types/database/schema.ts +49 -0
  105. package/shared/types/db-client/connection.ts +6 -0
  106. package/shared/types/ssh/connection.ts +80 -0
  107. package/shared/types/ssh/forward.ts +46 -0
  108. package/shared/types/ssh/index.ts +8 -0
  109. package/shared/types/ssh/known-host.ts +19 -0
  110. package/shared/types/ssh/sftp.ts +141 -0
  111. package/shared/utils/logger.ts +1 -0
  112. package/backend/ws/engine/restart.ts +0 -54
  113. package/dist/assets/main-VgdjTBLR.css +0 -1
  114. package/dist/assets/main-r0iv2PDz.js +0 -1044
@@ -2,26 +2,55 @@
2
2
  * Open Code Server & Client Pool
3
3
  *
4
4
  * Open Code runs as a persistent `opencode serve` child process that bakes its
5
- * MCP set and agent registry at boot. A single shared server therefore CANNOT
6
- * express a per-session Profile (excluded connectors/subagents leak, and the
7
- * registry is served stale). So instead of one server we keep a POOL keyed by a
8
- * config SIGNATURE — the Profile's filtered MCP set + inline agent set — and
9
- * route each stream to the server matching its Profile. Two sessions on the same
10
- * Profile share a server; different Profiles get isolated servers, concurrently.
5
+ * MCP set, provider list and agent registry at boot. Nothing it reads at start-up
6
+ * can be changed in place, so the pool keeps one server per CONFIG SIGNATURE and
7
+ * routes each stream to the server matching the config it needs.
11
8
  *
12
- * Strategy per key:
13
- * 1. Reuse the pooled server if it is still alive.
14
- * 2. Otherwise spawn `opencode serve` (port 0) with the key's config content and
15
- * add it to the pool. Profile servers beyond a small cap are LRU-evicted.
16
- * 3. Health-check on every access; a dead server is dropped and respawned.
9
+ * The signature is a hash of the bytes we are about to hand the process —
10
+ * `OPENCODE_CONFIG_CONTENT`, the provider env vars, and a fingerprint of the
11
+ * on-disk artifact files it reads at boot. That is the whole point: the key is
12
+ * derived from the config itself rather than from a hand-maintained list of
13
+ * "things that need a restart". A field added to the spawn config three features
14
+ * from now is covered without anybody remembering that this file exists, and a
15
+ * change that turns out not to alter any baked byte (toggling a connector off and
16
+ * back on, editing a permission rule that is enforced per-prompt) produces the
17
+ * same hash and reuses the running server.
17
18
  *
18
- * The DEFAULT key (`*|*`, no Profile constraint) is the server used for model
19
- * listing and unprofiled streams. The pool is in-memory only — a Clopen restart
20
- * respawns servers (a legacy single-server URL persisted by older builds is
21
- * shut down once on first use).
19
+ * This replaced a "Restart Server" button. The button was the only thing that
20
+ * made a config edit take effect, which meant the product worked correctly only
21
+ * for users who knew the button existed. Everything below exists so that nobody
22
+ * has to know.
23
+ *
24
+ * ── Two keys, not one ───────────────────────────────────────────────────────
25
+ * `scopeKey` decides WHERE SESSION DATA LIVES (the XDG data dir holding
26
+ * opencode.db). `poolKey` decides WHICH PROCESS serves a stream. They are
27
+ * separate because conflating them loses conversations: session resume works by
28
+ * forking an opencode session id, so if the data dir moved every time a setting
29
+ * changed, every in-progress chat would silently lose its engine-side history the
30
+ * next time the user edited anything. The scope is the Profile's shape — the set
31
+ * of connectors and subagents — which is also the isolation boundary that made
32
+ * per-scope dirs necessary in the first place.
33
+ *
34
+ * A consequence is that two processes can briefly share one data dir while an old
35
+ * server drains. Open Code stores sessions in WAL-mode SQLite and keeps a `locks/`
36
+ * directory for exactly this, and running its CLI alongside a server on one XDG
37
+ * home is its normal mode of operation.
38
+ *
39
+ * ── Draining, not killing ───────────────────────────────────────────────────
40
+ * A server is never killed while a stream holds it. Each stream registers itself
41
+ * as a holder for as long as it runs — including while it sits waiting on an
42
+ * AskUserQuestion, which is idle but very much alive. A server whose config is no
43
+ * longer current dies the moment its last holder leaves; a current one dies after
44
+ * sitting unused for `IDLE_TTL_MS`.
45
+ *
46
+ * There is deliberately NO cap on the pool. A cap can only be enforced by killing
47
+ * a server, and the servers it would reach for during a burst are the ones being
48
+ * used — trading a bounded number of processes for broken chats. Idle servers are
49
+ * already reaped, so the count settles on its own.
22
50
  */
23
51
 
24
52
  import { join } from 'path';
53
+ import { readdir, rename, stat } from 'fs/promises';
25
54
  import type { OpencodeClient } from '@opencode-ai/sdk';
26
55
  import type { Subprocess } from 'bun';
27
56
  import { getOpenCodeMcpConfig } from '../../../mcp';
@@ -30,6 +59,7 @@ import { generateOpenCodeProviderConfig, parseCredentialMap } from './config';
30
59
  import type { OpenCodeInlineAgent } from '$backend/subagents';
31
60
  import { resolveEngineCli } from '$backend/engine/engine-cli';
32
61
  import { loadEngineSdk } from '$backend/engine/sdk-loader';
62
+ import { getEngineConfigRevision } from '$backend/engine/config-revision';
33
63
  import { getEngineUserConfigDir } from '$backend/utils/paths';
34
64
  import { debug } from '$shared/utils/logger';
35
65
 
@@ -39,30 +69,80 @@ const LEGACY_DB_KEY = 'opencode.server.url';
39
69
  const LEGACY_DB_KEY_DATADIR = 'opencode.server.datadir';
40
70
  const HEALTH_TIMEOUT = 1500;
41
71
  const SERVER_START_TIMEOUT = 30_000; // 30s — generous for slow devices
42
- /** Config signature for a stream with no Profile constraint. */
43
- export const DEFAULT_SERVER_KEY = '*|*';
44
- /** Max concurrently-pooled Profile servers (the default server is never evicted). */
45
- const MAX_POOL_SERVERS = 4;
72
+ /**
73
+ * Session-data scope for a stream with no Profile constraint.
74
+ *
75
+ * Must be exactly what `scopeKeyFor({})` produces — model listing, warm-up and
76
+ * unprofiled streams all have to land on the same scope, and a constant that
77
+ * merely looked like the default would silently match nothing.
78
+ */
79
+ export const DEFAULT_SCOPE_KEY = 'mcp:*|agents:*';
80
+ /** How long an unused, still-current server is kept before being reaped. */
81
+ const IDLE_TTL_MS = 30 * 60_000;
82
+ /**
83
+ * Grace period after last use during which a server is never reaped.
84
+ *
85
+ * Not every use registers a holder — model listing and one-shot structured
86
+ * generation borrow a client for a second and hand it back. Rather than thread a
87
+ * holder token through those call sites, the reaper simply leaves recently-touched
88
+ * servers alone. Worst case a superseded server lives ten seconds longer.
89
+ */
90
+ const REAP_GRACE_MS = 10_000;
46
91
 
47
92
  export interface ServerInstance {
93
+ /** Config signature — identifies the PROCESS. */
48
94
  key: string;
95
+ /** Profile shape — identifies the DATA DIR, and is stable across config edits. */
96
+ scopeKey: string;
49
97
  url: string;
50
98
  client: OpencodeClient;
51
99
  proc: Subprocess | null;
52
100
  ownsProcess: boolean;
53
101
  lastUsed: number;
102
+ /** Stream ids currently bound to this server. Non-empty ⇒ never reaped. */
103
+ holders: Set<string>;
54
104
  }
55
105
 
56
106
  /** What distinguishes one Profile's server from another. */
57
107
  export interface ServerConfigSpec {
58
108
  /** Allowed MCP connector slugs (undefined = unconstrained → all enabled). */
59
109
  mcpProfileFilter?: Set<string>;
110
+ /** Subagent slugs the active Profile narrows to (undefined = unconstrained). */
111
+ subagentFilter?: Set<string>;
60
112
  /** Inline agent definitions (undefined/empty = the engine's default set). */
61
113
  inlineAgents?: Record<string, OpenCodeInlineAgent>;
62
114
  }
63
115
 
116
+ /** Everything needed to spawn a server, plus the key derived from it. */
117
+ interface SpawnPlan {
118
+ key: string;
119
+ scopeKey: string;
120
+ configContent: string;
121
+ envVars: Record<string, string>;
122
+ }
123
+
124
+ /**
125
+ * The expensive half of a plan — cached until the config revision moves.
126
+ *
127
+ * Holds only what costs a network round-trip to determine: which MCP endpoints
128
+ * answered, and which models a custom provider advertises. Everything cheap is
129
+ * assembled per call, so nothing that can change without the database noticing
130
+ * gets to hide behind this cache.
131
+ */
132
+ interface CachedConfig {
133
+ revision: number;
134
+ mcpConfig: Record<string, unknown>;
135
+ enabledProviders: string[];
136
+ providerSection: Record<string, unknown>;
137
+ envVars: Record<string, string>;
138
+ }
139
+
64
140
  const pool = new Map<string, ServerInstance>();
65
141
  const initPromises = new Map<string, Promise<ServerInstance>>();
142
+ /** scopeKey → the poolKey that scope should currently be served by. */
143
+ const currentKeyByScope = new Map<string, string>();
144
+ const configCache = new Map<string, CachedConfig>();
145
+ const adoptedScopes = new Set<string>();
66
146
  let legacyCleaned = false;
67
147
 
68
148
  /** Short, stable FNV-1a hex hash — folds variable config (e.g. inline agent
@@ -106,112 +186,94 @@ function killInstance(inst: ServerInstance): void {
106
186
  }
107
187
  }
108
188
 
109
- /** Evict the least-recently-used PROFILE server when the pool is over cap. */
110
- function evictIfNeeded(): void {
111
- const evictable = [...pool.values()].filter(s => s.key !== DEFAULT_SERVER_KEY);
112
- if (evictable.length <= MAX_POOL_SERVERS) return;
113
- evictable.sort((a, b) => a.lastUsed - b.lastUsed);
114
- for (const victim of evictable.slice(0, evictable.length - MAX_POOL_SERVERS)) {
115
- debug.log('engine', `Open Code: evicting idle Profile server (${victim.key}) at ${victim.url}`);
116
- killInstance(victim);
117
- pool.delete(victim.key);
118
- }
119
- }
189
+ // ============================================================================
190
+ // Keys
191
+ // ============================================================================
120
192
 
121
193
  /**
122
- * Get (or spawn) the pooled Open Code server for a config signature. The `spec`
123
- * is only consulted when a server for `key` must be spawned; callers must pass a
124
- * `key` that uniquely captures the spec (see the adapter's signature builder).
194
+ * The session-data scope for a spec: what the active Profile CONSTRAINS, and
195
+ * nothing else.
196
+ *
197
+ * Only the Profile's filters go in — never the artifacts they resolve to, and
198
+ * never those artifacts' content. Both alternatives move the data dir for things
199
+ * that are not a change of isolation boundary: keying on the resolved agent set
200
+ * would relocate every conversation the moment a subagent is added globally, and
201
+ * keying on the agents' content (which the previous scheme did, by folding a
202
+ * content hash into the dir name) relocated them on every prompt edit. A
203
+ * relocated data dir means `session.fork` cannot find the session id and the
204
+ * chat silently loses its engine-side history.
125
205
  */
126
- export async function ensureServer(key: string, spec: ServerConfigSpec): Promise<ServerInstance> {
127
- await cleanupLegacyServer();
128
-
129
- const existing = pool.get(key);
130
- if (existing) {
131
- if (await isServerAlive(existing.url)) {
132
- existing.lastUsed = Date.now();
133
- return existing;
134
- }
135
- killInstance(existing);
136
- pool.delete(key);
137
- }
138
-
139
- const inFlight = initPromises.get(key);
140
- if (inFlight) return inFlight;
141
-
142
- const p = spawnServer(key, spec)
143
- .then(inst => {
144
- pool.set(key, inst);
145
- evictIfNeeded();
146
- return inst;
147
- })
148
- .finally(() => { initPromises.delete(key); });
149
- initPromises.set(key, p);
150
- return p;
206
+ function scopeKeyFor(spec: ServerConfigSpec): string {
207
+ const mcpKey = spec.mcpProfileFilter ? [...spec.mcpProfileFilter].sort().join(',') : '*';
208
+ const agentKey = spec.subagentFilter ? [...spec.subagentFilter].sort().join(',') : '*';
209
+ return `mcp:${mcpKey}|agents:${agentKey}`;
151
210
  }
152
211
 
153
- async function spawnServer(key: string, spec: ServerConfigSpec): Promise<ServerInstance> {
154
- debug.log('engine', `Spawning Open Code server for key "${key}"...`);
155
-
156
- // Isolate Open Code state under Clopen's dir (XDG overrides) — never mixes with
157
- // the user's own CLI usage. CONFIG is shared across pooled servers (commands +
158
- // instructions live there; agents come INLINE via OPENCODE_CONFIG_CONTENT, not
159
- // the on-disk agent dir). DATA/STATE/CACHE (incl. opencode.db, sessions,
160
- // snapshots) are per-key so concurrent Profile servers never share one SQLite
161
- // db. The DEFAULT server keeps the base dir for back-compat with old sessions.
162
- const configDir = getEngineUserConfigDir('opencode');
163
- const dataDir = key === DEFAULT_SERVER_KEY
164
- ? configDir
165
- : join(configDir, 'pool', Buffer.from(key).toString('base64url'));
212
+ /**
213
+ * Session data dir for a scope.
214
+ *
215
+ * Every scope — including the unconstrained one — gets its own directory under
216
+ * `pool/`, so concurrent Profile servers never share a SQLite store. The base
217
+ * config dir stays XDG_CONFIG_HOME (commands, AGENTS.md), which is shared by
218
+ * design and holds no session state.
219
+ */
220
+ function dataDirForScope(scopeKey: string): string {
221
+ return join(getEngineUserConfigDir('opencode'), 'pool', Buffer.from(scopeKey).toString('base64url'));
222
+ }
166
223
 
167
- // The CLI lives in clopen's managed stack dir (or, failing that, on the
168
- // user's PATH); `resolveEngineCli` is the same lookup Settings → Stack
169
- // reports, so an engine shown as installed is always one we can spawn.
170
- // The literal "Settings → Stack" routes the chat/model-picker error to the
171
- // one place that fixes it.
172
- const cli = await resolveEngineCli('opencode');
173
- if (!cli) {
174
- throw new Error(
175
- 'Open Code is missing its CLI. Open Settings → Stack to install it before using this engine.'
176
- );
177
- }
178
- const args = [cli.path, 'serve', `--hostname=${OPENCODE_HOST}`, '--port=0'];
224
+ /**
225
+ * Fingerprint of the artifact files Open Code reads at boot.
226
+ *
227
+ * Commands, subagent files and the AGENTS.md instruction block are written to
228
+ * disk by the per-stream artifact sync, so their CONTENT never appears in the DB
229
+ * and the config revision cannot see it change. Size + mtime is enough to notice
230
+ * an edit and costs three stats. Missing paths contribute a stable marker rather
231
+ * than throwing — an engine with no commands yet is the normal case.
232
+ */
233
+ async function artifactFingerprint(): Promise<string> {
234
+ const base = join(getEngineUserConfigDir('opencode'), 'opencode');
235
+ const targets = [join(base, 'command'), join(base, 'agent'), join(base, 'AGENTS.md')];
236
+ const parts: string[] = [];
179
237
 
180
- // MCP: only inject remote servers whose endpoint is reachable — an unreachable
181
- // remote can stall startup. stdio/local servers (no `url`) always survive.
182
- const mcpConfig = getOpenCodeMcpConfig(spec.mcpProfileFilter);
183
- if (Object.keys(mcpConfig).length > 0) {
184
- const entries = Object.entries(mcpConfig);
185
- const reachability = await Promise.all(
186
- entries.map(([, c]) => {
187
- const url = (c as any).url as string | undefined;
188
- return url ? isServerAlive(url) : Promise.resolve(true);
189
- })
190
- );
191
- entries.forEach(([name, config], i) => {
192
- if (reachability[i]) {
193
- debug.log('engine', `Open Code[${key}]: MCP → ${name}: ${config.type} (${(config as any).url || (config as any).command?.join(' ')})`);
238
+ for (const path of targets) {
239
+ try {
240
+ const info = await stat(path);
241
+ if (info.isDirectory()) {
242
+ const names = (await readdir(path)).sort();
243
+ const entries = await Promise.all(names.map(async name => {
244
+ try {
245
+ const child = await stat(join(path, name));
246
+ return `${name}:${child.size}:${Math.floor(child.mtimeMs)}`;
247
+ } catch {
248
+ return `${name}:gone`;
249
+ }
250
+ }));
251
+ parts.push(`${path}[${entries.join('|')}]`);
194
252
  } else {
195
- debug.warn('engine', `Open Code[${key}]: MCP endpoint for "${name}" not reachable, skipping it`);
196
- delete mcpConfig[name];
253
+ parts.push(`${path}:${info.size}:${Math.floor(info.mtimeMs)}`);
197
254
  }
198
- });
255
+ } catch {
256
+ parts.push(`${path}:absent`);
257
+ }
199
258
  }
200
259
 
201
- const providerConfig = generateOpenCodeProviderConfig();
260
+ return hashConfig(parts.join('\n'));
261
+ }
202
262
 
203
- // Merge MCP + providers + inline agents into a single OPENCODE_CONFIG_CONTENT.
204
- const mergedConfig: Record<string, unknown> = {};
205
- if (Object.keys(mcpConfig).length > 0) mergedConfig.mcp = mcpConfig;
206
- if (providerConfig.enabledProviders.length > 0) mergedConfig.enabled_providers = providerConfig.enabledProviders;
207
- if (spec.inlineAgents && Object.keys(spec.inlineAgents).length > 0) mergedConfig.agent = spec.inlineAgents;
208
-
209
- // Inject provider definitions for custom OpenAI-compatible providers
210
- // (those with api_url set). Unlike models.dev catalog providers, custom
211
- // providers need their npm + baseURL passed explicitly so the opencode
212
- // server can discover models from their /v1/models endpoint.
263
+ // ============================================================================
264
+ // Config building
265
+ // ============================================================================
266
+
267
+ /**
268
+ * Build the provider section for custom OpenAI-compatible providers.
269
+ *
270
+ * Unlike models.dev catalog providers, these need their npm package and baseURL
271
+ * passed explicitly so the server can discover models from `/v1/models`.
272
+ */
273
+ async function buildProviderSection(): Promise<Record<string, unknown>> {
213
274
  const providerSection: Record<string, unknown> = {};
214
275
  const opencodeProviders = engineQueries.getEnabledProviders('opencode');
276
+
215
277
  for (const provider of opencodeProviders) {
216
278
  if (!provider.api_url) continue;
217
279
 
@@ -243,6 +305,7 @@ async function spawnServer(key: string, spec: ServerConfigSpec): Promise<ServerI
243
305
  let modelLimits: Record<string, { context?: number; output?: number }> = {};
244
306
  let modelNames: Record<string, string> = {};
245
307
  let hiddenSet = new Set<string>();
308
+ let storedModels: string[] = [];
246
309
  try {
247
310
  const opts = JSON.parse(provider.options || '{}') as {
248
311
  models?: string[];
@@ -257,6 +320,7 @@ async function spawnServer(key: string, spec: ServerConfigSpec): Promise<ServerI
257
320
  if (opts.modelLimits) modelLimits = opts.modelLimits;
258
321
  if (opts.modelNames) modelNames = opts.modelNames;
259
322
  if (opts.hiddenModels) hiddenSet = new Set(opts.hiddenModels);
323
+ if (opts.models) storedModels = opts.models;
260
324
  } catch {
261
325
  // malformed options — proceed to auto-discover
262
326
  }
@@ -266,15 +330,8 @@ async function spawnServer(key: string, spec: ServerConfigSpec): Promise<ServerI
266
330
  models[id] = { name: modelNames[id] || id, limit: { context: lim?.context || defaultContext, output: lim?.output || defaultOutput } };
267
331
  };
268
332
 
269
- try {
270
- const opts = JSON.parse(provider.options || '{}') as { models?: string[] };
271
- if (opts.models && opts.models.length > 0) {
272
- for (const id of opts.models) {
273
- if (!hiddenSet.has(id)) addModel(id);
274
- }
275
- }
276
- } catch {
277
- // malformed options — proceed to auto-discover
333
+ for (const id of storedModels) {
334
+ if (!hiddenSet.has(id)) addModel(id);
278
335
  }
279
336
 
280
337
  // Auto-discover models from /v1/models if none stored in options
@@ -296,11 +353,7 @@ async function spawnServer(key: string, spec: ServerConfigSpec): Promise<ServerI
296
353
  }
297
354
  }
298
355
 
299
- let modelOrder: string[] | undefined;
300
- try {
301
- const o = JSON.parse(provider.options || '{}') as { models?: string[] };
302
- if (o.models && o.models.length > 0) modelOrder = o.models.filter(id => !hiddenSet.has(id));
303
- } catch { /* ignore */ }
356
+ const modelOrder = storedModels.length > 0 ? storedModels.filter(id => !hiddenSet.has(id)) : undefined;
304
357
  const providerOptions: Record<string, unknown> = { baseURL };
305
358
  if (apiKey) providerOptions.apiKey = apiKey;
306
359
  if (modelOrder) providerOptions._modelOrder = modelOrder;
@@ -311,21 +364,292 @@ async function spawnServer(key: string, spec: ServerConfigSpec): Promise<ServerI
311
364
  models: models,
312
365
  };
313
366
  }
314
- if (Object.keys(providerSection).length > 0) mergedConfig.provider = providerSection;
315
367
 
316
- const configContent = Object.keys(mergedConfig).length > 0 ? JSON.stringify(mergedConfig) : '{}';
368
+ return providerSection;
369
+ }
370
+
371
+ /**
372
+ * Assemble the exact config content and env a server for `spec` would be spawned
373
+ * with. Cached per (config revision, scope) because it makes network calls —
374
+ * reachability probes and model discovery — that must not run on every turn.
375
+ */
376
+ async function resolveConfig(spec: ServerConfigSpec, scopeKey: string): Promise<CachedConfig> {
377
+ const revision = getEngineConfigRevision();
378
+ const cached = configCache.get(scopeKey);
379
+ if (cached && cached.revision === revision) return cached;
380
+
381
+ // MCP: only inject remote servers whose endpoint is reachable — an unreachable
382
+ // remote can stall startup. stdio/local servers (no `url`) always survive.
383
+ const mcpConfig = getOpenCodeMcpConfig(spec.mcpProfileFilter);
384
+ if (Object.keys(mcpConfig).length > 0) {
385
+ const entries = Object.entries(mcpConfig);
386
+ const reachability = await Promise.all(
387
+ entries.map(([, c]) => {
388
+ const url = (c as any).url as string | undefined;
389
+ return url ? isServerAlive(url) : Promise.resolve(true);
390
+ })
391
+ );
392
+ entries.forEach(([name, config], i) => {
393
+ if (reachability[i]) {
394
+ debug.log('engine', `Open Code[${scopeKey}]: MCP → ${name}: ${config.type} (${(config as any).url || (config as any).command?.join(' ')})`);
395
+ } else {
396
+ debug.warn('engine', `Open Code[${scopeKey}]: MCP endpoint for "${name}" not reachable, skipping it`);
397
+ delete mcpConfig[name];
398
+ }
399
+ });
400
+ }
401
+
402
+ const providerConfig = generateOpenCodeProviderConfig();
403
+
404
+ const resolved: CachedConfig = {
405
+ revision,
406
+ mcpConfig,
407
+ enabledProviders: providerConfig.enabledProviders,
408
+ providerSection: await buildProviderSection(),
409
+ envVars: providerConfig.envVars,
410
+ };
411
+ configCache.set(scopeKey, resolved);
412
+ return resolved;
413
+ }
414
+
415
+ /**
416
+ * Assemble the exact `OPENCODE_CONFIG_CONTENT` for a spawn.
417
+ *
418
+ * The inline agents are folded in HERE rather than inside the cached half, and
419
+ * that placement is load-bearing. A subagent's prompt lives in the canonical
420
+ * store on disk, not in the `subagents` table, so editing it changes no database
421
+ * row and moves no revision — and because Open Code receives agents inline, it
422
+ * also touches none of the files the artifact fingerprint watches. Caching a
423
+ * config that already contained the agents would therefore serve the old prompt
424
+ * indefinitely. `buildOpenCodeInlineAgents` reads that store fresh at every
425
+ * stream start, so folding its result in at assembly time makes the edit reach
426
+ * the signature the way any other config change does.
427
+ */
428
+ function assembleConfigContent(cached: CachedConfig, inlineAgents?: Record<string, OpenCodeInlineAgent>): string {
429
+ const mergedConfig: Record<string, unknown> = {};
430
+ if (Object.keys(cached.mcpConfig).length > 0) mergedConfig.mcp = cached.mcpConfig;
431
+ if (cached.enabledProviders.length > 0) mergedConfig.enabled_providers = cached.enabledProviders;
432
+ if (inlineAgents && Object.keys(inlineAgents).length > 0) mergedConfig.agent = inlineAgents;
433
+ if (Object.keys(cached.providerSection).length > 0) mergedConfig.provider = cached.providerSection;
434
+ return Object.keys(mergedConfig).length > 0 ? JSON.stringify(mergedConfig) : '{}';
435
+ }
436
+
437
+ /**
438
+ * The plan for `spec` right now, including the key that identifies its process.
439
+ *
440
+ * Also records the scope's current key, which is what makes a superseded server
441
+ * reapable: the reaper does not need to be told a config changed, it only needs
442
+ * to see that a pooled server's key is no longer the one its scope resolves to.
443
+ */
444
+ async function resolvePlan(spec: ServerConfigSpec): Promise<SpawnPlan> {
445
+ const scopeKey = scopeKeyFor(spec);
446
+ const [config, fingerprint] = await Promise.all([resolveConfig(spec, scopeKey), artifactFingerprint()]);
447
+ const configContent = assembleConfigContent(config, spec.inlineAgents);
448
+ const signature = hashConfig(`${configContent}‖${JSON.stringify(config.envVars)}‖${fingerprint}`);
449
+ const key = `${scopeKey}#${signature}`;
450
+
451
+ currentKeyByScope.set(scopeKey, key);
452
+ return { key, scopeKey, configContent, envVars: config.envVars };
453
+ }
454
+
455
+ // ============================================================================
456
+ // Reaping
457
+ // ============================================================================
458
+
459
+ /**
460
+ * Kill servers nothing needs any more.
461
+ *
462
+ * Superseded servers go as soon as they are unheld; current ones go after
463
+ * sitting idle. A held server is never touched, whatever its age — a chat
464
+ * blocked on an AskUserQuestion for ten minutes is a live conversation, not an
465
+ * idle process.
466
+ */
467
+ function reap(reason: string): void {
468
+ const now = Date.now();
469
+ for (const inst of [...pool.values()]) {
470
+ if (inst.holders.size > 0) continue;
471
+ if (now - inst.lastUsed < REAP_GRACE_MS) continue;
472
+
473
+ const current = currentKeyByScope.get(inst.scopeKey);
474
+ const superseded = current !== undefined && current !== inst.key;
475
+ const expired = now - inst.lastUsed > IDLE_TTL_MS;
476
+ if (!superseded && !expired) continue;
477
+
478
+ debug.log('engine', `Open Code: reaping ${superseded ? 'superseded' : 'idle'} server ${inst.url} (${inst.key}) — ${reason}`);
479
+ killInstance(inst);
480
+ pool.delete(inst.key);
481
+ }
482
+ }
483
+
484
+ /**
485
+ * Drop holders that no longer correspond to a live stream.
486
+ *
487
+ * Holder bookkeeping is a `finally` away from being correct, and a `finally` is
488
+ * one uncaught teardown path away from leaking a holder forever — which, with no
489
+ * restart button left, would strand a superseded server permanently. The live
490
+ * stream set is the authority; this reconciles against it. Same shape as the
491
+ * orphan sweep the MCP tab locks use.
492
+ */
493
+ export function reconcileServerHolders(liveStreamIds: Set<string>): void {
494
+ let dropped = 0;
495
+ for (const inst of pool.values()) {
496
+ for (const holder of [...inst.holders]) {
497
+ if (!liveStreamIds.has(holder)) {
498
+ inst.holders.delete(holder);
499
+ dropped++;
500
+ }
501
+ }
502
+ }
503
+ if (dropped > 0) debug.log('engine', `Open Code: released ${dropped} orphaned server holder(s)`);
504
+ reap('holder reconciliation');
505
+ }
506
+
507
+ // ============================================================================
508
+ // Pool access
509
+ // ============================================================================
510
+
511
+ /**
512
+ * One-time adoption of a data dir written by the previous key scheme.
513
+ *
514
+ * The old scheme folded the inline agents' content hash into the dir name, so an
515
+ * upgrade would otherwise point a scope at an empty directory and every existing
516
+ * conversation under it would fail to resume. The old name is this scope's key
517
+ * plus `:<hash>`, so the directory is findable; the newest match wins.
518
+ */
519
+ async function adoptLegacyScopeDir(scopeKey: string, dataDir: string): Promise<void> {
520
+ if (adoptedScopes.has(scopeKey)) return;
521
+ adoptedScopes.add(scopeKey);
522
+
523
+ try {
524
+ await stat(dataDir);
525
+ return; // Already populated — nothing to adopt.
526
+ } catch { /* fall through */ }
527
+
528
+ const poolRoot = join(getEngineUserConfigDir('opencode'), 'pool');
529
+ let candidates: string[];
530
+ try {
531
+ candidates = await readdir(poolRoot);
532
+ } catch {
533
+ return; // No pool dir yet — fresh install.
534
+ }
535
+
536
+ let newest: { path: string; mtime: number } | null = null;
537
+ for (const name of candidates) {
538
+ let decoded: string;
539
+ try {
540
+ decoded = Buffer.from(name, 'base64url').toString();
541
+ } catch {
542
+ continue;
543
+ }
544
+ if (!decoded.startsWith(`${scopeKey}:`)) continue;
545
+ try {
546
+ const info = await stat(join(poolRoot, name));
547
+ if (!newest || info.mtimeMs > newest.mtime) newest = { path: join(poolRoot, name), mtime: info.mtimeMs };
548
+ } catch { /* raced away */ }
549
+ }
550
+
551
+ if (!newest) return;
552
+ try {
553
+ await rename(newest.path, dataDir);
554
+ debug.log('engine', `Open Code: adopted legacy session dir for scope "${scopeKey}"`);
555
+ } catch (error) {
556
+ debug.warn('engine', `Open Code: could not adopt legacy session dir for "${scopeKey}"`, error);
557
+ }
558
+ }
559
+
560
+ /**
561
+ * Get (or spawn) the server matching `spec`'s current config.
562
+ *
563
+ * `holderId` — the stream id — pins the returned server for as long as that
564
+ * stream runs. Pass `undefined` for a borrow (model listing, warm-up); the
565
+ * reaper's grace window covers those.
566
+ */
567
+ export async function acquireServer(spec: ServerConfigSpec, holderId?: string): Promise<ServerInstance> {
568
+ await cleanupLegacyServer();
569
+
570
+ const plan = await resolvePlan(spec);
571
+ const existing = pool.get(plan.key);
572
+ if (existing) {
573
+ if (await isServerAlive(existing.url)) {
574
+ existing.lastUsed = Date.now();
575
+ if (holderId) existing.holders.add(holderId);
576
+ reap('server reuse');
577
+ return existing;
578
+ }
579
+ killInstance(existing);
580
+ pool.delete(plan.key);
581
+ }
582
+
583
+ const inFlight = initPromises.get(plan.key);
584
+ if (inFlight) {
585
+ const inst = await inFlight;
586
+ if (holderId) inst.holders.add(holderId);
587
+ return inst;
588
+ }
589
+
590
+ const p = spawnServer(plan)
591
+ .then(inst => {
592
+ pool.set(plan.key, inst);
593
+ // Only now that a healthy replacement exists is the old one expendable.
594
+ // Spawning before killing means a config that cannot start leaves the
595
+ // user with the previous working server rather than with nothing.
596
+ reap('new server ready');
597
+ return inst;
598
+ })
599
+ .finally(() => { initPromises.delete(plan.key); });
600
+ initPromises.set(plan.key, p);
601
+
602
+ const inst = await p;
603
+ if (holderId) inst.holders.add(holderId);
604
+ return inst;
605
+ }
606
+
607
+ /** Release a stream's hold, and reap anything that became expendable. */
608
+ export function releaseServer(key: string, holderId: string): void {
609
+ const inst = pool.get(key);
610
+ if (!inst) return;
611
+ inst.holders.delete(holderId);
612
+ inst.lastUsed = Date.now();
613
+ reap('holder released');
614
+ }
615
+
616
+ async function spawnServer(plan: SpawnPlan): Promise<ServerInstance> {
617
+ debug.log('engine', `Spawning Open Code server for key "${plan.key}"...`);
618
+
619
+ // Isolate Open Code state under Clopen's dir (XDG overrides) — never mixes with
620
+ // the user's own CLI usage. CONFIG is shared across pooled servers (commands +
621
+ // instructions live there; agents come INLINE via OPENCODE_CONFIG_CONTENT, not
622
+ // the on-disk agent dir). DATA/STATE/CACHE (incl. opencode.db, sessions,
623
+ // snapshots) follow the SCOPE, not the config signature, so a settings change
624
+ // never moves a running conversation's session store.
625
+ const configDir = getEngineUserConfigDir('opencode');
626
+ const dataDir = dataDirForScope(plan.scopeKey);
627
+ await adoptLegacyScopeDir(plan.scopeKey, dataDir);
628
+
629
+ // The CLI lives in clopen's managed stack dir (or, failing that, on the
630
+ // user's PATH); `resolveEngineCli` is the same lookup Settings → Stack
631
+ // reports, so an engine shown as installed is always one we can spawn.
632
+ // The literal "Settings → Stack" routes the chat/model-picker error to the
633
+ // one place that fixes it.
634
+ const cli = await resolveEngineCli('opencode');
635
+ if (!cli) {
636
+ throw new Error(
637
+ 'Open Code is missing its CLI. Open Settings → Stack to install it before using this engine.'
638
+ );
639
+ }
640
+ const args = [cli.path, 'serve', `--hostname=${OPENCODE_HOST}`, '--port=0'];
317
641
 
318
642
  const proc = Bun.spawn(args, {
319
643
  stdout: 'pipe',
320
644
  stderr: 'pipe',
321
645
  env: {
322
646
  ...process.env,
323
- ...providerConfig.envVars,
647
+ ...plan.envVars,
324
648
  XDG_CONFIG_HOME: configDir,
325
649
  XDG_DATA_HOME: dataDir,
326
650
  XDG_STATE_HOME: dataDir,
327
651
  XDG_CACHE_HOME: dataDir,
328
- OPENCODE_CONFIG_CONTENT: configContent,
652
+ OPENCODE_CONFIG_CONTENT: plan.configContent,
329
653
  },
330
654
  });
331
655
 
@@ -368,8 +692,44 @@ async function spawnServer(key: string, spec: ServerConfigSpec): Promise<ServerI
368
692
 
369
693
  const { createOpencodeClient } = await loadEngineSdk<typeof import('@opencode-ai/sdk')>('opencode', '@opencode-ai/sdk');
370
694
  const client = createOpencodeClient({ baseUrl: url });
371
- debug.log('engine', `Open Code server ready (key "${key}", ${url}, data dir: ${dataDir})`);
372
- return { key, url, client, proc, ownsProcess: true, lastUsed: Date.now() };
695
+ debug.log('engine', `Open Code server ready (key "${plan.key}", ${url}, data dir: ${dataDir})`);
696
+ return {
697
+ key: plan.key,
698
+ scopeKey: plan.scopeKey,
699
+ url,
700
+ client,
701
+ proc,
702
+ ownsProcess: true,
703
+ lastUsed: Date.now(),
704
+ holders: new Set<string>(),
705
+ };
706
+ }
707
+
708
+ /**
709
+ * Bring every pooled scope up to date with the current config.
710
+ *
711
+ * Called after a config change settles and no stream is running: the replacement
712
+ * is spawned and verified now, so the user's next message does not pay for it.
713
+ * When streams ARE running this is skipped entirely — the next stream to start
714
+ * resolves the new key on its own, and the running ones keep the server they
715
+ * were bound to. A failure here is logged and nothing else: the existing server
716
+ * stays in the pool, and the real error surfaces in chat when a turn actually
717
+ * needs the config that cannot start.
718
+ */
719
+ export async function refreshPool(specForScope: Map<string, ServerConfigSpec>): Promise<void> {
720
+ for (const [scopeKey, spec] of specForScope) {
721
+ try {
722
+ await acquireServer(spec);
723
+ } catch (error) {
724
+ debug.warn('engine', `Open Code: warm-up for scope "${scopeKey}" failed; keeping the current server`, error);
725
+ }
726
+ }
727
+ reap('post warm-up');
728
+ }
729
+
730
+ /** The scopes currently backed by a pooled server, for warm-up. */
731
+ export function pooledScopeKeys(): string[] {
732
+ return [...new Set([...pool.values()].map(s => s.scopeKey))];
373
733
  }
374
734
 
375
735
  /**
@@ -377,17 +737,32 @@ async function spawnServer(key: string, spec: ServerConfigSpec): Promise<ServerI
377
737
  * generation, and warm-up. Concurrency-safe via the shared init promise.
378
738
  */
379
739
  export async function ensureClient(): Promise<OpencodeClient> {
380
- return (await ensureServer(DEFAULT_SERVER_KEY, {})).client;
740
+ return (await acquireServer({})).client;
381
741
  }
382
742
 
383
743
  /** The DEFAULT server's client, if up (back-compat for callers with no stream context). */
384
744
  export function getClient(): OpencodeClient | null {
385
- return pool.get(DEFAULT_SERVER_KEY)?.client ?? null;
745
+ const inst = defaultInstance();
746
+ if (inst) inst.lastUsed = Date.now();
747
+ return inst?.client ?? null;
386
748
  }
387
749
 
388
750
  /** The DEFAULT server's URL, if up. */
389
751
  export function getServerUrl(): string | null {
390
- return pool.get(DEFAULT_SERVER_KEY)?.url ?? null;
752
+ const inst = defaultInstance();
753
+ if (inst) inst.lastUsed = Date.now();
754
+ return inst?.url ?? null;
755
+ }
756
+
757
+ function defaultInstance(): ServerInstance | undefined {
758
+ const key = currentKeyByScope.get(DEFAULT_SCOPE_KEY);
759
+ if (key) {
760
+ const exact = pool.get(key);
761
+ if (exact) return exact;
762
+ }
763
+ // The current key is unknown until a config has been resolved once; fall back
764
+ // to any server on the default scope rather than reporting nothing.
765
+ return [...pool.values()].find(s => s.scopeKey === DEFAULT_SCOPE_KEY);
391
766
  }
392
767
 
393
768
  /**
@@ -399,6 +774,8 @@ export async function disposeOpenCodeClient(_forRestart = false): Promise<void>
399
774
  for (const inst of pool.values()) killInstance(inst);
400
775
  pool.clear();
401
776
  initPromises.clear();
777
+ currentKeyByScope.clear();
778
+ configCache.clear();
402
779
  settingsQueries.delete(LEGACY_DB_KEY);
403
780
  settingsQueries.delete(LEGACY_DB_KEY_DATADIR);
404
781
  debug.log('engine', 'Open Code pool disposed');