@myrialabs/clopen 0.4.35 → 0.4.36
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/artifacts/sync.test.ts +63 -0
- package/backend/artifacts/sync.ts +56 -3
- package/backend/database/migrations/070_create_worktrees_table.ts +67 -0
- package/backend/database/migrations/index.ts +7 -0
- package/backend/database/queries/index.ts +1 -0
- package/backend/database/queries/session-queries.ts +50 -11
- package/backend/database/queries/worktree-queries.ts +148 -0
- package/backend/engine/adapters/opencode/server.ts +389 -83
- package/backend/engine/adapters/opencode/stream.ts +14 -14
- package/backend/engine/hot-reload.ts +25 -10
- package/backend/files/file-watcher.ts +35 -9
- package/backend/host/metrics.test.ts +110 -0
- package/backend/host/metrics.ts +235 -0
- package/backend/index.ts +5 -2
- package/backend/mcp/internal/servers/browser-automation/context.ts +16 -2
- package/backend/ports/attribute.test.ts +3 -2
- package/backend/ports/attribute.ts +5 -44
- package/backend/preview/browser/browser-pool.ts +81 -0
- package/backend/preview/browser/browser-preview-service.ts +142 -32
- package/backend/preview/browser/browser-tab-manager.ts +350 -113
- package/backend/preview/browser/types.ts +9 -0
- package/backend/projects/project-cleanup.integration.test.ts +1 -1
- package/backend/projects/project-cleanup.ts +7 -1
- package/backend/projects/shell-ownership.ts +65 -0
- package/backend/snapshot/snapshot-service.ts +6 -2
- package/backend/terminal/ptykit.ts +35 -6
- package/backend/utils/ws.ts +21 -1
- package/backend/worktrees/clone.ts +222 -0
- package/backend/worktrees/index.ts +29 -0
- package/backend/worktrees/merge.test.ts +93 -0
- package/backend/worktrees/merge.ts +232 -0
- package/backend/worktrees/paths.test.ts +60 -0
- package/backend/worktrees/paths.ts +60 -0
- package/backend/worktrees/resolve.ts +67 -0
- package/backend/worktrees/service.ts +315 -0
- package/backend/worktrees/tree.ts +59 -0
- package/backend/ws/access.ts +18 -0
- package/backend/ws/artifacts/generate.ts +2 -2
- package/backend/ws/chat/stream.ts +9 -2
- package/backend/ws/files/panel-state-scope.test.ts +102 -0
- package/backend/ws/files/path-access.test.ts +93 -1
- package/backend/ws/files/path-access.ts +54 -5
- package/backend/ws/files/read.ts +15 -10
- package/backend/ws/files/search.ts +7 -7
- package/backend/ws/files/state.ts +70 -8
- package/backend/ws/files/watch.ts +16 -14
- package/backend/ws/git/branch-name.ts +3 -3
- package/backend/ws/git/branch.ts +15 -15
- package/backend/ws/git/commit-message.ts +3 -3
- package/backend/ws/git/commit.ts +17 -17
- package/backend/ws/git/conflict.ts +10 -10
- package/backend/ws/git/diff.ts +9 -9
- package/backend/ws/git/ignored.ts +9 -9
- package/backend/ws/git/log.ts +3 -3
- package/backend/ws/git/remote.ts +43 -43
- package/backend/ws/git/staging.ts +16 -16
- package/backend/ws/git/status.ts +13 -13
- package/backend/ws/index.ts +4 -0
- package/backend/ws/preview/access.ts +11 -3
- package/backend/ws/projects/index.ts +5 -1
- package/backend/ws/projects/info.test.ts +54 -0
- package/backend/ws/projects/info.ts +398 -0
- package/backend/ws/sessions/crud.ts +21 -6
- package/backend/ws/snapshot/restore.ts +11 -14
- package/backend/ws/system/device-info.ts +62 -144
- package/backend/ws/worktrees/crud.ts +187 -0
- package/backend/ws/worktrees/index.ts +33 -0
- package/backend/ws/worktrees/transfer.ts +88 -0
- package/dist/assets/{index-B0iIhSO9.js → index-Bg-SUCFg.js} +1 -1
- package/dist/assets/{index-BRJqss6F.js → index-Cz4YpHVi.js} +1 -1
- package/dist/assets/main-9G7IpQpK.css +1 -0
- package/dist/assets/main-BofFsH8E.js +1085 -0
- package/dist/index.html +2 -2
- package/package.json +1 -1
- package/shared/types/database/schema.ts +26 -0
- package/shared/utils/logger.ts +1 -0
- package/shared/utils/workspace-scope.test.ts +80 -0
- package/shared/utils/workspace-scope.ts +57 -0
- package/shared/utils/ws-client.ts +25 -5
- package/shared/utils/ws-server.ts +19 -3
- package/dist/assets/main-Buko4D0t.css +0 -1
- package/dist/assets/main-C_iGUZyL.js +0 -1078
|
@@ -12,9 +12,15 @@
|
|
|
12
12
|
* derived from the config itself rather than from a hand-maintained list of
|
|
13
13
|
* "things that need a restart". A field added to the spawn config three features
|
|
14
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 (
|
|
16
|
-
*
|
|
17
|
-
*
|
|
15
|
+
* change that turns out not to alter any baked byte (editing a permission rule
|
|
16
|
+
* that is enforced per-prompt) produces the same hash and reuses the running
|
|
17
|
+
* server.
|
|
18
|
+
*
|
|
19
|
+
* One thing the bytes cannot express is folded in explicitly: the INTERNAL
|
|
20
|
+
* connector set. Those all sit behind a single `clopen-mcp` bridge entry, so
|
|
21
|
+
* toggling one changes what the bridge serves without changing the config at
|
|
22
|
+
* all — and Open Code reads its tool list once, when it connects. See
|
|
23
|
+
* `internalBridgeExposure`.
|
|
18
24
|
*
|
|
19
25
|
* This replaced a "Restart Server" button. The button was the only thing that
|
|
20
26
|
* made a config edit take effect, which meant the product worked correctly only
|
|
@@ -43,17 +49,28 @@
|
|
|
43
49
|
* longer current dies the moment its last holder leaves; a current one dies after
|
|
44
50
|
* sitting unused for `IDLE_TTL_MS`.
|
|
45
51
|
*
|
|
52
|
+
* Both rules are enforced by a TIMER, not by the next call to `acquireServer`.
|
|
53
|
+
* Reaping as a side effect of acquiring meant nothing was ever collected once
|
|
54
|
+
* Open Code went quiet — which is exactly when there is most to collect.
|
|
55
|
+
*
|
|
46
56
|
* There is deliberately NO cap on the pool. A cap can only be enforced by killing
|
|
47
57
|
* a server, and the servers it would reach for during a burst are the ones being
|
|
48
58
|
* used — trading a bounded number of processes for broken chats. Idle servers are
|
|
49
59
|
* already reaped, so the count settles on its own.
|
|
60
|
+
*
|
|
61
|
+
* ── Outliving us ────────────────────────────────────────────────────────────
|
|
62
|
+
* These are child processes that do NOT die with their parent, so every spawn is
|
|
63
|
+
* recorded in the DB and a fresh process sweeps what a crash left behind. The
|
|
64
|
+
* record carries the owning Clopen pid: a second instance sharing one `app.db`
|
|
65
|
+
* must not mistake the first's live servers for orphans.
|
|
50
66
|
*/
|
|
51
67
|
|
|
52
68
|
import { join } from 'path';
|
|
53
|
-
import { readdir, rename, stat } from 'fs/promises';
|
|
69
|
+
import { readdir, readFile, rename, stat } from 'fs/promises';
|
|
70
|
+
import { createServer } from 'node:net';
|
|
54
71
|
import type { OpencodeClient } from '@opencode-ai/sdk';
|
|
55
72
|
import type { Subprocess } from 'bun';
|
|
56
|
-
import { getOpenCodeMcpConfig } from '../../../mcp';
|
|
73
|
+
import { getOpenCodeMcpConfig, getEnabledServerNames, getEnabledToolsForServer } from '../../../mcp';
|
|
57
74
|
import { engineQueries, settingsQueries } from '../../../database/queries';
|
|
58
75
|
import { generateOpenCodeProviderConfig, parseCredentialMap } from './config';
|
|
59
76
|
import type { OpenCodeInlineAgent } from '$backend/subagents';
|
|
@@ -64,11 +81,21 @@ import { getEngineUserConfigDir } from '$backend/utils/paths';
|
|
|
64
81
|
import { debug } from '$shared/utils/logger';
|
|
65
82
|
|
|
66
83
|
const OPENCODE_HOST = '127.0.0.1';
|
|
84
|
+
/** Basic-auth user the server is started with; Open Code's own default name. */
|
|
85
|
+
const OPENCODE_AUTH_USER = 'opencode';
|
|
67
86
|
/** Legacy single-server keys persisted by pre-pool builds — cleaned up once. */
|
|
68
87
|
const LEGACY_DB_KEY = 'opencode.server.url';
|
|
69
88
|
const LEGACY_DB_KEY_DATADIR = 'opencode.server.datadir';
|
|
89
|
+
/** Servers we spawned, so a restart after a crash can still reclaim them. */
|
|
90
|
+
const REGISTRY_DB_KEY = 'opencode.server.registry';
|
|
70
91
|
const HEALTH_TIMEOUT = 1500;
|
|
71
92
|
const SERVER_START_TIMEOUT = 30_000; // 30s — generous for slow devices
|
|
93
|
+
/** Attempts to win a port before giving up — covers losing the allocate→spawn race. */
|
|
94
|
+
const PORT_ATTEMPTS = 3;
|
|
95
|
+
/** How long a server gets to honour SIGTERM before it is killed outright. */
|
|
96
|
+
const KILL_GRACE_MS = 2_000;
|
|
97
|
+
/** How often the pool sweeps itself for idle, superseded and orphaned entries. */
|
|
98
|
+
const MAINTENANCE_INTERVAL_MS = 60_000;
|
|
72
99
|
/**
|
|
73
100
|
* Session-data scope for a stream with no Profile constraint.
|
|
74
101
|
*
|
|
@@ -94,8 +121,12 @@ export interface ServerInstance {
|
|
|
94
121
|
key: string;
|
|
95
122
|
/** Profile shape — identifies the DATA DIR, and is stable across config edits. */
|
|
96
123
|
scopeKey: string;
|
|
124
|
+
/** The spec this server was built for, so its key can be re-resolved without a stream. */
|
|
125
|
+
spec: ServerConfigSpec;
|
|
97
126
|
url: string;
|
|
98
127
|
client: OpencodeClient;
|
|
128
|
+
/** Basic-auth header for the raw `fetch` call sites that bypass the SDK client. */
|
|
129
|
+
authHeaders: Record<string, string>;
|
|
99
130
|
proc: Subprocess | null;
|
|
100
131
|
ownsProcess: boolean;
|
|
101
132
|
lastUsed: number;
|
|
@@ -128,13 +159,16 @@ interface SpawnPlan {
|
|
|
128
159
|
* answered, and which models a custom provider advertises. Everything cheap is
|
|
129
160
|
* assembled per call, so nothing that can change without the database noticing
|
|
130
161
|
* gets to hide behind this cache.
|
|
162
|
+
*
|
|
163
|
+
* `enabledProviders`/`envVars` are deliberately NOT here even though they are
|
|
164
|
+
* config: they derive from the models.dev catalog in `settings`, which no
|
|
165
|
+
* revision trigger watches. Cached, a first run whose catalog had not been
|
|
166
|
+
* fetched yet would spawn every later server with no provider credentials.
|
|
131
167
|
*/
|
|
132
168
|
interface CachedConfig {
|
|
133
169
|
revision: number;
|
|
134
170
|
mcpConfig: Record<string, unknown>;
|
|
135
|
-
enabledProviders: string[];
|
|
136
171
|
providerSection: Record<string, unknown>;
|
|
137
|
-
envVars: Record<string, string>;
|
|
138
172
|
}
|
|
139
173
|
|
|
140
174
|
const pool = new Map<string, ServerInstance>();
|
|
@@ -143,7 +177,9 @@ const initPromises = new Map<string, Promise<ServerInstance>>();
|
|
|
143
177
|
const currentKeyByScope = new Map<string, string>();
|
|
144
178
|
const configCache = new Map<string, CachedConfig>();
|
|
145
179
|
const adoptedScopes = new Set<string>();
|
|
146
|
-
let
|
|
180
|
+
let orphanSweepDone = false;
|
|
181
|
+
let maintenanceTimer: ReturnType<typeof setInterval> | null = null;
|
|
182
|
+
let liveStreamSource: (() => Set<string>) | null = null;
|
|
147
183
|
|
|
148
184
|
/** Short, stable FNV-1a hex hash — folds variable config (e.g. inline agent
|
|
149
185
|
* content) into a compact server-key segment so an edit spawns a fresh server. */
|
|
@@ -165,25 +201,171 @@ async function isServerAlive(url: string): Promise<boolean> {
|
|
|
165
201
|
}
|
|
166
202
|
}
|
|
167
203
|
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
204
|
+
// ============================================================================
|
|
205
|
+
// Processes
|
|
206
|
+
// ============================================================================
|
|
207
|
+
|
|
208
|
+
/**
|
|
209
|
+
* Ask the OS for a free port.
|
|
210
|
+
*
|
|
211
|
+
* `--port=0` cannot be used: Open Code reads it as "try 4096, fall back to an
|
|
212
|
+
* ephemeral port", so the first pooled server always squats the well-known
|
|
213
|
+
* default — taking it from the user's own `opencode serve`, and putting an
|
|
214
|
+
* unauthenticated agent API on a guessable port. Binding here and handing over
|
|
215
|
+
* the number the kernel picked is the only way to get a genuinely arbitrary one.
|
|
216
|
+
*/
|
|
217
|
+
function allocateEphemeralPort(): Promise<number> {
|
|
218
|
+
return new Promise((resolve, reject) => {
|
|
219
|
+
const probe = createServer();
|
|
220
|
+
probe.once('error', reject);
|
|
221
|
+
probe.listen(0, OPENCODE_HOST, () => {
|
|
222
|
+
const address = probe.address();
|
|
223
|
+
const port = typeof address === 'object' && address ? address.port : 0;
|
|
224
|
+
probe.close(() => port ? resolve(port) : reject(new Error('Could not allocate a local port')));
|
|
225
|
+
});
|
|
226
|
+
});
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
/** Servers this build spawned, as last written to the DB. */
|
|
230
|
+
interface RegisteredServer {
|
|
231
|
+
pid: number;
|
|
232
|
+
url: string;
|
|
233
|
+
key: string;
|
|
234
|
+
/**
|
|
235
|
+
* The Clopen process that spawned it. Two Clopen instances share one
|
|
236
|
+
* `app.db`, so without this a second one would read the first's registry at
|
|
237
|
+
* boot and kill servers that are very much in use.
|
|
238
|
+
*/
|
|
239
|
+
ownerPid: number;
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
function readSpawnRegistry(): RegisteredServer[] {
|
|
243
|
+
try {
|
|
244
|
+
const stored = settingsQueries.get(REGISTRY_DB_KEY)?.value;
|
|
245
|
+
const parsed = stored ? JSON.parse(stored) : [];
|
|
246
|
+
return Array.isArray(parsed) ? parsed as RegisteredServer[] : [];
|
|
247
|
+
} catch {
|
|
248
|
+
return [];
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
function writeSpawnRegistry(entries: RegisteredServer[]): void {
|
|
253
|
+
try {
|
|
254
|
+
settingsQueries.set(REGISTRY_DB_KEY, JSON.stringify(entries));
|
|
255
|
+
} catch (error) {
|
|
256
|
+
debug.warn('engine', 'Open Code: could not persist the spawn registry', error);
|
|
257
|
+
}
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
function registerSpawnedServer(entry: RegisteredServer): void {
|
|
261
|
+
writeSpawnRegistry([...readSpawnRegistry().filter(existing => existing.pid !== entry.pid), entry]);
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
function unregisterSpawnedServer(pid: number): void {
|
|
265
|
+
writeSpawnRegistry(readSpawnRegistry().filter(existing => existing.pid !== pid));
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
/** Whether a pid is currently running (regardless of what it is). */
|
|
269
|
+
function processAlive(pid: number): boolean {
|
|
270
|
+
try {
|
|
271
|
+
process.kill(pid, 0);
|
|
272
|
+
return true;
|
|
273
|
+
} catch {
|
|
274
|
+
return false;
|
|
275
|
+
}
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
/**
|
|
279
|
+
* Whether `pid` is still one of our Open Code servers.
|
|
280
|
+
*
|
|
281
|
+
* A pid alone is not enough to kill on: the OS recycles them, and a registry
|
|
282
|
+
* entry can outlive its process by days. The command line has to confirm it.
|
|
283
|
+
*/
|
|
284
|
+
async function isOpenCodeProcess(pid: number): Promise<boolean> {
|
|
285
|
+
if (!processAlive(pid)) return false;
|
|
286
|
+
const command = process.platform === 'win32'
|
|
287
|
+
? ['tasklist', '/FI', `PID eq ${pid}`, '/FO', 'CSV', '/NH']
|
|
288
|
+
: ['ps', '-p', String(pid), '-o', 'command='];
|
|
289
|
+
try {
|
|
290
|
+
const probe = Bun.spawn(command, { stdout: 'pipe', stderr: 'ignore' });
|
|
291
|
+
const output = (await new Response(probe.stdout).text()).toLowerCase();
|
|
292
|
+
await probe.exited;
|
|
293
|
+
return output.includes('opencode') && (process.platform === 'win32' || output.includes('serve'));
|
|
294
|
+
} catch {
|
|
295
|
+
return false;
|
|
296
|
+
}
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
/**
|
|
300
|
+
* Kill servers left behind by a previous run.
|
|
301
|
+
*
|
|
302
|
+
* Graceful shutdown disposes the pool, but a crash — or the 5s force-exit that
|
|
303
|
+
* guards `bun --watch` restarts — does not. Without this the orphan keeps its
|
|
304
|
+
* port and its data-dir lock, and nothing in a fresh process can even see it.
|
|
305
|
+
*/
|
|
306
|
+
async function sweepOrphanedServers(): Promise<void> {
|
|
307
|
+
if (orphanSweepDone) return;
|
|
308
|
+
orphanSweepDone = true;
|
|
309
|
+
|
|
310
|
+
const legacyUrl = settingsQueries.get(LEGACY_DB_KEY)?.value;
|
|
311
|
+
if (legacyUrl) {
|
|
174
312
|
try {
|
|
175
|
-
await fetch(`${
|
|
313
|
+
await fetch(`${legacyUrl}/shutdown`, { method: 'POST', signal: AbortSignal.timeout(2000) });
|
|
176
314
|
} catch { /* endpoint may not exist / already dead */ }
|
|
177
315
|
settingsQueries.delete(LEGACY_DB_KEY);
|
|
178
316
|
settingsQueries.delete(LEGACY_DB_KEY_DATADIR);
|
|
179
|
-
debug.log('engine', `Open Code: shut down legacy single-server (${
|
|
317
|
+
debug.log('engine', `Open Code: shut down legacy single-server (${legacyUrl})`);
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
const registered = readSpawnRegistry();
|
|
321
|
+
if (registered.length === 0) return;
|
|
322
|
+
|
|
323
|
+
const stillOwned: RegisteredServer[] = [];
|
|
324
|
+
for (const entry of registered) {
|
|
325
|
+
// Another live Clopen owns it — leave both the process and its entry alone.
|
|
326
|
+
if (entry.ownerPid !== process.pid && processAlive(entry.ownerPid)) {
|
|
327
|
+
stillOwned.push(entry);
|
|
328
|
+
continue;
|
|
329
|
+
}
|
|
330
|
+
if (!(await isOpenCodeProcess(entry.pid))) continue;
|
|
331
|
+
try {
|
|
332
|
+
process.kill(entry.pid, 'SIGTERM');
|
|
333
|
+
debug.log('engine', `Open Code: killed orphaned server ${entry.url} (pid ${entry.pid}) from a previous run`);
|
|
334
|
+
} catch (error) {
|
|
335
|
+
debug.warn('engine', `Open Code: could not kill orphaned server pid ${entry.pid}`, error);
|
|
336
|
+
}
|
|
180
337
|
}
|
|
338
|
+
writeSpawnRegistry(stillOwned);
|
|
181
339
|
}
|
|
182
340
|
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
341
|
+
/**
|
|
342
|
+
* Stop a server for good: SIGTERM, then SIGKILL if it is still up.
|
|
343
|
+
*
|
|
344
|
+
* Fire-and-forget SIGTERM was not enough — a server that is slow to exit (Open
|
|
345
|
+
* Code checkpoints a large WAL on the way out) keeps its port bound after the
|
|
346
|
+
* pool has already dropped its handle, so nothing can reach it again.
|
|
347
|
+
*/
|
|
348
|
+
async function killInstance(inst: ServerInstance): Promise<void> {
|
|
349
|
+
const pid = inst.proc?.pid;
|
|
350
|
+
if (!inst.ownsProcess || !inst.proc) {
|
|
351
|
+
if (pid) unregisterSpawnedServer(pid);
|
|
352
|
+
return;
|
|
186
353
|
}
|
|
354
|
+
|
|
355
|
+
try { inst.proc.kill(); } catch { /* already gone */ }
|
|
356
|
+
|
|
357
|
+
let graceTimer: ReturnType<typeof setTimeout> | undefined;
|
|
358
|
+
const exited = await Promise.race([
|
|
359
|
+
inst.proc.exited.then(() => true).catch(() => true),
|
|
360
|
+
new Promise<boolean>(resolve => { graceTimer = setTimeout(() => resolve(false), KILL_GRACE_MS); })
|
|
361
|
+
]);
|
|
362
|
+
clearTimeout(graceTimer);
|
|
363
|
+
|
|
364
|
+
if (!exited) {
|
|
365
|
+
debug.warn('engine', `Open Code: server ${inst.url} ignored SIGTERM — sending SIGKILL`);
|
|
366
|
+
try { inst.proc.kill('SIGKILL'); } catch { /* raced */ }
|
|
367
|
+
}
|
|
368
|
+
if (pid) unregisterSpawnedServer(pid);
|
|
187
369
|
}
|
|
188
370
|
|
|
189
371
|
// ============================================================================
|
|
@@ -226,31 +408,37 @@ function dataDirForScope(scopeKey: string): string {
|
|
|
226
408
|
*
|
|
227
409
|
* Commands, subagent files and the AGENTS.md instruction block are written to
|
|
228
410
|
* disk by the per-stream artifact sync, so their CONTENT never appears in the DB
|
|
229
|
-
* and the config revision cannot see it change.
|
|
230
|
-
*
|
|
231
|
-
*
|
|
411
|
+
* and the config revision cannot see it change. Missing paths contribute a
|
|
412
|
+
* stable marker rather than throwing — an engine with no commands yet is normal.
|
|
413
|
+
*
|
|
414
|
+
* Hashes CONTENT, not size + mtime. Every writer that materializes these files
|
|
415
|
+
* runs at every stream start, so keying on mtime made the fingerprint a clock:
|
|
416
|
+
* an identical rewrite moved it, and each turn spawned a new server for config
|
|
417
|
+
* that had not changed. Content is the property that actually matters, and it
|
|
418
|
+
* cannot be moved by a writer that merely runs again.
|
|
232
419
|
*/
|
|
233
420
|
async function artifactFingerprint(): Promise<string> {
|
|
234
421
|
const base = join(getEngineUserConfigDir('opencode'), 'opencode');
|
|
235
422
|
const targets = [join(base, 'command'), join(base, 'agent'), join(base, 'AGENTS.md')];
|
|
236
423
|
const parts: string[] = [];
|
|
237
424
|
|
|
425
|
+
const fileEntry = async (path: string, label: string): Promise<string> => {
|
|
426
|
+
try {
|
|
427
|
+
return `${label}:${hashConfig(await readFile(path, 'utf8'))}`;
|
|
428
|
+
} catch {
|
|
429
|
+
return `${label}:gone`;
|
|
430
|
+
}
|
|
431
|
+
};
|
|
432
|
+
|
|
238
433
|
for (const path of targets) {
|
|
239
434
|
try {
|
|
240
435
|
const info = await stat(path);
|
|
241
436
|
if (info.isDirectory()) {
|
|
242
437
|
const names = (await readdir(path)).sort();
|
|
243
|
-
const entries = await Promise.all(names.map(
|
|
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
|
-
}));
|
|
438
|
+
const entries = await Promise.all(names.map(name => fileEntry(join(path, name), name)));
|
|
251
439
|
parts.push(`${path}[${entries.join('|')}]`);
|
|
252
440
|
} else {
|
|
253
|
-
parts.push(
|
|
441
|
+
parts.push(await fileEntry(path, path));
|
|
254
442
|
}
|
|
255
443
|
} catch {
|
|
256
444
|
parts.push(`${path}:absent`);
|
|
@@ -260,6 +448,23 @@ async function artifactFingerprint(): Promise<string> {
|
|
|
260
448
|
return hashConfig(parts.join('\n'));
|
|
261
449
|
}
|
|
262
450
|
|
|
451
|
+
/**
|
|
452
|
+
* What the shared `clopen-mcp` bridge exposes, as a stable string.
|
|
453
|
+
*
|
|
454
|
+
* The bridge is a SINGLE config entry — one URL, one token — so adding or
|
|
455
|
+
* removing an internal connector changes no baked byte, and the running server
|
|
456
|
+
* would keep serving the tool list it read when it connected (the bridge binds
|
|
457
|
+
* its tool set at MCP-session initialize, and never sends `list_changed`).
|
|
458
|
+
* Folding the exposed set into the signature is what makes an internal toggle
|
|
459
|
+
* reach the engine at all.
|
|
460
|
+
*/
|
|
461
|
+
function internalBridgeExposure(): string {
|
|
462
|
+
return getEnabledServerNames()
|
|
463
|
+
.sort()
|
|
464
|
+
.map(name => `${name}(${getEnabledToolsForServer(name).sort().join(',')})`)
|
|
465
|
+
.join('|');
|
|
466
|
+
}
|
|
467
|
+
|
|
263
468
|
// ============================================================================
|
|
264
469
|
// Config building
|
|
265
470
|
// ============================================================================
|
|
@@ -399,14 +604,10 @@ async function resolveConfig(spec: ServerConfigSpec, scopeKey: string): Promise<
|
|
|
399
604
|
});
|
|
400
605
|
}
|
|
401
606
|
|
|
402
|
-
const providerConfig = generateOpenCodeProviderConfig();
|
|
403
|
-
|
|
404
607
|
const resolved: CachedConfig = {
|
|
405
608
|
revision,
|
|
406
609
|
mcpConfig,
|
|
407
|
-
enabledProviders: providerConfig.enabledProviders,
|
|
408
610
|
providerSection: await buildProviderSection(),
|
|
409
|
-
envVars: providerConfig.envVars,
|
|
410
611
|
};
|
|
411
612
|
configCache.set(scopeKey, resolved);
|
|
412
613
|
return resolved;
|
|
@@ -425,10 +626,14 @@ async function resolveConfig(spec: ServerConfigSpec, scopeKey: string): Promise<
|
|
|
425
626
|
* stream start, so folding its result in at assembly time makes the edit reach
|
|
426
627
|
* the signature the way any other config change does.
|
|
427
628
|
*/
|
|
428
|
-
function assembleConfigContent(
|
|
629
|
+
function assembleConfigContent(
|
|
630
|
+
cached: CachedConfig,
|
|
631
|
+
enabledProviders: string[],
|
|
632
|
+
inlineAgents?: Record<string, OpenCodeInlineAgent>
|
|
633
|
+
): string {
|
|
429
634
|
const mergedConfig: Record<string, unknown> = {};
|
|
430
635
|
if (Object.keys(cached.mcpConfig).length > 0) mergedConfig.mcp = cached.mcpConfig;
|
|
431
|
-
if (
|
|
636
|
+
if (enabledProviders.length > 0) mergedConfig.enabled_providers = enabledProviders;
|
|
432
637
|
if (inlineAgents && Object.keys(inlineAgents).length > 0) mergedConfig.agent = inlineAgents;
|
|
433
638
|
if (Object.keys(cached.providerSection).length > 0) mergedConfig.provider = cached.providerSection;
|
|
434
639
|
return Object.keys(mergedConfig).length > 0 ? JSON.stringify(mergedConfig) : '{}';
|
|
@@ -444,12 +649,17 @@ function assembleConfigContent(cached: CachedConfig, inlineAgents?: Record<strin
|
|
|
444
649
|
async function resolvePlan(spec: ServerConfigSpec): Promise<SpawnPlan> {
|
|
445
650
|
const scopeKey = scopeKeyFor(spec);
|
|
446
651
|
const [config, fingerprint] = await Promise.all([resolveConfig(spec, scopeKey), artifactFingerprint()]);
|
|
447
|
-
|
|
448
|
-
|
|
652
|
+
// Cheap and DB-derived, so it is resolved per call rather than cached — the
|
|
653
|
+
// models.dev catalog it reads lives in `settings`, which bumps no revision.
|
|
654
|
+
const providerConfig = generateOpenCodeProviderConfig();
|
|
655
|
+
const configContent = assembleConfigContent(config, providerConfig.enabledProviders, spec.inlineAgents);
|
|
656
|
+
const signature = hashConfig(
|
|
657
|
+
`${configContent}‖${JSON.stringify(providerConfig.envVars)}‖${fingerprint}‖${internalBridgeExposure()}`
|
|
658
|
+
);
|
|
449
659
|
const key = `${scopeKey}#${signature}`;
|
|
450
660
|
|
|
451
661
|
currentKeyByScope.set(scopeKey, key);
|
|
452
|
-
return { key, scopeKey, configContent, envVars:
|
|
662
|
+
return { key, scopeKey, configContent, envVars: providerConfig.envVars };
|
|
453
663
|
}
|
|
454
664
|
|
|
455
665
|
// ============================================================================
|
|
@@ -476,9 +686,71 @@ function reap(reason: string): void {
|
|
|
476
686
|
if (!superseded && !expired) continue;
|
|
477
687
|
|
|
478
688
|
debug.log('engine', `Open Code: reaping ${superseded ? 'superseded' : 'idle'} server ${inst.url} (${inst.key}) — ${reason}`);
|
|
479
|
-
killInstance(inst);
|
|
689
|
+
void killInstance(inst);
|
|
480
690
|
pool.delete(inst.key);
|
|
481
691
|
}
|
|
692
|
+
if (pool.size === 0) stopMaintenance();
|
|
693
|
+
}
|
|
694
|
+
|
|
695
|
+
/**
|
|
696
|
+
* Sweep the pool on a timer.
|
|
697
|
+
*
|
|
698
|
+
* Reaping used to happen only as a side effect of acquiring or releasing a
|
|
699
|
+
* server, which made both of its rules unenforceable once Open Code went quiet:
|
|
700
|
+
* the idle TTL never came due, and a holder leaked by a torn-down stream pinned
|
|
701
|
+
* its server until the next config change — potentially forever. A server that
|
|
702
|
+
* nothing needs must stop because time passed, not because someone happened to
|
|
703
|
+
* ask for another one.
|
|
704
|
+
*/
|
|
705
|
+
function startMaintenance(): void {
|
|
706
|
+
if (maintenanceTimer || pool.size === 0) return;
|
|
707
|
+
maintenanceTimer = setInterval(() => {
|
|
708
|
+
if (liveStreamSource) reconcileServerHolders(liveStreamSource());
|
|
709
|
+
else reap('idle sweep');
|
|
710
|
+
}, MAINTENANCE_INTERVAL_MS);
|
|
711
|
+
maintenanceTimer.unref?.();
|
|
712
|
+
debug.log('engine', 'Open Code: pool maintenance started');
|
|
713
|
+
}
|
|
714
|
+
|
|
715
|
+
function stopMaintenance(): void {
|
|
716
|
+
if (!maintenanceTimer) return;
|
|
717
|
+
clearInterval(maintenanceTimer);
|
|
718
|
+
maintenanceTimer = null;
|
|
719
|
+
debug.log('engine', 'Open Code: pool empty, maintenance stopped');
|
|
720
|
+
}
|
|
721
|
+
|
|
722
|
+
/**
|
|
723
|
+
* Tell the pool where to read the live stream set. Injected because the stream
|
|
724
|
+
* manager sits above the engine layer and must not be imported from here.
|
|
725
|
+
*/
|
|
726
|
+
export function setLiveStreamSource(source: () => Set<string>): void {
|
|
727
|
+
liveStreamSource = source;
|
|
728
|
+
}
|
|
729
|
+
|
|
730
|
+
/**
|
|
731
|
+
* Re-resolve every pooled server's key so a settled config change makes stale
|
|
732
|
+
* ones reapable immediately.
|
|
733
|
+
*
|
|
734
|
+
* Without this only the default scope was ever revisited: a Profile server kept
|
|
735
|
+
* being its own scope's "current" key, so it was neither superseded nor idle,
|
|
736
|
+
* and it went on running with the config — including the credentials — the user
|
|
737
|
+
* had just replaced. This costs no spawn; it only recomputes keys.
|
|
738
|
+
*/
|
|
739
|
+
export async function revalidatePool(): Promise<void> {
|
|
740
|
+
// One pass per scope, using its most recently spawned server. `resolvePlan`
|
|
741
|
+
// WRITES the scope's current key, so revalidating an older instance after a
|
|
742
|
+
// newer one would hand "current" back to the server being replaced.
|
|
743
|
+
const newestByScope = new Map<string, ServerInstance>();
|
|
744
|
+
for (const inst of pool.values()) newestByScope.set(inst.scopeKey, inst);
|
|
745
|
+
|
|
746
|
+
for (const [scopeKey, inst] of newestByScope) {
|
|
747
|
+
try {
|
|
748
|
+
await resolvePlan(inst.spec);
|
|
749
|
+
} catch (error) {
|
|
750
|
+
debug.warn('engine', `Open Code: could not revalidate scope "${scopeKey}"`, error);
|
|
751
|
+
}
|
|
752
|
+
}
|
|
753
|
+
reap('config revalidation');
|
|
482
754
|
}
|
|
483
755
|
|
|
484
756
|
/**
|
|
@@ -565,7 +837,7 @@ async function adoptLegacyScopeDir(scopeKey: string, dataDir: string): Promise<v
|
|
|
565
837
|
* reaper's grace window covers those.
|
|
566
838
|
*/
|
|
567
839
|
export async function acquireServer(spec: ServerConfigSpec, holderId?: string): Promise<ServerInstance> {
|
|
568
|
-
await
|
|
840
|
+
await sweepOrphanedServers();
|
|
569
841
|
|
|
570
842
|
const plan = await resolvePlan(spec);
|
|
571
843
|
const existing = pool.get(plan.key);
|
|
@@ -576,7 +848,7 @@ export async function acquireServer(spec: ServerConfigSpec, holderId?: string):
|
|
|
576
848
|
reap('server reuse');
|
|
577
849
|
return existing;
|
|
578
850
|
}
|
|
579
|
-
killInstance(existing);
|
|
851
|
+
void killInstance(existing);
|
|
580
852
|
pool.delete(plan.key);
|
|
581
853
|
}
|
|
582
854
|
|
|
@@ -587,9 +859,10 @@ export async function acquireServer(spec: ServerConfigSpec, holderId?: string):
|
|
|
587
859
|
return inst;
|
|
588
860
|
}
|
|
589
861
|
|
|
590
|
-
const
|
|
862
|
+
const pendingSpawn = spawnServer(plan, spec)
|
|
591
863
|
.then(inst => {
|
|
592
864
|
pool.set(plan.key, inst);
|
|
865
|
+
startMaintenance();
|
|
593
866
|
// Only now that a healthy replacement exists is the old one expendable.
|
|
594
867
|
// Spawning before killing means a config that cannot start leaves the
|
|
595
868
|
// user with the previous working server rather than with nothing.
|
|
@@ -597,9 +870,9 @@ export async function acquireServer(spec: ServerConfigSpec, holderId?: string):
|
|
|
597
870
|
return inst;
|
|
598
871
|
})
|
|
599
872
|
.finally(() => { initPromises.delete(plan.key); });
|
|
600
|
-
initPromises.set(plan.key,
|
|
873
|
+
initPromises.set(plan.key, pendingSpawn);
|
|
601
874
|
|
|
602
|
-
const inst = await
|
|
875
|
+
const inst = await pendingSpawn;
|
|
603
876
|
if (holderId) inst.holders.add(holderId);
|
|
604
877
|
return inst;
|
|
605
878
|
}
|
|
@@ -613,8 +886,45 @@ export function releaseServer(key: string, holderId: string): void {
|
|
|
613
886
|
reap('holder released');
|
|
614
887
|
}
|
|
615
888
|
|
|
616
|
-
|
|
617
|
-
|
|
889
|
+
/** True for the one failure worth retrying on a different port: anything but a slow start. */
|
|
890
|
+
function isRetriableSpawnFailure(error: unknown): boolean {
|
|
891
|
+
return !(error instanceof Error && error.message.includes('Timeout waiting for opencode server'));
|
|
892
|
+
}
|
|
893
|
+
|
|
894
|
+
/**
|
|
895
|
+
* Spawn a server, retrying if it loses the race for its port.
|
|
896
|
+
*
|
|
897
|
+
* The port is allocated by binding a socket and handing over the number the
|
|
898
|
+
* kernel picked, so between closing that socket and Open Code binding it there
|
|
899
|
+
* is a window another process can win. An explicit port has no fallback inside
|
|
900
|
+
* Open Code, so the retry is ours to do.
|
|
901
|
+
*/
|
|
902
|
+
async function spawnServer(plan: SpawnPlan, spec: ServerConfigSpec): Promise<ServerInstance> {
|
|
903
|
+
// Random per process: the server exposes an agent API that can run shell
|
|
904
|
+
// commands, and it is unauthenticated unless this is set.
|
|
905
|
+
const password = crypto.randomUUID();
|
|
906
|
+
let lastError: unknown;
|
|
907
|
+
|
|
908
|
+
for (let attempt = 1; attempt <= PORT_ATTEMPTS; attempt++) {
|
|
909
|
+
const port = await allocateEphemeralPort();
|
|
910
|
+
try {
|
|
911
|
+
return await spawnServerOnce(plan, spec, port, password);
|
|
912
|
+
} catch (error) {
|
|
913
|
+
lastError = error;
|
|
914
|
+
if (!isRetriableSpawnFailure(error) || attempt === PORT_ATTEMPTS) throw error;
|
|
915
|
+
debug.warn('engine', `Open Code: spawn on port ${port} failed (attempt ${attempt}/${PORT_ATTEMPTS}), retrying`, error);
|
|
916
|
+
}
|
|
917
|
+
}
|
|
918
|
+
throw lastError;
|
|
919
|
+
}
|
|
920
|
+
|
|
921
|
+
async function spawnServerOnce(
|
|
922
|
+
plan: SpawnPlan,
|
|
923
|
+
spec: ServerConfigSpec,
|
|
924
|
+
port: number,
|
|
925
|
+
password: string
|
|
926
|
+
): Promise<ServerInstance> {
|
|
927
|
+
debug.log('engine', `Spawning Open Code server for key "${plan.key}" on port ${port}...`);
|
|
618
928
|
|
|
619
929
|
// Isolate Open Code state under Clopen's dir (XDG overrides) — never mixes with
|
|
620
930
|
// the user's own CLI usage. CONFIG is shared across pooled servers (commands +
|
|
@@ -637,7 +947,7 @@ async function spawnServer(plan: SpawnPlan): Promise<ServerInstance> {
|
|
|
637
947
|
'Open Code is missing its CLI. Open Settings → Stack to install it before using this engine.'
|
|
638
948
|
);
|
|
639
949
|
}
|
|
640
|
-
const args = [cli.path, 'serve', `--hostname=${OPENCODE_HOST}`,
|
|
950
|
+
const args = [cli.path, 'serve', `--hostname=${OPENCODE_HOST}`, `--port=${port}`];
|
|
641
951
|
|
|
642
952
|
const proc = Bun.spawn(args, {
|
|
643
953
|
stdout: 'pipe',
|
|
@@ -650,6 +960,10 @@ async function spawnServer(plan: SpawnPlan): Promise<ServerInstance> {
|
|
|
650
960
|
XDG_STATE_HOME: dataDir,
|
|
651
961
|
XDG_CACHE_HOME: dataDir,
|
|
652
962
|
OPENCODE_CONFIG_CONTENT: plan.configContent,
|
|
963
|
+
// Set explicitly so an inherited value from the user's shell cannot
|
|
964
|
+
// leave us holding a password the server did not start with.
|
|
965
|
+
OPENCODE_SERVER_USERNAME: OPENCODE_AUTH_USER,
|
|
966
|
+
OPENCODE_SERVER_PASSWORD: password,
|
|
653
967
|
},
|
|
654
968
|
});
|
|
655
969
|
|
|
@@ -690,14 +1004,21 @@ async function spawnServer(plan: SpawnPlan): Promise<ServerInstance> {
|
|
|
690
1004
|
});
|
|
691
1005
|
});
|
|
692
1006
|
|
|
1007
|
+
// Applies to the SSE event stream too — the SDK merges client-level headers
|
|
1008
|
+
// into every request, including `event.subscribe`.
|
|
1009
|
+
const authHeaders = { Authorization: `Basic ${btoa(`${OPENCODE_AUTH_USER}:${password}`)}` };
|
|
693
1010
|
const { createOpencodeClient } = await loadEngineSdk<typeof import('@opencode-ai/sdk')>('opencode', '@opencode-ai/sdk');
|
|
694
|
-
const client = createOpencodeClient({ baseUrl: url });
|
|
1011
|
+
const client = createOpencodeClient({ baseUrl: url, headers: authHeaders });
|
|
1012
|
+
|
|
1013
|
+
if (proc.pid) registerSpawnedServer({ pid: proc.pid, url, key: plan.key, ownerPid: process.pid });
|
|
695
1014
|
debug.log('engine', `Open Code server ready (key "${plan.key}", ${url}, data dir: ${dataDir})`);
|
|
696
1015
|
return {
|
|
697
1016
|
key: plan.key,
|
|
698
1017
|
scopeKey: plan.scopeKey,
|
|
1018
|
+
spec,
|
|
699
1019
|
url,
|
|
700
1020
|
client,
|
|
1021
|
+
authHeaders,
|
|
701
1022
|
proc,
|
|
702
1023
|
ownsProcess: true,
|
|
703
1024
|
lastUsed: Date.now(),
|
|
@@ -705,28 +1026,6 @@ async function spawnServer(plan: SpawnPlan): Promise<ServerInstance> {
|
|
|
705
1026
|
};
|
|
706
1027
|
}
|
|
707
1028
|
|
|
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
1029
|
/** The scopes currently backed by a pooled server, for warm-up. */
|
|
731
1030
|
export function pooledScopeKeys(): string[] {
|
|
732
1031
|
return [...new Set([...pool.values()].map(s => s.scopeKey))];
|
|
@@ -740,18 +1039,17 @@ export async function ensureClient(): Promise<OpencodeClient> {
|
|
|
740
1039
|
return (await acquireServer({})).client;
|
|
741
1040
|
}
|
|
742
1041
|
|
|
743
|
-
/**
|
|
744
|
-
|
|
745
|
-
|
|
746
|
-
|
|
747
|
-
|
|
748
|
-
|
|
749
|
-
|
|
750
|
-
|
|
751
|
-
export function getServerUrl(): string | null {
|
|
1042
|
+
/**
|
|
1043
|
+
* The DEFAULT server, if up — for callers with no stream context.
|
|
1044
|
+
*
|
|
1045
|
+
* Returns the instance rather than a bare url or client because the raw
|
|
1046
|
+
* `fetch` call sites need its auth header too, and a url without the header
|
|
1047
|
+
* that goes with it is a 401 waiting to happen.
|
|
1048
|
+
*/
|
|
1049
|
+
export function getDefaultServer(): ServerInstance | null {
|
|
752
1050
|
const inst = defaultInstance();
|
|
753
1051
|
if (inst) inst.lastUsed = Date.now();
|
|
754
|
-
return inst
|
|
1052
|
+
return inst ?? null;
|
|
755
1053
|
}
|
|
756
1054
|
|
|
757
1055
|
function defaultInstance(): ServerInstance | undefined {
|
|
@@ -769,13 +1067,21 @@ function defaultInstance(): ServerInstance | undefined {
|
|
|
769
1067
|
* Dispose the whole pool. `forRestart` is accepted for signature compatibility
|
|
770
1068
|
* with the previous single-server API; every pooled server we own is killed
|
|
771
1069
|
* either way (there is no external-server-reuse path anymore).
|
|
1070
|
+
*
|
|
1071
|
+
* Kills run concurrently and are awaited: shutdown is bounded by one grace
|
|
1072
|
+
* period, and a child process that outlives us keeps both its port and its
|
|
1073
|
+
* data-dir lock.
|
|
772
1074
|
*/
|
|
773
1075
|
export async function disposeOpenCodeClient(_forRestart = false): Promise<void> {
|
|
774
|
-
|
|
1076
|
+
stopMaintenance();
|
|
1077
|
+
await Promise.all([...pool.values()].map(inst => killInstance(inst)));
|
|
775
1078
|
pool.clear();
|
|
776
1079
|
initPromises.clear();
|
|
777
1080
|
currentKeyByScope.clear();
|
|
778
1081
|
configCache.clear();
|
|
1082
|
+
// Nothing of OURS is running any more. Stated rather than derived, because the
|
|
1083
|
+
// per-kill updates race each other — but another Clopen's entries stay.
|
|
1084
|
+
writeSpawnRegistry(readSpawnRegistry().filter(entry => entry.ownerPid !== process.pid));
|
|
779
1085
|
settingsQueries.delete(LEGACY_DB_KEY);
|
|
780
1086
|
settingsQueries.delete(LEGACY_DB_KEY_DATADIR);
|
|
781
1087
|
debug.log('engine', 'Open Code pool disposed');
|