@myrialabs/clopen 0.4.5 → 0.4.7
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/auth/session-invalidation.test.ts +17 -21
- package/backend/auth/session-invalidation.ts +10 -11
- 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/models.ts +46 -3
- 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/files/file-archive.test.ts +86 -26
- package/backend/files/file-archive.ts +214 -134
- 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/terminal/index.ts +2 -5
- package/backend/terminal/ptykit.ts +64 -0
- package/backend/tunnel/tunnel-config.ts +1 -1
- package/backend/utils/ws.ts +14 -0
- package/backend/ws/files/write.ts +23 -7
- package/backend/ws/index.ts +5 -1
- package/backend/ws/projects/crud.ts +4 -4
- 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/backend/ws/system/operations.ts +23 -0
- package/backend/ws/terminal/index.ts +6 -33
- package/backend/ws/terminal/tunnel.ts +76 -0
- package/dist/assets/index-xrB3zcfA.js +1 -0
- package/dist/assets/main-BXS8bjJ6.css +1 -0
- package/dist/assets/{main-zXKH_C5O.js → main-LBI3a0n5.js} +304 -261
- package/dist/index.html +2 -2
- package/package.json +7 -11
- package/shared/constants/engines.ts +4 -4
- package/shared/utils/logger.ts +1 -0
- package/backend/terminal/helpers.ts +0 -14
- package/backend/terminal/pty-manager.ts +0 -4
- package/backend/terminal/pty-session-manager.ts +0 -349
- package/backend/terminal/stream-manager.ts +0 -300
- package/backend/ws/terminal/access.ts +0 -56
- package/backend/ws/terminal/persistence.ts +0 -145
- package/backend/ws/terminal/session.ts +0 -470
- package/backend/ws/terminal/stream.ts +0 -82
- 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
|
/**
|
|
@@ -7,11 +7,7 @@ const mockGetProjectChatSessions = mock(() => new Map());
|
|
|
7
7
|
const mockEmitUser = mock(() => {});
|
|
8
8
|
|
|
9
9
|
const mockKillSession = mock(() => {});
|
|
10
|
-
const
|
|
11
|
-
sessionId: string;
|
|
12
|
-
projectId?: string;
|
|
13
|
-
userId: string;
|
|
14
|
-
}>);
|
|
10
|
+
const mockList = mock((_namespace: string) => [] as Array<{ sessionId: string }>);
|
|
15
11
|
|
|
16
12
|
mock.module('$backend/utils/ws', () => ({
|
|
17
13
|
ws: {
|
|
@@ -24,9 +20,9 @@ mock.module('$backend/utils/ws', () => ({
|
|
|
24
20
|
}
|
|
25
21
|
}));
|
|
26
22
|
|
|
27
|
-
mock.module('$backend/terminal/
|
|
28
|
-
|
|
29
|
-
|
|
23
|
+
mock.module('$backend/terminal/ptykit', () => ({
|
|
24
|
+
ptyKitManager: {
|
|
25
|
+
list: mockList,
|
|
30
26
|
killSession: mockKillSession
|
|
31
27
|
}
|
|
32
28
|
}));
|
|
@@ -38,7 +34,7 @@ describe('invalidateUserSessions', () => {
|
|
|
38
34
|
mockGetProjectChatSessions.mockClear();
|
|
39
35
|
mockEmitUser.mockClear();
|
|
40
36
|
mockKillSession.mockClear();
|
|
41
|
-
|
|
37
|
+
mockList.mockClear();
|
|
42
38
|
});
|
|
43
39
|
|
|
44
40
|
test('clears auth on all connections for a user', () => {
|
|
@@ -62,33 +58,33 @@ describe('invalidateUserSessions', () => {
|
|
|
62
58
|
expect(cleared).toBe(0);
|
|
63
59
|
});
|
|
64
60
|
|
|
65
|
-
test('kills
|
|
61
|
+
test('kills all PTY sessions in the project namespace on access revocation', () => {
|
|
66
62
|
mockGetConnectionsForUser.mockReturnValue(['conn1']);
|
|
67
63
|
mockClearAuthForConnections.mockReturnValue(1);
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
{ sessionId: '
|
|
64
|
+
// PtyKit lists sessions by namespace (= projectId); collaborative terminals
|
|
65
|
+
// are project-scoped, so all of proj-1's sessions are torn down.
|
|
66
|
+
mockList.mockReturnValue([
|
|
67
|
+
{ sessionId: 'session-a' },
|
|
68
|
+
{ sessionId: 'session-b' }
|
|
72
69
|
]);
|
|
73
70
|
|
|
74
71
|
invalidateUserSessions('bob', 'proj-1');
|
|
75
72
|
|
|
76
|
-
expect(
|
|
77
|
-
expect(mockKillSession).
|
|
73
|
+
expect(mockList).toHaveBeenCalledWith('proj-1');
|
|
74
|
+
expect(mockKillSession).toHaveBeenCalledTimes(2);
|
|
75
|
+
expect(mockKillSession).toHaveBeenCalledWith('session-a', 'SIGKILL');
|
|
76
|
+
expect(mockKillSession).toHaveBeenCalledWith('session-b', 'SIGKILL');
|
|
78
77
|
});
|
|
79
78
|
|
|
80
79
|
test('kills PTY sessions when user has no websocket connections but project access was revoked', () => {
|
|
81
80
|
mockGetConnectionsForUser.mockReturnValue([]);
|
|
82
|
-
|
|
83
|
-
{ sessionId: 'bob-session', projectId: 'proj-1', userId: 'bob' },
|
|
84
|
-
{ sessionId: 'alice-session', projectId: 'proj-1', userId: 'alice' }
|
|
85
|
-
]);
|
|
81
|
+
mockList.mockReturnValue([{ sessionId: 'session-a' }]);
|
|
86
82
|
|
|
87
83
|
const cleared = invalidateUserSessions('bob', 'proj-1');
|
|
88
84
|
|
|
89
85
|
expect(cleared).toBe(0);
|
|
90
86
|
expect(mockKillSession).toHaveBeenCalledTimes(1);
|
|
91
|
-
expect(mockKillSession).toHaveBeenCalledWith('
|
|
87
|
+
expect(mockKillSession).toHaveBeenCalledWith('session-a', 'SIGKILL');
|
|
92
88
|
});
|
|
93
89
|
});
|
|
94
90
|
|
|
@@ -7,7 +7,7 @@
|
|
|
7
7
|
|
|
8
8
|
import { ws } from '$backend/utils/ws';
|
|
9
9
|
import { debug } from '$shared/utils/logger';
|
|
10
|
-
import {
|
|
10
|
+
import { ptyKitManager } from '$backend/terminal/ptykit';
|
|
11
11
|
|
|
12
12
|
/**
|
|
13
13
|
* Invalidate all active WebSocket sessions for a specific user.
|
|
@@ -46,23 +46,22 @@ export function invalidateUserSessions(userId: string, projectId?: string): numb
|
|
|
46
46
|
}
|
|
47
47
|
|
|
48
48
|
/**
|
|
49
|
-
* Kill PTY terminal sessions
|
|
50
|
-
* Prevents orphaned shell processes from continuing to run
|
|
51
|
-
*
|
|
49
|
+
* Kill PTY terminal sessions in a project when a user's access is revoked.
|
|
50
|
+
* Prevents orphaned shell processes from continuing to run. Terminals are
|
|
51
|
+
* collaborative and project-scoped (PtyKit keys sessions by namespace =
|
|
52
|
+
* projectId), so revoking access tears down that project's terminals.
|
|
52
53
|
*/
|
|
53
54
|
function killUserPtySessionsForProject(userId: string, projectId: string): void {
|
|
54
55
|
let killedCount = 0;
|
|
55
56
|
|
|
56
|
-
for (const session of
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
killedCount++;
|
|
61
|
-
}
|
|
57
|
+
for (const session of ptyKitManager.list(projectId)) {
|
|
58
|
+
debug.log('auth', `Killing PTY session ${session.sessionId} (project ${projectId} access revoked for user ${userId})`);
|
|
59
|
+
ptyKitManager.killSession(session.sessionId, 'SIGKILL');
|
|
60
|
+
killedCount++;
|
|
62
61
|
}
|
|
63
62
|
|
|
64
63
|
if (killedCount > 0) {
|
|
65
|
-
debug.log('auth', `Killed ${killedCount} PTY session(s)
|
|
64
|
+
debug.log('auth', `Killed ${killedCount} PTY session(s) in project ${projectId}`);
|
|
66
65
|
}
|
|
67
66
|
}
|
|
68
67
|
|
|
@@ -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
|
+
};
|
|
@@ -100,8 +100,8 @@ export const CLAUDE_CODE_MODELS: EngineModel[] = [
|
|
|
100
100
|
type: 'claude-code',
|
|
101
101
|
provider: 'anthropic',
|
|
102
102
|
model: {
|
|
103
|
-
id: 'claude-sonnet-
|
|
104
|
-
name: 'Claude Sonnet
|
|
103
|
+
id: 'claude-sonnet-5',
|
|
104
|
+
name: 'Claude Sonnet 5',
|
|
105
105
|
},
|
|
106
106
|
account: {
|
|
107
107
|
id: 0,
|
|
@@ -110,7 +110,7 @@ export const CLAUDE_CODE_MODELS: EngineModel[] = [
|
|
|
110
110
|
},
|
|
111
111
|
limit: {
|
|
112
112
|
input: 1_000_000,
|
|
113
|
-
output:
|
|
113
|
+
output: 128_000,
|
|
114
114
|
},
|
|
115
115
|
modalities: {
|
|
116
116
|
input: {
|
|
@@ -224,6 +224,49 @@ export const CLAUDE_CODE_MODELS: EngineModel[] = [
|
|
|
224
224
|
output: 25,
|
|
225
225
|
},
|
|
226
226
|
},
|
|
227
|
+
{
|
|
228
|
+
engine: {
|
|
229
|
+
type: 'claude-code',
|
|
230
|
+
provider: 'anthropic',
|
|
231
|
+
model: {
|
|
232
|
+
id: 'claude-sonnet-4-6',
|
|
233
|
+
name: 'Claude Sonnet 4.6',
|
|
234
|
+
},
|
|
235
|
+
account: {
|
|
236
|
+
id: 0,
|
|
237
|
+
name: '',
|
|
238
|
+
},
|
|
239
|
+
},
|
|
240
|
+
limit: {
|
|
241
|
+
input: 1_000_000,
|
|
242
|
+
output: 128_000,
|
|
243
|
+
},
|
|
244
|
+
modalities: {
|
|
245
|
+
input: {
|
|
246
|
+
text: true,
|
|
247
|
+
image: true,
|
|
248
|
+
audio: false,
|
|
249
|
+
video: false,
|
|
250
|
+
pdf: true,
|
|
251
|
+
},
|
|
252
|
+
output: {
|
|
253
|
+
text: true,
|
|
254
|
+
image: false,
|
|
255
|
+
audio: false,
|
|
256
|
+
video: false,
|
|
257
|
+
pdf: false,
|
|
258
|
+
},
|
|
259
|
+
},
|
|
260
|
+
capabilities: {
|
|
261
|
+
reasoning: true,
|
|
262
|
+
tools: true,
|
|
263
|
+
structuredOutput: true,
|
|
264
|
+
},
|
|
265
|
+
cost: {
|
|
266
|
+
input: 3,
|
|
267
|
+
output: 15,
|
|
268
|
+
},
|
|
269
|
+
},
|
|
227
270
|
{
|
|
228
271
|
engine: {
|
|
229
272
|
type: 'claude-code',
|
|
@@ -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
|
|