@myrialabs/clopen 0.4.31 → 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 +27 -11
- 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 +45 -18
- 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 +511 -134
- 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/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/hot-reload.ts +99 -0
- package/backend/engine/index.ts +96 -24
- 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/ws/chat/stream.ts +24 -0
- package/backend/ws/engine/codex/accounts.ts +0 -12
- 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/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
|
@@ -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.
|
|
6
|
-
*
|
|
7
|
-
*
|
|
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
|
-
*
|
|
13
|
-
*
|
|
14
|
-
*
|
|
15
|
-
*
|
|
16
|
-
*
|
|
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
|
-
*
|
|
19
|
-
*
|
|
20
|
-
*
|
|
21
|
-
*
|
|
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
|
-
/**
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
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
|
-
|
|
110
|
-
|
|
111
|
-
|
|
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
|
-
*
|
|
123
|
-
*
|
|
124
|
-
*
|
|
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
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
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
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
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
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
const
|
|
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
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
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
|
-
|
|
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
|
-
|
|
260
|
+
return hashConfig(parts.join('\n'));
|
|
261
|
+
}
|
|
202
262
|
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
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
|
-
|
|
270
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
...
|
|
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 {
|
|
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
|
|
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
|
-
|
|
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
|
-
|
|
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');
|