@myrialabs/clopen 0.4.5 → 0.4.6
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.ts +14 -1
- package/backend/database/migrations/044_create_skills_table.ts +29 -0
- package/backend/database/migrations/index.ts +7 -0
- package/backend/database/queries/index.ts +3 -1
- package/backend/database/queries/skill-queries.ts +105 -0
- package/backend/engine/adapters/claude/stream.ts +5 -0
- package/backend/engine/adapters/codex/credential.ts +114 -13
- package/backend/engine/adapters/codex/stream.ts +34 -8
- package/backend/engine/adapters/copilot/stream.ts +4 -0
- package/backend/engine/adapters/opencode/stream.ts +4 -0
- package/backend/engine/adapters/qwen/stream.ts +3 -0
- package/backend/engine/docs/lessons-learned.md +54 -50
- package/backend/index.ts +10 -1
- package/backend/mcp/README.md +77 -24
- package/backend/mcp/external/config.ts +82 -101
- package/backend/mcp/external/proxy.ts +202 -0
- package/backend/mcp/index.ts +4 -3
- package/backend/mcp/internal/remote-server.ts +103 -55
- package/backend/skills/index.ts +21 -0
- package/backend/skills/marketplace.ts +172 -0
- package/backend/skills/service.ts +245 -0
- package/backend/skills/spec.ts +214 -0
- package/backend/skills/store.ts +99 -0
- package/backend/skills/sync.ts +187 -0
- package/backend/ws/index.ts +5 -1
- package/backend/ws/skills/catalog.ts +79 -0
- package/backend/ws/skills/crud.ts +123 -0
- package/backend/ws/skills/index.ts +15 -0
- package/dist/assets/main-BkMrek4_.css +1 -0
- package/dist/assets/{main-zXKH_C5O.js → main-TYNK6Orl.js} +256 -241
- package/dist/index.html +2 -2
- package/package.json +1 -1
- package/shared/utils/logger.ts +1 -0
- package/dist/assets/main-gNUEJAC5.css +0 -1
|
@@ -112,7 +112,20 @@ export const ADMIN_ONLY_ROUTES = new Set([
|
|
|
112
112
|
'mcp:uninstall',
|
|
113
113
|
'mcp:status',
|
|
114
114
|
'mcp:oauth-start',
|
|
115
|
-
'mcp:oauth-complete'
|
|
115
|
+
'mcp:oauth-complete',
|
|
116
|
+
// Agent Skills — creating/importing/installing skills writes to the shared
|
|
117
|
+
// canonical store and applies to every engine, so the whole surface is
|
|
118
|
+
// admin-only, mirroring MCP and System Tools.
|
|
119
|
+
'skills:list',
|
|
120
|
+
'skills:get',
|
|
121
|
+
'skills:create',
|
|
122
|
+
'skills:update',
|
|
123
|
+
'skills:parse-import',
|
|
124
|
+
'skills:import',
|
|
125
|
+
'skills:toggle',
|
|
126
|
+
'skills:delete',
|
|
127
|
+
'skills:catalog',
|
|
128
|
+
'skills:install'
|
|
116
129
|
]);
|
|
117
130
|
|
|
118
131
|
/**
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import type { DatabaseConnection } from '$shared/types/database/connection';
|
|
2
|
+
import { debug } from '$shared/utils/logger';
|
|
3
|
+
|
|
4
|
+
export const description = 'Create skills table for user-managed Agent Skills (SKILL.md)';
|
|
5
|
+
|
|
6
|
+
export const up = (db: DatabaseConnection): void => {
|
|
7
|
+
debug.log('migration', 'Creating skills table...');
|
|
8
|
+
db.exec(`
|
|
9
|
+
CREATE TABLE IF NOT EXISTS skills (
|
|
10
|
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
11
|
+
slug TEXT NOT NULL UNIQUE,
|
|
12
|
+
name TEXT NOT NULL,
|
|
13
|
+
description TEXT NOT NULL DEFAULT '',
|
|
14
|
+
source TEXT NOT NULL DEFAULT 'custom',
|
|
15
|
+
marketplace_ref TEXT,
|
|
16
|
+
version TEXT,
|
|
17
|
+
license TEXT,
|
|
18
|
+
is_enabled INTEGER NOT NULL DEFAULT 1,
|
|
19
|
+
created_at DATETIME DEFAULT CURRENT_TIMESTAMP
|
|
20
|
+
)
|
|
21
|
+
`);
|
|
22
|
+
debug.log('migration', 'skills table created');
|
|
23
|
+
};
|
|
24
|
+
|
|
25
|
+
export const down = (db: DatabaseConnection): void => {
|
|
26
|
+
debug.log('migration', 'Dropping skills table...');
|
|
27
|
+
db.exec('DROP TABLE IF EXISTS skills');
|
|
28
|
+
debug.log('migration', 'skills table dropped');
|
|
29
|
+
};
|
|
@@ -42,6 +42,7 @@ import * as migration040 from './040_create_mcp_servers_table';
|
|
|
42
42
|
import * as migration041 from './041_add_mcp_config_schema';
|
|
43
43
|
import * as migration042 from './042_add_mcp_oauth';
|
|
44
44
|
import * as migration043 from './043_relocate_engine_config_dirs';
|
|
45
|
+
import * as migration044 from './044_create_skills_table';
|
|
45
46
|
|
|
46
47
|
// Export all migrations in order
|
|
47
48
|
export const migrations = [
|
|
@@ -302,6 +303,12 @@ export const migrations = [
|
|
|
302
303
|
description: migration043.description,
|
|
303
304
|
up: migration043.up,
|
|
304
305
|
down: migration043.down
|
|
306
|
+
},
|
|
307
|
+
{
|
|
308
|
+
id: '044',
|
|
309
|
+
description: migration044.description,
|
|
310
|
+
up: migration044.up,
|
|
311
|
+
down: migration044.down
|
|
305
312
|
}
|
|
306
313
|
];
|
|
307
314
|
|
|
@@ -13,4 +13,6 @@ export { dbClientQueryHistoryQueries } from './db-client-query-history-queries';
|
|
|
13
13
|
export { auditLogQueries } from './audit-log-queries';
|
|
14
14
|
export { fileAuditLogQueries } from './file-audit-log-queries';
|
|
15
15
|
export { mcpServerQueries } from './mcp-server-queries';
|
|
16
|
-
export type { McpServerRow, McpServerInput, McpTransport, McpSource, McpConfigField } from './mcp-server-queries';
|
|
16
|
+
export type { McpServerRow, McpServerInput, McpTransport, McpSource, McpConfigField } from './mcp-server-queries';
|
|
17
|
+
export { skillQueries } from './skill-queries';
|
|
18
|
+
export type { SkillRow, SkillInput, SkillSource } from './skill-queries';
|
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Skill Queries
|
|
3
|
+
*
|
|
4
|
+
* CRUD for user-managed Agent Skills — the skills managed from Settings →
|
|
5
|
+
* Skills. The `skills` table holds only METADATA + the enable/disable toggle;
|
|
6
|
+
* the actual SKILL.md (and any bundled resources) live on disk in the canonical
|
|
7
|
+
* store under `{clopenDir}/skills/<slug>/` (see `backend/skills/store.ts`).
|
|
8
|
+
*
|
|
9
|
+
* Conventions:
|
|
10
|
+
* - `slug` : unique machine id, matches the on-disk folder name and the
|
|
11
|
+
* SKILL.md `name` frontmatter. Only `[a-z0-9-]`.
|
|
12
|
+
* - `source` : where the skill came from — 'custom' (created in-app),
|
|
13
|
+
* 'imported' (pasted/uploaded), or 'marketplace' (installed from
|
|
14
|
+
* a provider).
|
|
15
|
+
*/
|
|
16
|
+
|
|
17
|
+
import { getDatabase } from '../index';
|
|
18
|
+
|
|
19
|
+
export type SkillSource = 'custom' | 'imported' | 'marketplace';
|
|
20
|
+
|
|
21
|
+
/** Raw DB row. */
|
|
22
|
+
export interface SkillRow {
|
|
23
|
+
id: number;
|
|
24
|
+
slug: string;
|
|
25
|
+
name: string;
|
|
26
|
+
description: string;
|
|
27
|
+
source: SkillSource;
|
|
28
|
+
/** Provider reference for marketplace skills (e.g. `official:pdf-processing`), or null. */
|
|
29
|
+
marketplace_ref: string | null;
|
|
30
|
+
version: string | null;
|
|
31
|
+
license: string | null;
|
|
32
|
+
is_enabled: number;
|
|
33
|
+
created_at: string;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export interface SkillInput {
|
|
37
|
+
slug: string;
|
|
38
|
+
name: string;
|
|
39
|
+
description: string;
|
|
40
|
+
source?: SkillSource;
|
|
41
|
+
marketplaceRef?: string | null;
|
|
42
|
+
version?: string | null;
|
|
43
|
+
license?: string | null;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
export const skillQueries = {
|
|
47
|
+
getAll(): SkillRow[] {
|
|
48
|
+
const db = getDatabase();
|
|
49
|
+
return db.prepare(`SELECT * FROM skills ORDER BY created_at ASC`).all() as SkillRow[];
|
|
50
|
+
},
|
|
51
|
+
|
|
52
|
+
getEnabled(): SkillRow[] {
|
|
53
|
+
const db = getDatabase();
|
|
54
|
+
return db.prepare(`SELECT * FROM skills WHERE is_enabled = 1 ORDER BY created_at ASC`).all() as SkillRow[];
|
|
55
|
+
},
|
|
56
|
+
|
|
57
|
+
getById(id: number): SkillRow | null {
|
|
58
|
+
const db = getDatabase();
|
|
59
|
+
return db.prepare(`SELECT * FROM skills WHERE id = ?`).get(id) as SkillRow | null;
|
|
60
|
+
},
|
|
61
|
+
|
|
62
|
+
getBySlug(slug: string): SkillRow | null {
|
|
63
|
+
const db = getDatabase();
|
|
64
|
+
return db.prepare(`SELECT * FROM skills WHERE slug = ?`).get(slug) as SkillRow | null;
|
|
65
|
+
},
|
|
66
|
+
|
|
67
|
+
insert(input: SkillInput): SkillRow {
|
|
68
|
+
const db = getDatabase();
|
|
69
|
+
const result = db.prepare(
|
|
70
|
+
`INSERT INTO skills (slug, name, description, source, marketplace_ref, version, license)
|
|
71
|
+
VALUES (?, ?, ?, ?, ?, ?, ?)`
|
|
72
|
+
).run(
|
|
73
|
+
input.slug,
|
|
74
|
+
input.name,
|
|
75
|
+
input.description,
|
|
76
|
+
input.source ?? 'custom',
|
|
77
|
+
input.marketplaceRef ?? null,
|
|
78
|
+
input.version ?? null,
|
|
79
|
+
input.license ?? null
|
|
80
|
+
) as { lastInsertRowid: number | bigint };
|
|
81
|
+
const id = Number(result.lastInsertRowid);
|
|
82
|
+
return this.getById(id)!;
|
|
83
|
+
},
|
|
84
|
+
|
|
85
|
+
/** Update the display metadata (name/description/license) of a skill. */
|
|
86
|
+
updateMeta(id: number, name: string, description: string, license: string | null): void {
|
|
87
|
+
const db = getDatabase();
|
|
88
|
+
db.prepare(`UPDATE skills SET name = ?, description = ?, license = ? WHERE id = ?`).run(
|
|
89
|
+
name,
|
|
90
|
+
description,
|
|
91
|
+
license,
|
|
92
|
+
id
|
|
93
|
+
);
|
|
94
|
+
},
|
|
95
|
+
|
|
96
|
+
setEnabled(id: number, enabled: boolean): void {
|
|
97
|
+
const db = getDatabase();
|
|
98
|
+
db.prepare(`UPDATE skills SET is_enabled = ? WHERE id = ?`).run(enabled ? 1 : 0, id);
|
|
99
|
+
},
|
|
100
|
+
|
|
101
|
+
remove(id: number): void {
|
|
102
|
+
const db = getDatabase();
|
|
103
|
+
db.prepare(`DELETE FROM skills WHERE id = ?`).run(id);
|
|
104
|
+
}
|
|
105
|
+
};
|
|
@@ -27,6 +27,7 @@ import { resolveOsPath } from '$backend/utils/paths';
|
|
|
27
27
|
import { setupEnvironmentOnce, getEngineEnv } from './environment';
|
|
28
28
|
import { handleStreamError } from './error-handler';
|
|
29
29
|
import { getEnabledMcpServers, getAllowedMcpTools } from '../../../mcp';
|
|
30
|
+
import { syncSkills } from '$backend/skills';
|
|
30
31
|
import type { AIEngine, EngineQueryOptions } from '../../types';
|
|
31
32
|
import type { EngineModel } from '$shared/types/unified';
|
|
32
33
|
import { CLAUDE_CODE_MODELS } from './models';
|
|
@@ -98,6 +99,10 @@ export class ClaudeCodeEngine implements AIEngine {
|
|
|
98
99
|
const resolvedProjectPath = resolveOsPath(projectPath);
|
|
99
100
|
|
|
100
101
|
try {
|
|
102
|
+
// Materialize enabled skills into Claude's native skills dir before the
|
|
103
|
+
// session starts so the SDK picks them up via settingSources.
|
|
104
|
+
await syncSkills('claude');
|
|
105
|
+
|
|
101
106
|
// Get custom MCP servers and allowed tools
|
|
102
107
|
// Pass mcpContext so tool handlers are bound to the correct project
|
|
103
108
|
const mcpServers = getEnabledMcpServers(options.mcpContext);
|
|
@@ -69,6 +69,92 @@ export function serializeCodexCredential(cred: CodexCredential): string {
|
|
|
69
69
|
return JSON.stringify(cred);
|
|
70
70
|
}
|
|
71
71
|
|
|
72
|
+
/**
|
|
73
|
+
* Identity + freshness extracted from a ChatGPT `auth.json` blob.
|
|
74
|
+
*
|
|
75
|
+
* `accountId` (`tokens.account_id`) tells us *which* ChatGPT account a blob
|
|
76
|
+
* belongs to; `lastRefresh` (epoch ms parsed from `last_refresh`) tells us how
|
|
77
|
+
* *fresh* its tokens are. Both drive the no-clobber decision below: the Codex
|
|
78
|
+
* CLI rotates the refresh token in place on every refresh (old token revoked),
|
|
79
|
+
* so we must never write an older blob over a newer one for the same account —
|
|
80
|
+
* doing so replays an already-revoked refresh token and bricks the account.
|
|
81
|
+
*/
|
|
82
|
+
interface AuthJsonMeta {
|
|
83
|
+
accountId: string | null;
|
|
84
|
+
lastRefresh: number | null;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
function parseAuthJsonMeta(authJsonRaw: string): AuthJsonMeta {
|
|
88
|
+
try {
|
|
89
|
+
const parsed = JSON.parse(authJsonRaw) as {
|
|
90
|
+
last_refresh?: unknown;
|
|
91
|
+
tokens?: { account_id?: unknown } | null;
|
|
92
|
+
};
|
|
93
|
+
const accountId = typeof parsed.tokens?.account_id === 'string' ? parsed.tokens.account_id : null;
|
|
94
|
+
let lastRefresh: number | null = null;
|
|
95
|
+
if (typeof parsed.last_refresh === 'string') {
|
|
96
|
+
const ts = Date.parse(parsed.last_refresh);
|
|
97
|
+
lastRefresh = Number.isNaN(ts) ? null : ts;
|
|
98
|
+
}
|
|
99
|
+
return { accountId, lastRefresh };
|
|
100
|
+
} catch {
|
|
101
|
+
return { accountId: null, lastRefresh: null };
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/**
|
|
106
|
+
* Decide whether the desired (DB) blob should overwrite the current on-disk
|
|
107
|
+
* `auth.json`. The on-disk copy is authoritative for *freshness* because the
|
|
108
|
+
* CLI refreshes it in place; the DB is authoritative only for *account switch*.
|
|
109
|
+
*
|
|
110
|
+
* - disk empty / identical content → trivial (handled by caller).
|
|
111
|
+
* - different `account_id` → account switch → write.
|
|
112
|
+
* - same `account_id` → keep the live disk token unless the DB blob is
|
|
113
|
+
* strictly newer (e.g. just after a re-login produced a fresher token).
|
|
114
|
+
* - identity unknown on either side → fall back to freshness if both
|
|
115
|
+
* timestamps are present (keep disk when same-or-newer), else write.
|
|
116
|
+
*/
|
|
117
|
+
function shouldWriteAuthJson(current: string, desired: string): boolean {
|
|
118
|
+
const cur = parseAuthJsonMeta(current);
|
|
119
|
+
const des = parseAuthJsonMeta(desired);
|
|
120
|
+
|
|
121
|
+
if (cur.accountId && des.accountId) {
|
|
122
|
+
if (cur.accountId !== des.accountId) return true; // account switch
|
|
123
|
+
// Same ChatGPT account already on disk — never clobber a fresher live
|
|
124
|
+
// token; only adopt the DB blob when it is strictly newer.
|
|
125
|
+
return des.lastRefresh !== null && cur.lastRefresh !== null && des.lastRefresh > cur.lastRefresh;
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
// Identity unknown on at least one side — defer to freshness when we can.
|
|
129
|
+
if (cur.lastRefresh !== null && des.lastRefresh !== null) {
|
|
130
|
+
return des.lastRefresh > cur.lastRefresh;
|
|
131
|
+
}
|
|
132
|
+
return true;
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
/**
|
|
136
|
+
* Locate the account whose stored ChatGPT blob matches the given on-disk
|
|
137
|
+
* `account_id`, so a token refresh persists back to the *right* account even
|
|
138
|
+
* when the active account differs from the one currently on disk (per-stream
|
|
139
|
+
* account override). Falls back to the active account only for legacy blobs
|
|
140
|
+
* with no `account_id`; returns null when an id is present but matches no
|
|
141
|
+
* account (avoid cross-contaminating an unrelated row).
|
|
142
|
+
*/
|
|
143
|
+
function findAccountForAuthJson(accountId: string | null): EngineAccount | null {
|
|
144
|
+
if (!accountId) {
|
|
145
|
+
return engineQueries.getActiveAccountForEngine('codex');
|
|
146
|
+
}
|
|
147
|
+
const provider = engineQueries.getProviderBySlug('codex', 'openai');
|
|
148
|
+
if (!provider) return null;
|
|
149
|
+
for (const account of engineQueries.getAccountsByProvider(provider.id)) {
|
|
150
|
+
const parsed = parseCodexCredential(account.credential);
|
|
151
|
+
if (parsed?.kind === 'chatgpt' && parseAuthJsonMeta(parsed.authJson).accountId === accountId) {
|
|
152
|
+
return account;
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
return null;
|
|
156
|
+
}
|
|
157
|
+
|
|
72
158
|
/** True when the model requires a ChatGPT-mode account (e.g. gpt-5.5). */
|
|
73
159
|
export function authModeOf(account: EngineAccount): 'api_key' | 'chatgpt' | null {
|
|
74
160
|
const parsed = parseCodexCredential(account.credential);
|
|
@@ -144,11 +230,14 @@ export function applyAccountAuth(account: EngineAccount): CodexCredential | null
|
|
|
144
230
|
}
|
|
145
231
|
|
|
146
232
|
if (cred.kind === 'chatgpt') {
|
|
147
|
-
//
|
|
148
|
-
//
|
|
149
|
-
//
|
|
233
|
+
// The CLI rotates its refresh token in place on every refresh, so the
|
|
234
|
+
// on-disk auth.json is the live, authoritative copy for the active
|
|
235
|
+
// account. Only write the DB blob when the file is absent, belongs to a
|
|
236
|
+
// different account (switch), or the DB copy is strictly newer — never
|
|
237
|
+
// clobber a fresher on-disk token with a stale snapshot (that replays an
|
|
238
|
+
// already-revoked refresh token and bricks the account).
|
|
150
239
|
const current = readAuthJson();
|
|
151
|
-
if (current !== cred.authJson) {
|
|
240
|
+
if (current === null || (current !== cred.authJson && shouldWriteAuthJson(current, cred.authJson))) {
|
|
152
241
|
writeAuthJson(cred.authJson);
|
|
153
242
|
debug.log('engine', `Codex: wrote auth.json from account "${account.name}" (${cred.authJson.length} bytes)`);
|
|
154
243
|
}
|
|
@@ -158,27 +247,39 @@ export function applyAccountAuth(account: EngineAccount): CodexCredential | null
|
|
|
158
247
|
}
|
|
159
248
|
|
|
160
249
|
/**
|
|
161
|
-
* Snapshot the current
|
|
162
|
-
* account
|
|
163
|
-
*
|
|
250
|
+
* Snapshot the current on-disk `auth.json` back into the credential row of the
|
|
251
|
+
* account it belongs to (matched by `tokens.account_id`), so any token refresh
|
|
252
|
+
* the CLI performed during the turn survives across account switches and restarts.
|
|
253
|
+
*
|
|
254
|
+
* Matching by `account_id` — rather than blindly targeting the active account —
|
|
255
|
+
* keeps a per-stream account override (a turn run under a non-active account)
|
|
256
|
+
* from writing its refreshed token onto the wrong row.
|
|
164
257
|
*
|
|
165
258
|
* No-op when:
|
|
166
|
-
* - There's no active Codex account.
|
|
167
|
-
* - The active account is API-key mode (auth.json wasn't touched).
|
|
168
259
|
* - The auth.json file doesn't exist.
|
|
260
|
+
* - No account matches the on-disk `account_id` (and no legacy fallback).
|
|
261
|
+
* - The matched account is API-key mode (auth.json wasn't touched).
|
|
169
262
|
* - The on-disk content is identical to what we already have stored.
|
|
263
|
+
* - The on-disk copy is older than the stored one (never persist a stale read).
|
|
170
264
|
*/
|
|
171
265
|
export function snapshotAuthJsonToActiveAccount(): void {
|
|
172
|
-
const
|
|
266
|
+
const current = readAuthJson();
|
|
267
|
+
if (current === null) return;
|
|
268
|
+
|
|
269
|
+
const curMeta = parseAuthJsonMeta(current);
|
|
270
|
+
const account = findAccountForAuthJson(curMeta.accountId);
|
|
173
271
|
if (!account) return;
|
|
174
272
|
|
|
175
273
|
const parsed = parseCodexCredential(account.credential);
|
|
176
274
|
if (!parsed || parsed.kind !== 'chatgpt') return;
|
|
177
|
-
|
|
178
|
-
const current = readAuthJson();
|
|
179
|
-
if (current === null) return;
|
|
180
275
|
if (current === parsed.authJson) return;
|
|
181
276
|
|
|
277
|
+
// Guard against persisting an older read over a newer stored blob.
|
|
278
|
+
const storedMeta = parseAuthJsonMeta(parsed.authJson);
|
|
279
|
+
if (curMeta.lastRefresh !== null && storedMeta.lastRefresh !== null && curMeta.lastRefresh < storedMeta.lastRefresh) {
|
|
280
|
+
return;
|
|
281
|
+
}
|
|
282
|
+
|
|
182
283
|
const updated = serializeCodexCredential({ kind: 'chatgpt', authJson: current });
|
|
183
284
|
try {
|
|
184
285
|
engineQueries.updateAccountCredential(account.id, updated);
|
|
@@ -28,6 +28,7 @@ import { resolveOsPath } from '$backend/utils/paths';
|
|
|
28
28
|
import { resolveBinary } from '$backend/utils/cli';
|
|
29
29
|
import { getCleanSpawnEnv } from '$backend/utils/index.js';
|
|
30
30
|
import { getCodexMcpConfig } from '../../../mcp';
|
|
31
|
+
import { syncSkills } from '$backend/skills';
|
|
31
32
|
import { CODEX_MODELS } from './models';
|
|
32
33
|
import { debug } from '$shared/utils/logger';
|
|
33
34
|
import { handleStreamError, buildTurnError } from './error-handler';
|
|
@@ -138,6 +139,9 @@ export class CodexEngine implements AIEngine {
|
|
|
138
139
|
async *streamQuery(options: EngineQueryOptions): AsyncGenerator<EngineOutput, void, unknown> {
|
|
139
140
|
const { projectPath, prompt, resume, modelId, abortController, accountId } = options;
|
|
140
141
|
|
|
142
|
+
// Refresh the synthetic skills preamble in CODEX_HOME before the turn.
|
|
143
|
+
await syncSkills('codex');
|
|
144
|
+
|
|
141
145
|
// Per-stream account override — same shape as Copilot. The SDK takes
|
|
142
146
|
// the apiKey at construction time, so an account switch requires
|
|
143
147
|
// re-creating the Codex client.
|
|
@@ -300,6 +304,18 @@ export class CodexEngine implements AIEngine {
|
|
|
300
304
|
throw new Error('Codex client unavailable.');
|
|
301
305
|
}
|
|
302
306
|
|
|
307
|
+
// Refresh auth.json for the active account before the turn (cheap
|
|
308
|
+
// idempotent op — keeps a freshly-refreshed on-disk token, see
|
|
309
|
+
// credential.ts). Without this the structured turn could run on a stale
|
|
310
|
+
// blob; without the finally-snapshot below, a refresh it performs would
|
|
311
|
+
// be lost and the next stream would replay a revoked token.
|
|
312
|
+
const structuredAccount = accountId != null
|
|
313
|
+
? engineQueries.getAccount(accountId)
|
|
314
|
+
: engineQueries.getActiveAccountForEngine('codex');
|
|
315
|
+
if (structuredAccount) {
|
|
316
|
+
applyAccountAuth(structuredAccount);
|
|
317
|
+
}
|
|
318
|
+
|
|
303
319
|
const controller = abortController || new AbortController();
|
|
304
320
|
const resolvedProjectPath = resolveOsPath(projectPath);
|
|
305
321
|
|
|
@@ -314,16 +330,26 @@ export class CodexEngine implements AIEngine {
|
|
|
314
330
|
|
|
315
331
|
debug.log('engine', `[codex structured] running with model=${modelId}`);
|
|
316
332
|
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
333
|
+
try {
|
|
334
|
+
const turn = await thread.run(prompt, {
|
|
335
|
+
outputSchema: schema,
|
|
336
|
+
signal: controller.signal,
|
|
337
|
+
});
|
|
321
338
|
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
339
|
+
if (!turn.finalResponse) {
|
|
340
|
+
throw new Error('Codex returned empty response');
|
|
341
|
+
}
|
|
325
342
|
|
|
326
|
-
|
|
343
|
+
return extractJson<T>(turn.finalResponse);
|
|
344
|
+
} finally {
|
|
345
|
+
// Persist any token refresh the CLI performed during this turn so the
|
|
346
|
+
// next stream doesn't replay an already-rotated (revoked) token.
|
|
347
|
+
try {
|
|
348
|
+
snapshotAuthJsonToActiveAccount();
|
|
349
|
+
} catch (snapshotErr) {
|
|
350
|
+
debug.warn('engine', 'Codex: post-structured auth.json snapshot failed (non-fatal):', snapshotErr);
|
|
351
|
+
}
|
|
352
|
+
}
|
|
327
353
|
}
|
|
328
354
|
}
|
|
329
355
|
|
|
@@ -21,6 +21,7 @@ import { engineQueries } from '$backend/database/queries/engine-queries';
|
|
|
21
21
|
import { resolveOsPath, getEngineUserConfigDir } from '$backend/utils/paths';
|
|
22
22
|
import { debug } from '$shared/utils/logger';
|
|
23
23
|
import { getCopilotMcpConfig } from '../../../mcp';
|
|
24
|
+
import { syncSkills } from '$backend/skills';
|
|
24
25
|
import { handleStreamError, buildSessionError } from './error-handler';
|
|
25
26
|
import { fetchCopilotModels } from './models';
|
|
26
27
|
|
|
@@ -193,6 +194,9 @@ export class CopilotEngine implements AIEngine {
|
|
|
193
194
|
|
|
194
195
|
this.activeController = abortController || new AbortController();
|
|
195
196
|
|
|
197
|
+
// Mirror enabled skills into Copilot's native skills dir before the turn.
|
|
198
|
+
await syncSkills('copilot');
|
|
199
|
+
|
|
196
200
|
const resolvedProjectPath = resolveOsPath(projectPath);
|
|
197
201
|
const state = createStreamConverterState('', modelId);
|
|
198
202
|
|
|
@@ -40,6 +40,7 @@ import {
|
|
|
40
40
|
getToolInput,
|
|
41
41
|
} from './message-converter';
|
|
42
42
|
import { ensureClient, getClient, getServerUrl } from './server';
|
|
43
|
+
import { syncSkills } from '$backend/skills';
|
|
43
44
|
import { formatSessionError, handleStreamError } from './error-handler';
|
|
44
45
|
import { buildJsonPrompt, extractJson } from '../../structured-helpers';
|
|
45
46
|
import { debug } from '$shared/utils/logger';
|
|
@@ -120,6 +121,9 @@ export class OpenCodeEngine implements AIEngine {
|
|
|
120
121
|
this._isActive = true;
|
|
121
122
|
this.activeProjectPath = projectPath;
|
|
122
123
|
|
|
124
|
+
// Refresh the synthetic skills preamble in OpenCode's config dir.
|
|
125
|
+
await syncSkills('opencode');
|
|
126
|
+
|
|
123
127
|
debug.log('chat', 'Open Code - Stream Query');
|
|
124
128
|
debug.log('chat', { prompt });
|
|
125
129
|
|
|
@@ -46,6 +46,7 @@ import { handleStreamError } from './error-handler';
|
|
|
46
46
|
import { createSdkMessageConverter, toSdkUserMessage, type SdkMessageConverter } from './message-converter';
|
|
47
47
|
import { fetchQwenModels } from './models';
|
|
48
48
|
import { getQwenMcpConfig } from '../../../mcp';
|
|
49
|
+
import { syncSkills } from '$backend/skills';
|
|
49
50
|
import { forkQwenSessionState, sessionStateExists } from './session-fork';
|
|
50
51
|
|
|
51
52
|
interface PendingAskUserQuestion {
|
|
@@ -137,6 +138,8 @@ export class QwenEngine implements AIEngine {
|
|
|
137
138
|
|
|
138
139
|
this.activeController = abortController || new AbortController();
|
|
139
140
|
const resolvedProjectPath = resolveOsPath(projectPath);
|
|
141
|
+
// Refresh the synthetic skills preamble in the Qwen memory file.
|
|
142
|
+
await syncSkills('qwen');
|
|
140
143
|
const mcpConfig = getQwenMcpConfig();
|
|
141
144
|
|
|
142
145
|
// Fork-by-copy on EVERY resume — same semantics as Claude
|
|
@@ -727,63 +727,67 @@ event protocol. Until then, v1 is intentional.
|
|
|
727
727
|
|
|
728
728
|
---
|
|
729
729
|
|
|
730
|
-
### 9.18 External (registry) MCP servers —
|
|
730
|
+
### 9.18 External (registry) MCP servers — proxied through the bridge
|
|
731
731
|
|
|
732
732
|
§9.12 covers the **internal** `clopen-mcp` bridge. **External** servers (the
|
|
733
|
-
ones users install from the registry, stored in `mcp_servers`)
|
|
734
|
-
|
|
735
|
-
|
|
736
|
-
|
|
737
|
-
|
|
738
|
-
|
|
739
|
-
|
|
740
|
-
|
|
741
|
-
>
|
|
742
|
-
>
|
|
743
|
-
>
|
|
744
|
-
|
|
745
|
-
|
|
746
|
-
|
|
747
|
-
|
|
748
|
-
|
|
749
|
-
|
|
750
|
-
|
|
751
|
-
|
|
752
|
-
|
|
753
|
-
|
|
754
|
-
|
|
755
|
-
(`
|
|
756
|
-
|
|
757
|
-
|
|
758
|
-
|
|
759
|
-
|
|
760
|
-
|
|
761
|
-
|
|
762
|
-
|
|
763
|
-
|
|
764
|
-
|
|
765
|
-
|
|
766
|
-
|
|
767
|
-
|
|
768
|
-
|
|
769
|
-
|
|
770
|
-
|
|
771
|
-
|
|
772
|
-
|
|
773
|
-
|
|
774
|
-
|
|
733
|
+
ones users install from the registry, stored in `mcp_servers`) used to be
|
|
734
|
+
connected **directly** by each engine — a third-party URL or stdio command.
|
|
735
|
+
That is no longer true: **external servers are now proxied** through a
|
|
736
|
+
per-server endpoint `GET/POST/DELETE /mcp/ext/<slug>` on the same
|
|
737
|
+
Streamable-HTTP bridge (`backend/mcp/external/proxy.ts`, mounted in
|
|
738
|
+
`backend/index.ts`). Clopen connects to the upstream as an MCP **client** and
|
|
739
|
+
re-exposes its tools; the engine only ever talks to Clopen over loopback.
|
|
740
|
+
|
|
741
|
+
> **Why proxy instead of direct?** Engines connect with the MCP SDK's
|
|
742
|
+
> `Client.listTools()`, which eagerly compiles an Ajv validator for every
|
|
743
|
+
> tool's `outputSchema`. A single unresolvable `$ref` (Stitch ships
|
|
744
|
+
> `#/$defs/ScreenInstance`) makes it throw, the engine CLIs' `discoverTools`
|
|
745
|
+
> swallow the error, and the server advertises **zero** tools while still
|
|
746
|
+
> reporting "connected". That hid every remote server's tools on Qwen and every
|
|
747
|
+
> external server on Copilot. The proxy reads `tools/list` with a **raw**
|
|
748
|
+
> request (no Ajv), **drops `outputSchema`**, and repairs dangling `$ref`s in
|
|
749
|
+
> `inputSchema` — so one bad schema can't take down a whole server.
|
|
750
|
+
|
|
751
|
+
What this means for a new adapter:
|
|
752
|
+
|
|
753
|
+
1. **Your `getXxxExternalMcpConfig()` is a one-liner per server.** Emit a
|
|
754
|
+
Streamable-HTTP remote pointing at `http://localhost:<port>/mcp/ext/<slug>`
|
|
755
|
+
plus the **service-token** header (`getMcpServiceToken()`), in your SDK's
|
|
756
|
+
shape. No stdio branch, no `oauth` flags, no third-party header forwarding —
|
|
757
|
+
the proxy injects the upstream credential itself. Every existing builder is
|
|
758
|
+
now identical bar the SDK field names
|
|
759
|
+
(`getClaude/OpenCode/Codex/Copilot/QwenExternalMcpConfig`); mirror that.
|
|
760
|
+
|
|
761
|
+
2. **Use the engine's real URL/header field** — same per-SDK caveats as the
|
|
762
|
+
internal bridge (§9.12), because the shape is identical:
|
|
763
|
+
- OpenCode: `url` (`type:'remote'`); Claude/Copilot: `url` (`type:'http'`).
|
|
764
|
+
- Qwen: `httpUrl`.
|
|
765
|
+
- **Codex: `http_headers`** (a TOML table) — **not** `bearer_token`, which is
|
|
766
|
+
rejected for `streamable_http` and aborts the run.
|
|
767
|
+
- Copilot: set `tools: ['*']` so the CLI exposes the proxy's tools (its
|
|
768
|
+
"undefined = all" default is not honoured for dynamically discovered
|
|
769
|
+
servers).
|
|
770
|
+
|
|
771
|
+
> **Two token systems — don't conflate them.** The bridge (internal AND
|
|
772
|
+
> external endpoints) is authed by a process-scoped, in-memory **service token**
|
|
773
|
+
> sent only over loopback (`backend/mcp/internal/service-token.ts`). The
|
|
774
|
+
> **third-party credential** (OAuth token / API key, persisted in
|
|
775
|
+
> `mcp_servers.oauth` / `mcp_servers.headers`) is used by the **proxy**, on the
|
|
776
|
+
> upstream hop — never by the engine. `resolveServerRow()` injects
|
|
777
|
+
> `Authorization: Bearer <token>` for the proxy client; `stream-manager` calls
|
|
778
|
+
> `refreshExpiringExternalOAuth()` before the stream so that token is fresh.
|
|
775
779
|
|
|
776
780
|
Connection health is surfaced engine-agnostically by `mcp:status`
|
|
777
|
-
(`backend/mcp/external/probe.ts`) —
|
|
778
|
-
|
|
779
|
-
offers **Authenticate** (OAuth) or **Configure** (API key) accordingly. A new
|
|
780
|
-
adapter needs no work here; the probe talks to the server, not the engine.
|
|
781
|
+
(`backend/mcp/external/probe.ts`) — `ok / needs_auth (OAuth) / needs_config
|
|
782
|
+
(missing API key) / unreachable / error`. A new adapter needs no work here.
|
|
781
783
|
|
|
782
784
|
What you must NOT do:
|
|
783
|
-
- ❌
|
|
785
|
+
- ❌ Point an engine straight at a third-party MCP URL/command — route it
|
|
786
|
+
through `/mcp/ext/<slug>` so schemas are sanitised and auth is centralized.
|
|
787
|
+
- ❌ Forward `mcp_servers.headers` (third-party creds) from a per-engine
|
|
788
|
+
builder — that's the proxy's job; the builder only carries the service token.
|
|
784
789
|
- ❌ Use `bearer_token` for Codex remote MCP — use `http_headers`.
|
|
785
|
-
- ❌ Add a per-engine OAuth flow or token store — Clopen centralizes it
|
|
786
|
-
injects the bearer into every engine, Codex included.
|
|
790
|
+
- ❌ Add a per-engine OAuth flow or token store — Clopen centralizes it.
|
|
787
791
|
|
|
788
792
|
---
|
|
789
793
|
|
package/backend/index.ts
CHANGED
|
@@ -40,7 +40,7 @@ import { audioRoute } from './http/audio';
|
|
|
40
40
|
import { browserPreviewServiceManager } from './preview';
|
|
41
41
|
|
|
42
42
|
// MCP remote server for Open Code custom tools
|
|
43
|
-
import { handleMcpRequest, closeMcpServer, completeAuthorization } from './mcp';
|
|
43
|
+
import { handleMcpRequest, handleExternalMcpRequest, closeMcpServer, completeAuthorization } from './mcp';
|
|
44
44
|
|
|
45
45
|
// Auth middleware
|
|
46
46
|
import { checkRouteAccess } from './auth/permissions';
|
|
@@ -109,6 +109,15 @@ const app = new Elysia()
|
|
|
109
109
|
return handleMcpRequest(request);
|
|
110
110
|
})
|
|
111
111
|
|
|
112
|
+
// Per-server proxy for user-installed (external) MCP servers. Clopen connects
|
|
113
|
+
// to the upstream third-party server and re-exposes its sanitized tools here,
|
|
114
|
+
// so engines never connect to it directly — see backend/mcp/external/proxy.ts.
|
|
115
|
+
// Same long-lived semantics as `/mcp`: disable Bun's idle timeout.
|
|
116
|
+
.all('/mcp/ext/:slug', async ({ request, params, server }) => {
|
|
117
|
+
server?.timeout(request, 0);
|
|
118
|
+
return handleExternalMcpRequest(request, params.slug);
|
|
119
|
+
})
|
|
120
|
+
|
|
112
121
|
// Stable OAuth redirect target for centralized MCP sign-in. The browser is
|
|
113
122
|
// redirected here after the user consents; we exchange the code for tokens
|
|
114
123
|
// (stored against the server) and show a self-closing confirmation page. The
|