@myrialabs/clopen 0.4.7 → 0.4.9
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/detect.ts +129 -0
- package/backend/artifacts/engine-map.ts +53 -0
- package/backend/artifacts/frontmatter.ts +68 -0
- package/backend/artifacts/generate.ts +105 -0
- package/backend/artifacts/index.ts +34 -0
- package/backend/artifacts/markers.ts +76 -0
- package/backend/artifacts/matrix.ts +247 -0
- package/backend/artifacts/slug.ts +35 -0
- package/backend/artifacts/sync.ts +130 -0
- package/backend/artifacts/types.ts +152 -0
- package/backend/auth/permissions.ts +51 -1
- package/backend/chat/stream-manager.ts +14 -1
- package/backend/commands/detect.ts +25 -0
- package/backend/commands/index.ts +9 -0
- package/backend/commands/service.ts +178 -0
- package/backend/commands/store.ts +45 -0
- package/backend/commands/sync.ts +94 -0
- package/backend/database/migrations/045_create_commands_table.ts +28 -0
- package/backend/database/migrations/046_create_subagents_table.ts +29 -0
- package/backend/database/migrations/047_create_instructions_table.ts +29 -0
- package/backend/database/migrations/048_add_mcp_tool_overrides.ts +23 -0
- package/backend/database/migrations/049_create_permission_sets_table.ts +50 -0
- package/backend/database/migrations/050_create_profiles_tables.ts +57 -0
- package/backend/database/migrations/051_add_profile_to_sessions.ts +20 -0
- package/backend/database/migrations/052_add_default_profile_to_projects.ts +20 -0
- package/backend/database/migrations/053_add_profile_to_permission_sets.ts +37 -0
- package/backend/database/migrations/054_drop_subagent_agent_type.ts +20 -0
- package/backend/database/migrations/055_artifact_model_tools_per_engine.ts +43 -0
- package/backend/database/migrations/index.ts +77 -0
- package/backend/database/queries/command-queries.ts +82 -0
- package/backend/database/queries/index.ts +12 -2
- package/backend/database/queries/instruction-queries.ts +62 -0
- package/backend/database/queries/mcp-server-queries.ts +25 -0
- package/backend/database/queries/permission-set-queries.ts +155 -0
- package/backend/database/queries/profile-queries.ts +118 -0
- package/backend/database/queries/project-queries.ts +14 -0
- package/backend/database/queries/session-queries.ts +10 -0
- package/backend/database/queries/subagent-queries.ts +92 -0
- package/backend/db-client/drivers/mysql.ts +21 -0
- package/backend/db-client/drivers/postgres.ts +20 -0
- package/backend/db-client/drivers/sqlite.ts +21 -0
- package/backend/db-client/drivers/types.ts +19 -0
- package/backend/db-client/query-executor.ts +89 -1
- package/backend/engine/adapters/claude/stream.ts +27 -3
- package/backend/engine/adapters/codex/stream.ts +46 -14
- package/backend/engine/adapters/copilot/stream.ts +58 -4
- package/backend/engine/adapters/opencode/message-converter.ts +22 -2
- package/backend/engine/adapters/opencode/server.ts +166 -210
- package/backend/engine/adapters/opencode/stream.ts +150 -24
- package/backend/engine/adapters/qwen/stream.ts +23 -3
- package/backend/engine/artifact-sync.ts +51 -0
- package/backend/engine/types.ts +6 -0
- package/backend/instructions/index.ts +8 -0
- package/backend/instructions/service.ts +63 -0
- package/backend/instructions/sync.ts +56 -0
- package/backend/mcp/external/config.ts +42 -20
- package/backend/mcp/external/proxy.ts +89 -5
- package/backend/mcp/external/tools.ts +88 -0
- package/backend/mcp/index.ts +38 -15
- package/backend/mcp/internal/config.ts +48 -11
- package/backend/mcp/internal/remote-server.ts +9 -1
- package/backend/permissions/index.ts +27 -0
- package/backend/permissions/materialize.ts +96 -0
- package/backend/permissions/resolve.test.ts +162 -0
- package/backend/permissions/resolve.ts +106 -0
- package/backend/permissions/service.ts +167 -0
- package/backend/profiles/index.ts +10 -0
- package/backend/profiles/service.ts +169 -0
- package/backend/skills/index.ts +1 -1
- package/backend/skills/sync.ts +88 -128
- package/backend/subagents/detect.ts +23 -0
- package/backend/subagents/index.ts +10 -0
- package/backend/subagents/service.ts +166 -0
- package/backend/subagents/store.ts +44 -0
- package/backend/subagents/sync.ts +144 -0
- package/backend/ws/artifacts/generate.ts +51 -0
- package/backend/ws/artifacts/index.ts +8 -0
- package/backend/ws/chat/stream.ts +33 -2
- package/backend/ws/commands/crud.ts +157 -0
- package/backend/ws/commands/index.ts +8 -0
- package/backend/ws/db-client/query-history-retention.test.ts +217 -0
- package/backend/ws/db-client/query.ts +77 -2
- package/backend/ws/git/branch.ts +4 -2
- package/backend/ws/git/ignored.ts +65 -0
- package/backend/ws/git/index.ts +3 -1
- package/backend/ws/git/remote.ts +21 -11
- package/backend/ws/index.ts +17 -1
- package/backend/ws/instructions/crud.ts +53 -0
- package/backend/ws/instructions/index.ts +8 -0
- package/backend/ws/mcp/crud.ts +7 -1
- package/backend/ws/mcp/index.ts +4 -1
- package/backend/ws/mcp/tools.ts +112 -0
- package/backend/ws/permissions/crud.ts +72 -0
- package/backend/ws/permissions/index.ts +8 -0
- package/backend/ws/profiles/crud.ts +149 -0
- package/backend/ws/profiles/index.ts +9 -0
- package/backend/ws/subagents/crud.ts +136 -0
- package/backend/ws/subagents/index.ts +8 -0
- package/dist/assets/__vite-browser-external-BIHI7g3E.js +1 -0
- package/dist/assets/index-BdRui-1z.js +1 -0
- package/dist/assets/{index-xrB3zcfA.js → index-BjaIjmd4.js} +1 -1
- package/dist/assets/{main-LBI3a0n5.js → main-Cf8SUfQ1.js} +387 -302
- package/dist/assets/main-D4pdkiQK.css +1 -0
- package/dist/assets/zipkit-engine-CaR0t_Uy.wasm +0 -0
- package/dist/index.html +2 -2
- package/package.json +1 -1
- package/shared/constants/engine-tools.ts +56 -0
- package/shared/types/database/schema.ts +2 -0
- package/shared/types/db-client/query.ts +33 -0
- package/shared/types/stores/settings.ts +15 -0
- package/shared/types/unified/stream.ts +7 -0
- package/shared/utils/db-client/split-sql.test.ts +88 -0
- package/shared/utils/db-client/split-sql.ts +132 -0
- package/shared/utils/logger.ts +6 -0
- package/dist/assets/main-BXS8bjJ6.css +0 -1
|
@@ -42,6 +42,7 @@ import type {
|
|
|
42
42
|
ReadMcpResourceInput,
|
|
43
43
|
TodoWriteInput,
|
|
44
44
|
PatchInput,
|
|
45
|
+
AgentInput,
|
|
45
46
|
} from '$shared/types/unified';
|
|
46
47
|
|
|
47
48
|
// ============================================================
|
|
@@ -87,7 +88,7 @@ type NormalizedToolInput =
|
|
|
87
88
|
| GlobInput | GrepInput | WebFetchInput | WebSearchInput
|
|
88
89
|
| AskUserQuestionInput | TodoWriteInput
|
|
89
90
|
| ListMcpResourcesInput | ReadMcpResourceInput
|
|
90
|
-
| PatchInput
|
|
91
|
+
| PatchInput | AgentInput
|
|
91
92
|
| Record<string, unknown>;
|
|
92
93
|
|
|
93
94
|
// ============================================================
|
|
@@ -103,7 +104,7 @@ type NormalizedToolInput =
|
|
|
103
104
|
*
|
|
104
105
|
* @see https://opencode.ai/docs/tools
|
|
105
106
|
*/
|
|
106
|
-
const TOOL_NAME_MAP: Record<string, string> = {
|
|
107
|
+
export const TOOL_NAME_MAP: Record<string, string> = {
|
|
107
108
|
// File operations
|
|
108
109
|
'bash': 'Bash',
|
|
109
110
|
'view': 'Read',
|
|
@@ -340,6 +341,24 @@ function normalizePatchInput(raw: OCToolInput): PatchInput {
|
|
|
340
341
|
return { filePath, patch: patchBody };
|
|
341
342
|
}
|
|
342
343
|
|
|
344
|
+
/**
|
|
345
|
+
* OpenCode's `task` tool dispatches a named sub-agent. Some providers (e.g.
|
|
346
|
+
* GLM/z.ai via opencode) emit already-snake_case args like `subagent_type`.
|
|
347
|
+
* Map those to the unified `AgentInput` so the Agent tool component renders
|
|
348
|
+
* consistently with Claude's `Task` and Copilot's `task`.
|
|
349
|
+
*/
|
|
350
|
+
function normalizeAgentInput(raw: OCToolInput): AgentInput {
|
|
351
|
+
return {
|
|
352
|
+
prompt: str(raw, 'prompt', 'prompt') || str(raw, 'task', 'task') || str(raw, 'instruction', 'instruction'),
|
|
353
|
+
description: str(raw, 'description', 'description'),
|
|
354
|
+
subagentType: optStr(raw, 'subagent_type', 'subagentType')
|
|
355
|
+
?? optStr(raw, 'agent_type', 'agentType')
|
|
356
|
+
?? optStr(raw, 'agent', 'agent')
|
|
357
|
+
?? optStr(raw, 'name', 'name')
|
|
358
|
+
?? 'general-purpose',
|
|
359
|
+
};
|
|
360
|
+
}
|
|
361
|
+
|
|
343
362
|
// ============================================================
|
|
344
363
|
// Normalizer Dispatcher
|
|
345
364
|
// ============================================================
|
|
@@ -368,6 +387,7 @@ function normalizeToolInput(claudeToolName: string, raw: OCToolInput): Normalize
|
|
|
368
387
|
case 'ReadMcpResource': return normalizeReadMcpResourceInput(raw);
|
|
369
388
|
case 'TodoWrite': return normalizeTodoWriteInput(raw);
|
|
370
389
|
case 'Patch': return normalizePatchInput(raw);
|
|
390
|
+
case 'Agent': return normalizeAgentInput(raw);
|
|
371
391
|
default: {
|
|
372
392
|
// Unknown tool: generic camelCase → snake_case key normalization
|
|
373
393
|
const normalized: Record<string, string | number | boolean> = {};
|
|
@@ -1,48 +1,78 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* Open Code Server & Client
|
|
2
|
+
* Open Code Server & Client Pool
|
|
3
3
|
*
|
|
4
|
-
*
|
|
5
|
-
*
|
|
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.
|
|
6
11
|
*
|
|
7
|
-
* Strategy:
|
|
8
|
-
* 1.
|
|
9
|
-
* 2. Otherwise spawn `opencode serve`
|
|
10
|
-
*
|
|
11
|
-
*
|
|
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.
|
|
17
|
+
*
|
|
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).
|
|
12
22
|
*/
|
|
13
23
|
|
|
24
|
+
import { join } from 'path';
|
|
14
25
|
import type { OpencodeClient } from '@opencode-ai/sdk';
|
|
15
26
|
import type { Subprocess } from 'bun';
|
|
16
27
|
import { getOpenCodeMcpConfig } from '../../../mcp';
|
|
17
28
|
import { settingsQueries } from '../../../database/queries';
|
|
18
29
|
import { generateOpenCodeProviderConfig } from './config';
|
|
30
|
+
import type { OpenCodeInlineAgent } from '$backend/subagents';
|
|
19
31
|
import { resolveBinaryWithRefresh } from '$backend/utils/cli';
|
|
20
32
|
import { getEngineUserConfigDir } from '$backend/utils/paths';
|
|
21
33
|
import { debug } from '$shared/utils/logger';
|
|
22
34
|
|
|
23
35
|
const OPENCODE_HOST = '127.0.0.1';
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
// update that moves the isolation path, or a server left over from before
|
|
28
|
-
// isolation existed) we must NOT reuse it — respawn into the right dir instead.
|
|
29
|
-
const DB_KEY_DATADIR = 'opencode.server.datadir';
|
|
36
|
+
/** Legacy single-server keys persisted by pre-pool builds — cleaned up once. */
|
|
37
|
+
const LEGACY_DB_KEY = 'opencode.server.url';
|
|
38
|
+
const LEGACY_DB_KEY_DATADIR = 'opencode.server.datadir';
|
|
30
39
|
const HEALTH_TIMEOUT = 1500;
|
|
31
40
|
const SERVER_START_TIMEOUT = 30_000; // 30s — generous for slow devices
|
|
41
|
+
/** Config signature for a stream with no Profile constraint. */
|
|
42
|
+
export const DEFAULT_SERVER_KEY = '*|*';
|
|
43
|
+
/** Max concurrently-pooled Profile servers (the default server is never evicted). */
|
|
44
|
+
const MAX_POOL_SERVERS = 4;
|
|
45
|
+
|
|
46
|
+
export interface ServerInstance {
|
|
47
|
+
key: string;
|
|
48
|
+
url: string;
|
|
49
|
+
client: OpencodeClient;
|
|
50
|
+
proc: Subprocess | null;
|
|
51
|
+
ownsProcess: boolean;
|
|
52
|
+
lastUsed: number;
|
|
53
|
+
}
|
|
32
54
|
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
55
|
+
/** What distinguishes one Profile's server from another. */
|
|
56
|
+
export interface ServerConfigSpec {
|
|
57
|
+
/** Allowed MCP connector slugs (undefined = unconstrained → all enabled). */
|
|
58
|
+
mcpProfileFilter?: Set<string>;
|
|
59
|
+
/** Inline agent definitions (undefined/empty = the engine's default set). */
|
|
60
|
+
inlineAgents?: Record<string, OpenCodeInlineAgent>;
|
|
61
|
+
}
|
|
39
62
|
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
63
|
+
const pool = new Map<string, ServerInstance>();
|
|
64
|
+
const initPromises = new Map<string, Promise<ServerInstance>>();
|
|
65
|
+
let legacyCleaned = false;
|
|
66
|
+
|
|
67
|
+
/** Short, stable FNV-1a hex hash — folds variable config (e.g. inline agent
|
|
68
|
+
* content) into a compact server-key segment so an edit spawns a fresh server. */
|
|
69
|
+
export function hashConfig(s: string): string {
|
|
70
|
+
let h = 0x811c9dc5;
|
|
71
|
+
for (let i = 0; i < s.length; i++) {
|
|
72
|
+
h ^= s.charCodeAt(i);
|
|
73
|
+
h = Math.imul(h, 0x01000193);
|
|
74
|
+
}
|
|
75
|
+
return (h >>> 0).toString(16);
|
|
46
76
|
}
|
|
47
77
|
|
|
48
78
|
async function isServerAlive(url: string): Promise<boolean> {
|
|
@@ -54,109 +84,92 @@ async function isServerAlive(url: string): Promise<boolean> {
|
|
|
54
84
|
}
|
|
55
85
|
}
|
|
56
86
|
|
|
57
|
-
/**
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
*/
|
|
70
|
-
export async function ensureClient(): Promise<OpencodeClient> {
|
|
71
|
-
// Wait for any in-progress init first
|
|
72
|
-
if (initPromise) {
|
|
73
|
-
try { await initPromise; } catch { /* handled below */ }
|
|
74
|
-
if (client && ready) return client;
|
|
75
|
-
}
|
|
76
|
-
|
|
77
|
-
// Fast path: server is up and healthy
|
|
78
|
-
if (client && ready && serverHandle) {
|
|
79
|
-
if (await isServerAlive(serverHandle.url)) return client;
|
|
80
|
-
|
|
81
|
-
// Server disconnected — purge stale DB entry
|
|
82
|
-
// Do NOT clear initPromise — another caller may have started one
|
|
83
|
-
debug.log('engine', 'Open Code server disconnected, recovering...');
|
|
84
|
-
settingsQueries.delete(DB_KEY);
|
|
85
|
-
settingsQueries.delete(DB_KEY_DATADIR);
|
|
86
|
-
clearClientState();
|
|
87
|
+
/** One-time shutdown of a server spawned by an older single-server build. */
|
|
88
|
+
async function cleanupLegacyServer(): Promise<void> {
|
|
89
|
+
if (legacyCleaned) return;
|
|
90
|
+
legacyCleaned = true;
|
|
91
|
+
const stored = settingsQueries.get(LEGACY_DB_KEY)?.value;
|
|
92
|
+
if (stored) {
|
|
93
|
+
try {
|
|
94
|
+
await fetch(`${stored}/shutdown`, { method: 'POST', signal: AbortSignal.timeout(2000) });
|
|
95
|
+
} catch { /* endpoint may not exist / already dead */ }
|
|
96
|
+
settingsQueries.delete(LEGACY_DB_KEY);
|
|
97
|
+
settingsQueries.delete(LEGACY_DB_KEY_DATADIR);
|
|
98
|
+
debug.log('engine', `Open Code: shut down legacy single-server (${stored})`);
|
|
87
99
|
}
|
|
100
|
+
}
|
|
88
101
|
|
|
89
|
-
|
|
90
|
-
if (
|
|
91
|
-
try {
|
|
92
|
-
if (client && ready) return client;
|
|
102
|
+
function killInstance(inst: ServerInstance): void {
|
|
103
|
+
if (inst.ownsProcess && inst.proc) {
|
|
104
|
+
try { inst.proc.kill(); } catch { /* already gone */ }
|
|
93
105
|
}
|
|
106
|
+
}
|
|
94
107
|
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
108
|
+
/** Evict the least-recently-used PROFILE server when the pool is over cap. */
|
|
109
|
+
function evictIfNeeded(): void {
|
|
110
|
+
const evictable = [...pool.values()].filter(s => s.key !== DEFAULT_SERVER_KEY);
|
|
111
|
+
if (evictable.length <= MAX_POOL_SERVERS) return;
|
|
112
|
+
evictable.sort((a, b) => a.lastUsed - b.lastUsed);
|
|
113
|
+
for (const victim of evictable.slice(0, evictable.length - MAX_POOL_SERVERS)) {
|
|
114
|
+
debug.log('engine', `Open Code: evicting idle Profile server (${victim.key}) at ${victim.url}`);
|
|
115
|
+
killInstance(victim);
|
|
116
|
+
pool.delete(victim.key);
|
|
103
117
|
}
|
|
104
118
|
}
|
|
105
119
|
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
120
|
+
/**
|
|
121
|
+
* Get (or spawn) the pooled Open Code server for a config signature. The `spec`
|
|
122
|
+
* is only consulted when a server for `key` must be spawned; callers must pass a
|
|
123
|
+
* `key` that uniquely captures the spec (see the adapter's signature builder).
|
|
124
|
+
*/
|
|
125
|
+
export async function ensureServer(key: string, spec: ServerConfigSpec): Promise<ServerInstance> {
|
|
126
|
+
await cleanupLegacyServer();
|
|
127
|
+
|
|
128
|
+
const existing = pool.get(key);
|
|
129
|
+
if (existing) {
|
|
130
|
+
if (await isServerAlive(existing.url)) {
|
|
131
|
+
existing.lastUsed = Date.now();
|
|
132
|
+
return existing;
|
|
133
|
+
}
|
|
134
|
+
killInstance(existing);
|
|
135
|
+
pool.delete(key);
|
|
136
|
+
}
|
|
116
137
|
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
138
|
+
const inFlight = initPromises.get(key);
|
|
139
|
+
if (inFlight) return inFlight;
|
|
140
|
+
|
|
141
|
+
const p = spawnServer(key, spec)
|
|
142
|
+
.then(inst => {
|
|
143
|
+
pool.set(key, inst);
|
|
144
|
+
evictIfNeeded();
|
|
145
|
+
return inst;
|
|
146
|
+
})
|
|
147
|
+
.finally(() => { initPromises.delete(key); });
|
|
148
|
+
initPromises.set(key, p);
|
|
149
|
+
return p;
|
|
150
|
+
}
|
|
125
151
|
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
client = createOpencodeClient({ baseUrl: stored.value });
|
|
129
|
-
serverHandle = { url: stored.value, close() {} };
|
|
130
|
-
ownsProcess = false;
|
|
131
|
-
ready = true;
|
|
132
|
-
debug.log('engine', `Reusing existing Open Code server at ${stored.value}`);
|
|
133
|
-
return;
|
|
134
|
-
}
|
|
152
|
+
async function spawnServer(key: string, spec: ServerConfigSpec): Promise<ServerInstance> {
|
|
153
|
+
debug.log('engine', `Spawning Open Code server for key "${key}"...`);
|
|
135
154
|
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
155
|
+
// Isolate Open Code state under Clopen's dir (XDG overrides) — never mixes with
|
|
156
|
+
// the user's own CLI usage. CONFIG is shared across pooled servers (commands +
|
|
157
|
+
// instructions live there; agents come INLINE via OPENCODE_CONFIG_CONTENT, not
|
|
158
|
+
// the on-disk agent dir). DATA/STATE/CACHE (incl. opencode.db, sessions,
|
|
159
|
+
// snapshots) are per-key so concurrent Profile servers never share one SQLite
|
|
160
|
+
// db. The DEFAULT server keeps the base dir for back-compat with old sessions.
|
|
161
|
+
const configDir = getEngineUserConfigDir('opencode');
|
|
162
|
+
const dataDir = key === DEFAULT_SERVER_KEY
|
|
163
|
+
? configDir
|
|
164
|
+
: join(configDir, 'pool', Buffer.from(key).toString('base64url'));
|
|
144
165
|
|
|
145
|
-
// 2. Spawn a new server via Bun.spawn with absolute binary path.
|
|
146
|
-
// Re-harvest PATH and fall back to known install locations so freshly
|
|
147
|
-
// installed binaries are picked up without a clopen restart.
|
|
148
166
|
const command = await resolveBinaryWithRefresh('opencode');
|
|
149
167
|
if (!command) throw new Error('opencode binary not found on PATH');
|
|
150
168
|
const args = [command, 'serve', `--hostname=${OPENCODE_HOST}`, '--port=0'];
|
|
151
169
|
|
|
152
|
-
//
|
|
153
|
-
//
|
|
154
|
-
|
|
155
|
-
// unreachable/slow remote endpoint can stall startup. Drop ONLY the
|
|
156
|
-
// unreachable remote entries; stdio/local servers (no `url`) are independent
|
|
157
|
-
// of the HTTP bridge and must always survive — they were previously thrown
|
|
158
|
-
// out together with the bridge when it wasn't reachable yet.
|
|
159
|
-
const mcpConfig = getOpenCodeMcpConfig();
|
|
170
|
+
// MCP: only inject remote servers whose endpoint is reachable — an unreachable
|
|
171
|
+
// remote can stall startup. stdio/local servers (no `url`) always survive.
|
|
172
|
+
const mcpConfig = getOpenCodeMcpConfig(spec.mcpProfileFilter);
|
|
160
173
|
if (Object.keys(mcpConfig).length > 0) {
|
|
161
174
|
const entries = Object.entries(mcpConfig);
|
|
162
175
|
const reachability = await Promise.all(
|
|
@@ -167,36 +180,22 @@ async function init(): Promise<void> {
|
|
|
167
180
|
);
|
|
168
181
|
entries.forEach(([name, config], i) => {
|
|
169
182
|
if (reachability[i]) {
|
|
170
|
-
debug.log('engine', `Open Code
|
|
183
|
+
debug.log('engine', `Open Code[${key}]: MCP → ${name}: ${config.type} (${(config as any).url || (config as any).command?.join(' ')})`);
|
|
171
184
|
} else {
|
|
172
|
-
debug.warn('engine', `Open Code
|
|
185
|
+
debug.warn('engine', `Open Code[${key}]: MCP endpoint for "${name}" not reachable, skipping it`);
|
|
173
186
|
delete mcpConfig[name];
|
|
174
187
|
}
|
|
175
188
|
});
|
|
176
189
|
}
|
|
177
190
|
|
|
178
|
-
// Build provider config from DB (enabled providers + env vars)
|
|
179
191
|
const providerConfig = generateOpenCodeProviderConfig();
|
|
180
|
-
if (providerConfig.enabledProviders.length > 0) {
|
|
181
|
-
debug.log('engine', `Open Code server: enabling ${providerConfig.enabledProviders.length} provider(s): ${providerConfig.enabledProviders.join(', ')}`);
|
|
182
|
-
}
|
|
183
|
-
if (Object.keys(providerConfig.envVars).length > 0) {
|
|
184
|
-
debug.log('engine', `Open Code server: injecting ${Object.keys(providerConfig.envVars).length} env var(s): ${Object.keys(providerConfig.envVars).join(', ')}`);
|
|
185
|
-
}
|
|
186
192
|
|
|
187
|
-
// Merge MCP
|
|
193
|
+
// Merge MCP + providers + inline agents into a single OPENCODE_CONFIG_CONTENT.
|
|
188
194
|
const mergedConfig: Record<string, unknown> = {};
|
|
189
|
-
if (Object.keys(mcpConfig).length > 0)
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
mergedConfig.enabled_providers = providerConfig.enabledProviders;
|
|
194
|
-
}
|
|
195
|
-
const configContent = Object.keys(mergedConfig).length > 0
|
|
196
|
-
? JSON.stringify(mergedConfig)
|
|
197
|
-
: '{}';
|
|
198
|
-
|
|
199
|
-
debug.log('engine', `Spawning: ${args.join(' ')} (data dir: ${opencodeUserDir})`);
|
|
195
|
+
if (Object.keys(mcpConfig).length > 0) mergedConfig.mcp = mcpConfig;
|
|
196
|
+
if (providerConfig.enabledProviders.length > 0) mergedConfig.enabled_providers = providerConfig.enabledProviders;
|
|
197
|
+
if (spec.inlineAgents && Object.keys(spec.inlineAgents).length > 0) mergedConfig.agent = spec.inlineAgents;
|
|
198
|
+
const configContent = Object.keys(mergedConfig).length > 0 ? JSON.stringify(mergedConfig) : '{}';
|
|
200
199
|
|
|
201
200
|
const proc = Bun.spawn(args, {
|
|
202
201
|
stdout: 'pipe',
|
|
@@ -204,15 +203,15 @@ async function init(): Promise<void> {
|
|
|
204
203
|
env: {
|
|
205
204
|
...process.env,
|
|
206
205
|
...providerConfig.envVars,
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
XDG_STATE_HOME:
|
|
210
|
-
XDG_CACHE_HOME:
|
|
206
|
+
XDG_CONFIG_HOME: configDir,
|
|
207
|
+
XDG_DATA_HOME: dataDir,
|
|
208
|
+
XDG_STATE_HOME: dataDir,
|
|
209
|
+
XDG_CACHE_HOME: dataDir,
|
|
211
210
|
OPENCODE_CONFIG_CONTENT: configContent,
|
|
212
211
|
},
|
|
213
212
|
});
|
|
214
213
|
|
|
215
|
-
// Parse
|
|
214
|
+
// Parse the URL from "opencode server listening on <url>".
|
|
216
215
|
const url = await new Promise<string>((resolve, reject) => {
|
|
217
216
|
const timeout = setTimeout(() => {
|
|
218
217
|
proc.kill();
|
|
@@ -220,7 +219,6 @@ async function init(): Promise<void> {
|
|
|
220
219
|
}, SERVER_START_TIMEOUT);
|
|
221
220
|
|
|
222
221
|
let output = '';
|
|
223
|
-
|
|
224
222
|
const readStream = async (stream: ReadableStream<Uint8Array>, label: string) => {
|
|
225
223
|
const reader = stream.getReader();
|
|
226
224
|
const decoder = new TextDecoder();
|
|
@@ -228,30 +226,20 @@ async function init(): Promise<void> {
|
|
|
228
226
|
while (true) {
|
|
229
227
|
const { done, value } = await reader.read();
|
|
230
228
|
if (done) break;
|
|
231
|
-
|
|
232
|
-
output += chunk;
|
|
233
|
-
|
|
229
|
+
output += decoder.decode(value, { stream: true });
|
|
234
230
|
if (label === 'stdout') {
|
|
235
231
|
for (const line of output.split('\n')) {
|
|
236
232
|
if (line.startsWith('opencode server listening')) {
|
|
237
233
|
const match = line.match(/on\s+(https?:\/\/[^\s]+)/);
|
|
238
|
-
if (match) {
|
|
239
|
-
clearTimeout(timeout);
|
|
240
|
-
resolve(match[1]);
|
|
241
|
-
return;
|
|
242
|
-
}
|
|
234
|
+
if (match) { clearTimeout(timeout); resolve(match[1]); return; }
|
|
243
235
|
}
|
|
244
236
|
}
|
|
245
237
|
}
|
|
246
238
|
}
|
|
247
|
-
} catch {
|
|
248
|
-
// stream closed
|
|
249
|
-
}
|
|
239
|
+
} catch { /* stream closed */ }
|
|
250
240
|
};
|
|
251
|
-
|
|
252
241
|
readStream(proc.stdout as ReadableStream<Uint8Array>, 'stdout');
|
|
253
242
|
readStream(proc.stderr as ReadableStream<Uint8Array>, 'stderr');
|
|
254
|
-
|
|
255
243
|
proc.exited.then((code) => {
|
|
256
244
|
clearTimeout(timeout);
|
|
257
245
|
let msg = `opencode server exited with code ${code}`;
|
|
@@ -260,72 +248,40 @@ async function init(): Promise<void> {
|
|
|
260
248
|
});
|
|
261
249
|
});
|
|
262
250
|
|
|
263
|
-
serverProc = proc;
|
|
264
251
|
const { createOpencodeClient } = await import('@opencode-ai/sdk');
|
|
265
|
-
client = createOpencodeClient({ baseUrl: url });
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
};
|
|
270
|
-
ownsProcess = true;
|
|
271
|
-
ready = true;
|
|
252
|
+
const client = createOpencodeClient({ baseUrl: url });
|
|
253
|
+
debug.log('engine', `Open Code server ready (key "${key}", ${url}, data dir: ${dataDir})`);
|
|
254
|
+
return { key, url, client, proc, ownsProcess: true, lastUsed: Date.now() };
|
|
255
|
+
}
|
|
272
256
|
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
257
|
+
/**
|
|
258
|
+
* The DEFAULT (no-Profile) client — used for model listing, one-shot structured
|
|
259
|
+
* generation, and warm-up. Concurrency-safe via the shared init promise.
|
|
260
|
+
*/
|
|
261
|
+
export async function ensureClient(): Promise<OpencodeClient> {
|
|
262
|
+
return (await ensureServer(DEFAULT_SERVER_KEY, {})).client;
|
|
276
263
|
}
|
|
277
264
|
|
|
265
|
+
/** The DEFAULT server's client, if up (back-compat for callers with no stream context). */
|
|
278
266
|
export function getClient(): OpencodeClient | null {
|
|
279
|
-
return
|
|
267
|
+
return pool.get(DEFAULT_SERVER_KEY)?.client ?? null;
|
|
280
268
|
}
|
|
281
269
|
|
|
270
|
+
/** The DEFAULT server's URL, if up. */
|
|
282
271
|
export function getServerUrl(): string | null {
|
|
283
|
-
return
|
|
272
|
+
return pool.get(DEFAULT_SERVER_KEY)?.url ?? null;
|
|
284
273
|
}
|
|
285
274
|
|
|
286
275
|
/**
|
|
287
|
-
* Dispose the
|
|
288
|
-
*
|
|
289
|
-
*
|
|
290
|
-
* we didn't spawn it) and purges the stored URL so the next init() spawns
|
|
291
|
-
* a fresh server with updated config. Used by the Restart Server flow.
|
|
292
|
-
*
|
|
293
|
-
* When false (default), only kills the child process when we spawned it.
|
|
294
|
-
* Reused servers stay alive so the next session can pick them up.
|
|
276
|
+
* Dispose the whole pool. `forRestart` is accepted for signature compatibility
|
|
277
|
+
* with the previous single-server API; every pooled server we own is killed
|
|
278
|
+
* either way (there is no external-server-reuse path anymore).
|
|
295
279
|
*/
|
|
296
|
-
export async function disposeOpenCodeClient(
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
} else if (forRestart) {
|
|
304
|
-
// Server we didn't spawn — kill it by sending a request or just
|
|
305
|
-
// purging the stored URL. The server process may be external, but
|
|
306
|
-
// clearing DB ensures we spawn a new one on next init().
|
|
307
|
-
try {
|
|
308
|
-
await fetch(`${serverHandle.url}/shutdown`, {
|
|
309
|
-
method: 'POST',
|
|
310
|
-
signal: AbortSignal.timeout(2000),
|
|
311
|
-
});
|
|
312
|
-
} catch {
|
|
313
|
-
// shutdown endpoint may not exist — that's fine
|
|
314
|
-
}
|
|
315
|
-
}
|
|
316
|
-
settingsQueries.delete(DB_KEY);
|
|
317
|
-
settingsQueries.delete(DB_KEY_DATADIR);
|
|
318
|
-
} catch (error) {
|
|
319
|
-
debug.error('engine', 'Error stopping Open Code server:', error);
|
|
320
|
-
}
|
|
321
|
-
}
|
|
322
|
-
} else if (forRestart) {
|
|
323
|
-
// No active handle but forRestart requested — ensure DB is clean
|
|
324
|
-
settingsQueries.delete(DB_KEY);
|
|
325
|
-
settingsQueries.delete(DB_KEY_DATADIR);
|
|
326
|
-
}
|
|
327
|
-
|
|
328
|
-
clearClientState();
|
|
329
|
-
initPromise = null;
|
|
330
|
-
debug.log('engine', 'Open Code client disposed');
|
|
280
|
+
export async function disposeOpenCodeClient(_forRestart = false): Promise<void> {
|
|
281
|
+
for (const inst of pool.values()) killInstance(inst);
|
|
282
|
+
pool.clear();
|
|
283
|
+
initPromises.clear();
|
|
284
|
+
settingsQueries.delete(LEGACY_DB_KEY);
|
|
285
|
+
settingsQueries.delete(LEGACY_DB_KEY_DATADIR);
|
|
286
|
+
debug.log('engine', 'Open Code pool disposed');
|
|
331
287
|
}
|