@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
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Subagent Queries
|
|
3
|
+
*
|
|
4
|
+
* CRUD for user-managed custom Subagents (Settings → Subagents). Subagents are
|
|
5
|
+
* Skills-shaped (a Markdown document with frontmatter) plus a per-engine tool
|
|
6
|
+
* allowlist and per-engine model override (stored as JSON maps keyed by
|
|
7
|
+
* EngineType). The `subagents` table holds metadata + the enable toggle; the
|
|
8
|
+
* document body lives on disk under `{clopenDir}/subagents/<slug>.md` (see
|
|
9
|
+
* `backend/subagents/store.ts`).
|
|
10
|
+
*/
|
|
11
|
+
|
|
12
|
+
import { getDatabase } from '../index';
|
|
13
|
+
|
|
14
|
+
export type SubagentSource = 'custom' | 'imported';
|
|
15
|
+
|
|
16
|
+
export interface SubagentRow {
|
|
17
|
+
id: number;
|
|
18
|
+
slug: string;
|
|
19
|
+
name: string;
|
|
20
|
+
description: string;
|
|
21
|
+
/** JSON map of EngineType → comma-separated tool allowlist ({} = all tools). */
|
|
22
|
+
tools_by_engine: string;
|
|
23
|
+
/** JSON map of EngineType → model id ({} = inherit everywhere). */
|
|
24
|
+
model_by_engine: string;
|
|
25
|
+
source: SubagentSource;
|
|
26
|
+
is_enabled: number;
|
|
27
|
+
created_at: string;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export interface SubagentInput {
|
|
31
|
+
slug: string;
|
|
32
|
+
name: string;
|
|
33
|
+
description: string;
|
|
34
|
+
/** JSON string: EngineType → comma-separated tool allowlist. */
|
|
35
|
+
toolsByEngine?: string;
|
|
36
|
+
/** JSON string: EngineType → model id. */
|
|
37
|
+
modelByEngine?: string;
|
|
38
|
+
source?: SubagentSource;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
export const subagentQueries = {
|
|
42
|
+
getAll(): SubagentRow[] {
|
|
43
|
+
return getDatabase().prepare(`SELECT * FROM subagents ORDER BY created_at ASC`).all() as SubagentRow[];
|
|
44
|
+
},
|
|
45
|
+
|
|
46
|
+
getEnabled(): SubagentRow[] {
|
|
47
|
+
return getDatabase().prepare(`SELECT * FROM subagents WHERE is_enabled = 1 ORDER BY created_at ASC`).all() as SubagentRow[];
|
|
48
|
+
},
|
|
49
|
+
|
|
50
|
+
getById(id: number): SubagentRow | null {
|
|
51
|
+
return getDatabase().prepare(`SELECT * FROM subagents WHERE id = ?`).get(id) as SubagentRow | null;
|
|
52
|
+
},
|
|
53
|
+
|
|
54
|
+
getBySlug(slug: string): SubagentRow | null {
|
|
55
|
+
return getDatabase().prepare(`SELECT * FROM subagents WHERE slug = ?`).get(slug) as SubagentRow | null;
|
|
56
|
+
},
|
|
57
|
+
|
|
58
|
+
insert(input: SubagentInput): SubagentRow {
|
|
59
|
+
const result = getDatabase().prepare(
|
|
60
|
+
`INSERT INTO subagents (slug, name, description, tools_by_engine, model_by_engine, source)
|
|
61
|
+
VALUES (?, ?, ?, ?, ?, ?)`
|
|
62
|
+
).run(
|
|
63
|
+
input.slug,
|
|
64
|
+
input.name,
|
|
65
|
+
input.description,
|
|
66
|
+
input.toolsByEngine ?? '{}',
|
|
67
|
+
input.modelByEngine ?? '{}',
|
|
68
|
+
input.source ?? 'custom'
|
|
69
|
+
) as { lastInsertRowid: number | bigint };
|
|
70
|
+
return this.getById(Number(result.lastInsertRowid))!;
|
|
71
|
+
},
|
|
72
|
+
|
|
73
|
+
updateMeta(
|
|
74
|
+
id: number,
|
|
75
|
+
name: string,
|
|
76
|
+
description: string,
|
|
77
|
+
toolsByEngine: string,
|
|
78
|
+
modelByEngine: string
|
|
79
|
+
): void {
|
|
80
|
+
getDatabase().prepare(
|
|
81
|
+
`UPDATE subagents SET name = ?, description = ?, tools_by_engine = ?, model_by_engine = ? WHERE id = ?`
|
|
82
|
+
).run(name, description, toolsByEngine, modelByEngine, id);
|
|
83
|
+
},
|
|
84
|
+
|
|
85
|
+
setEnabled(id: number, enabled: boolean): void {
|
|
86
|
+
getDatabase().prepare(`UPDATE subagents SET is_enabled = ? WHERE id = ?`).run(enabled ? 1 : 0, id);
|
|
87
|
+
},
|
|
88
|
+
|
|
89
|
+
remove(id: number): void {
|
|
90
|
+
getDatabase().prepare(`DELETE FROM subagents WHERE id = ?`).run(id);
|
|
91
|
+
}
|
|
92
|
+
};
|
|
@@ -18,6 +18,7 @@ import type {
|
|
|
18
18
|
import type {
|
|
19
19
|
AlterOperation,
|
|
20
20
|
DbClientDriverAdapter,
|
|
21
|
+
DbClientTxContext,
|
|
21
22
|
IndexDefinition,
|
|
22
23
|
SchemaOpts,
|
|
23
24
|
TableDefinition
|
|
@@ -157,6 +158,26 @@ export class MysqlAdapter implements DbClientDriverAdapter {
|
|
|
157
158
|
return this.executeRead(`EXPLAIN ${q}`, [], opts);
|
|
158
159
|
}
|
|
159
160
|
|
|
161
|
+
async withTransaction<T>(fn: (tx: DbClientTxContext) => Promise<T>, opts?: { database?: string }): Promise<T> {
|
|
162
|
+
await this.ensureDatabase(opts?.database);
|
|
163
|
+
const sql = this.requireSql();
|
|
164
|
+
// Bun.sql reserves one connection for the `begin` block. Note: MySQL
|
|
165
|
+
// implicitly commits on DDL (CREATE/ALTER/DROP/…), so a batch that
|
|
166
|
+
// mixes DDL with later failures cannot fully roll back the DDL — a
|
|
167
|
+
// server limitation, not an app one.
|
|
168
|
+
return sql.begin(async (tx) => {
|
|
169
|
+
const run = async (q: string, params: unknown[] = []): Promise<DbClientQueryResult> => {
|
|
170
|
+
const start = performance.now();
|
|
171
|
+
const raw = await tx.unsafe(q, params as never);
|
|
172
|
+
return normalizeBunSqlResult(raw, Math.round(performance.now() - start));
|
|
173
|
+
};
|
|
174
|
+
return fn({
|
|
175
|
+
executeRead: (q, params) => run(q, params ?? []),
|
|
176
|
+
executeWrite: (q, params) => run(q, params ?? [])
|
|
177
|
+
});
|
|
178
|
+
}) as Promise<T>;
|
|
179
|
+
}
|
|
180
|
+
|
|
160
181
|
// ── Overview ──────────────────────────────────────────────────────────
|
|
161
182
|
|
|
162
183
|
async overview(opts?: SchemaOpts): Promise<DbClientOverview> {
|
|
@@ -18,6 +18,7 @@ import type {
|
|
|
18
18
|
import type {
|
|
19
19
|
AlterOperation,
|
|
20
20
|
DbClientDriverAdapter,
|
|
21
|
+
DbClientTxContext,
|
|
21
22
|
IndexDefinition,
|
|
22
23
|
SchemaOpts,
|
|
23
24
|
TableDefinition
|
|
@@ -186,6 +187,25 @@ export class PostgresAdapter implements DbClientDriverAdapter {
|
|
|
186
187
|
return this.executeRead(`EXPLAIN ${q}`, [], opts);
|
|
187
188
|
}
|
|
188
189
|
|
|
190
|
+
async withTransaction<T>(fn: (tx: DbClientTxContext) => Promise<T>, opts?: { database?: string }): Promise<T> {
|
|
191
|
+
await this.ensureDatabase(opts?.database);
|
|
192
|
+
const sql = this.requireSql();
|
|
193
|
+
// Bun.sql reserves a single connection for the duration of `begin`, so
|
|
194
|
+
// every statement below shares one transaction. Postgres wraps DDL in
|
|
195
|
+
// the transaction too, so a mid-batch failure rolls everything back.
|
|
196
|
+
return sql.begin(async (tx) => {
|
|
197
|
+
const run = async (q: string, params: unknown[] = []): Promise<DbClientQueryResult> => {
|
|
198
|
+
const start = performance.now();
|
|
199
|
+
const raw = await tx.unsafe(q, params as never);
|
|
200
|
+
return normalizeBunSqlResult(raw, Math.round(performance.now() - start));
|
|
201
|
+
};
|
|
202
|
+
return fn({
|
|
203
|
+
executeRead: (q, params) => run(q, params ?? []),
|
|
204
|
+
executeWrite: (q, params) => run(q, params ?? [])
|
|
205
|
+
});
|
|
206
|
+
}) as Promise<T>;
|
|
207
|
+
}
|
|
208
|
+
|
|
189
209
|
// ── Overview ──────────────────────────────────────────────────────────
|
|
190
210
|
|
|
191
211
|
async overview(opts?: SchemaOpts): Promise<DbClientOverview> {
|
|
@@ -20,6 +20,7 @@ import type {
|
|
|
20
20
|
import type {
|
|
21
21
|
AlterOperation,
|
|
22
22
|
DbClientDriverAdapter,
|
|
23
|
+
DbClientTxContext,
|
|
23
24
|
IndexDefinition,
|
|
24
25
|
SchemaOpts,
|
|
25
26
|
TableDefinition
|
|
@@ -152,6 +153,26 @@ export class SqliteAdapter implements DbClientDriverAdapter {
|
|
|
152
153
|
return this.executeRead(`EXPLAIN QUERY PLAN ${q}`);
|
|
153
154
|
}
|
|
154
155
|
|
|
156
|
+
async withTransaction<T>(fn: (tx: DbClientTxContext) => Promise<T>): Promise<T> {
|
|
157
|
+
const db = this.requireDb();
|
|
158
|
+
db.exec('BEGIN');
|
|
159
|
+
try {
|
|
160
|
+
const out = await fn({
|
|
161
|
+
executeRead: (q, params) => this.executeRead(q, params ?? []),
|
|
162
|
+
executeWrite: (q, params) => this.executeWrite(q, params ?? [])
|
|
163
|
+
});
|
|
164
|
+
db.exec('COMMIT');
|
|
165
|
+
return out;
|
|
166
|
+
} catch (err) {
|
|
167
|
+
try {
|
|
168
|
+
db.exec('ROLLBACK');
|
|
169
|
+
} catch {
|
|
170
|
+
// Rollback failure is secondary to the error that triggered it.
|
|
171
|
+
}
|
|
172
|
+
throw err;
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
|
|
155
176
|
// ── Overview ──────────────────────────────────────────────────────────
|
|
156
177
|
|
|
157
178
|
async overview(): Promise<DbClientOverview> {
|
|
@@ -51,6 +51,16 @@ export type AlterOperation =
|
|
|
51
51
|
| { kind: 'rename-column'; name: string; newName: string }
|
|
52
52
|
| { kind: 'modify-column'; column: ColumnDefinition };
|
|
53
53
|
|
|
54
|
+
/**
|
|
55
|
+
* A connection-bound executor handed to `withTransaction`'s callback. Every
|
|
56
|
+
* call runs on the same transaction's connection, so a batch of statements
|
|
57
|
+
* commits or rolls back atomically.
|
|
58
|
+
*/
|
|
59
|
+
export interface DbClientTxContext {
|
|
60
|
+
executeRead(q: string, params?: unknown[], opts?: { database?: string; limit?: number }): Promise<DbClientQueryResult>;
|
|
61
|
+
executeWrite(q: string, params?: unknown[], opts?: { database?: string }): Promise<DbClientQueryResult>;
|
|
62
|
+
}
|
|
63
|
+
|
|
54
64
|
export interface DbClientDriverAdapter {
|
|
55
65
|
readonly kind: DbDriver;
|
|
56
66
|
|
|
@@ -75,6 +85,15 @@ export interface DbClientDriverAdapter {
|
|
|
75
85
|
explain?(q: string, opts?: { database?: string }): Promise<DbClientQueryResult>;
|
|
76
86
|
cancel?(): Promise<void>;
|
|
77
87
|
|
|
88
|
+
/**
|
|
89
|
+
* Run `fn` inside a single database transaction on one dedicated
|
|
90
|
+
* connection. Implemented only by drivers that can guarantee atomicity
|
|
91
|
+
* (a pooled driver must reserve a connection). If `fn` throws, the
|
|
92
|
+
* transaction is rolled back and the error re-thrown. Absence of this
|
|
93
|
+
* method signals the caller to fall back to non-transactional execution.
|
|
94
|
+
*/
|
|
95
|
+
withTransaction?<T>(fn: (tx: DbClientTxContext) => Promise<T>, opts?: { database?: string }): Promise<T>;
|
|
96
|
+
|
|
78
97
|
// Structure
|
|
79
98
|
createDatabase?(name: string): Promise<string>;
|
|
80
99
|
dropDatabase?(name: string): Promise<string>;
|
|
@@ -5,10 +5,12 @@
|
|
|
5
5
|
*/
|
|
6
6
|
|
|
7
7
|
import type {
|
|
8
|
+
DbClientBatchResult,
|
|
8
9
|
DbClientQueryResult,
|
|
10
|
+
DbClientStatementResult,
|
|
9
11
|
DbDriver
|
|
10
12
|
} from '$shared/types/db-client';
|
|
11
|
-
import type { DbClientDriverAdapter } from './drivers/types';
|
|
13
|
+
import type { DbClientDriverAdapter, DbClientTxContext } from './drivers/types';
|
|
12
14
|
|
|
13
15
|
export type QueryClass = 'read' | 'write' | 'ddl' | 'unknown';
|
|
14
16
|
|
|
@@ -124,3 +126,89 @@ export async function runSafely(input: RunSafelyInput): Promise<DbClientQueryRes
|
|
|
124
126
|
if (!fn) throw new Error(`Driver ${driver} does not support ${mode}`);
|
|
125
127
|
return fn.call(adapter, query, params, { database });
|
|
126
128
|
}
|
|
129
|
+
|
|
130
|
+
interface ExecuteBatchInput {
|
|
131
|
+
driver: DbDriver;
|
|
132
|
+
adapter: DbClientDriverAdapter;
|
|
133
|
+
statements: string[];
|
|
134
|
+
params?: unknown[];
|
|
135
|
+
database?: string;
|
|
136
|
+
limit?: number;
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
function skippedStatement(index: number, query: string, queryClass: QueryClass): DbClientStatementResult {
|
|
140
|
+
return { index, query, queryClass, status: 'skipped', result: null, error: null, durationMs: 0 };
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
/**
|
|
144
|
+
* Execute a pre-split batch of statements in order. Each statement is
|
|
145
|
+
* classified individually and routed to read (auto-LIMITed) or write
|
|
146
|
+
* execution accordingly — the classification of the whole batch never lets a
|
|
147
|
+
* write ride in on the read path. When the driver supports transactions the
|
|
148
|
+
* batch is atomic: the first failure rolls the whole batch back and every
|
|
149
|
+
* later statement is reported as `skipped`.
|
|
150
|
+
*/
|
|
151
|
+
export async function executeBatch(input: ExecuteBatchInput): Promise<DbClientBatchResult> {
|
|
152
|
+
const { driver, adapter, statements, params, database, limit } = input;
|
|
153
|
+
|
|
154
|
+
const runAll = async (exec: DbClientTxContext): Promise<{ results: DbClientStatementResult[]; totalDurationMs: number; failed: boolean }> => {
|
|
155
|
+
const results: DbClientStatementResult[] = [];
|
|
156
|
+
let totalDurationMs = 0;
|
|
157
|
+
let failed = false;
|
|
158
|
+
for (let index = 0; index < statements.length; index++) {
|
|
159
|
+
const query = statements[index];
|
|
160
|
+
const queryClass = classifyQuery(driver, query);
|
|
161
|
+
if (failed) {
|
|
162
|
+
results.push(skippedStatement(index, query, queryClass));
|
|
163
|
+
continue;
|
|
164
|
+
}
|
|
165
|
+
try {
|
|
166
|
+
const result = queryClass === 'read'
|
|
167
|
+
? await exec.executeRead(applyAutoLimit(query, limit ?? 500), params, { database })
|
|
168
|
+
: await exec.executeWrite(query, params, { database });
|
|
169
|
+
totalDurationMs += result.durationMs;
|
|
170
|
+
results.push({ index, query, queryClass, status: 'success', result, error: null, durationMs: result.durationMs });
|
|
171
|
+
} catch (err) {
|
|
172
|
+
failed = true;
|
|
173
|
+
results.push({
|
|
174
|
+
index,
|
|
175
|
+
query,
|
|
176
|
+
queryClass,
|
|
177
|
+
status: 'error',
|
|
178
|
+
result: null,
|
|
179
|
+
error: err instanceof Error ? err.message : String(err),
|
|
180
|
+
durationMs: 0
|
|
181
|
+
});
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
return { results, totalDurationMs, failed };
|
|
185
|
+
};
|
|
186
|
+
|
|
187
|
+
if (typeof adapter.withTransaction === 'function' && statements.length > 1) {
|
|
188
|
+
let captured: { results: DbClientStatementResult[]; totalDurationMs: number; failed: boolean } | null = null;
|
|
189
|
+
try {
|
|
190
|
+
await adapter.withTransaction(async (tx) => {
|
|
191
|
+
captured = await runAll(tx);
|
|
192
|
+
// Throw to force a rollback while preserving the per-statement report.
|
|
193
|
+
if (captured.failed) throw new BatchRollbackSignal();
|
|
194
|
+
}, { database });
|
|
195
|
+
} catch (err) {
|
|
196
|
+
if (!(err instanceof BatchRollbackSignal)) throw err;
|
|
197
|
+
}
|
|
198
|
+
// `captured` is always assigned unless withTransaction never ran the
|
|
199
|
+
// callback (which would have thrown a non-signal error above).
|
|
200
|
+
const c = captured as unknown as { results: DbClientStatementResult[]; totalDurationMs: number; failed: boolean };
|
|
201
|
+
return { statements: c.results, totalDurationMs: c.totalDurationMs, transaction: true, ok: !c.failed };
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
// Non-transactional fallback: statements run sequentially and independently.
|
|
205
|
+
const direct: DbClientTxContext = {
|
|
206
|
+
executeRead: (q, p, o) => runSafely({ driver, adapter, query: q, params: p, mode: 'read', database: o?.database, limit: o?.limit }),
|
|
207
|
+
executeWrite: (q, p, o) => runSafely({ driver, adapter, query: q, params: p, mode: 'write', database: o?.database })
|
|
208
|
+
};
|
|
209
|
+
const { results, totalDurationMs, failed } = await runAll(direct);
|
|
210
|
+
return { statements: results, totalDurationMs, transaction: false, ok: !failed };
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
/** Internal sentinel: thrown to trigger a transaction rollback on batch failure. */
|
|
214
|
+
class BatchRollbackSignal extends Error {}
|
|
@@ -28,6 +28,9 @@ import { setupEnvironmentOnce, getEngineEnv } from './environment';
|
|
|
28
28
|
import { handleStreamError } from './error-handler';
|
|
29
29
|
import { getEnabledMcpServers, getAllowedMcpTools } from '../../../mcp';
|
|
30
30
|
import { syncSkills } from '$backend/skills';
|
|
31
|
+
import { syncEngineArtifacts } from '$backend/engine/artifact-sync';
|
|
32
|
+
import { artifactFilter } from '$backend/profiles';
|
|
33
|
+
import { resolvePermissionsFromDb, isToolAllowed, syncPermissions } from '$backend/permissions';
|
|
31
34
|
import type { AIEngine, EngineQueryOptions } from '../../types';
|
|
32
35
|
import type { EngineModel } from '$shared/types/unified';
|
|
33
36
|
import { CLAUDE_CODE_MODELS } from './models';
|
|
@@ -99,13 +102,28 @@ export class ClaudeCodeEngine implements AIEngine {
|
|
|
99
102
|
const resolvedProjectPath = resolveOsPath(projectPath);
|
|
100
103
|
|
|
101
104
|
try {
|
|
105
|
+
// Active Profile for this stream (resolved in stream-manager). Scopes the
|
|
106
|
+
// materialized artifact set + MCP connectors to the profile's bundle.
|
|
107
|
+
const profileId = options.mcpContext?.profileId;
|
|
108
|
+
const mcpProfileFilter = artifactFilter(profileId, 'mcp') ?? undefined;
|
|
109
|
+
|
|
102
110
|
// Materialize enabled skills into Claude's native skills dir before the
|
|
103
111
|
// session starts so the SDK picks them up via settingSources.
|
|
104
|
-
await syncSkills('claude');
|
|
112
|
+
await syncSkills('claude', profileId);
|
|
113
|
+
// Commands, Subagents, and global Instructions share the same trigger.
|
|
114
|
+
await syncEngineArtifacts('claude', profileId);
|
|
115
|
+
// Write the resolved allow/deny into the isolated settings.json (honesty
|
|
116
|
+
// layer — the runtime hook below is the authoritative enforcement).
|
|
117
|
+
await syncPermissions('claude');
|
|
118
|
+
|
|
119
|
+
// Resolve the effective permission policy once per stream; the canUseTool
|
|
120
|
+
// hook consults it to actually block denied tools (Clopen otherwise
|
|
121
|
+
// auto-allows everything, so this hook is where deny gets its teeth).
|
|
122
|
+
const permissions = resolvePermissionsFromDb('claude-code', options.mcpContext?.projectId, profileId);
|
|
105
123
|
|
|
106
124
|
// Get custom MCP servers and allowed tools
|
|
107
125
|
// Pass mcpContext so tool handlers are bound to the correct project
|
|
108
|
-
const mcpServers = getEnabledMcpServers(options.mcpContext);
|
|
126
|
+
const mcpServers = getEnabledMcpServers(options.mcpContext, mcpProfileFilter);
|
|
109
127
|
const allowedMcpTools = getAllowedMcpTools();
|
|
110
128
|
|
|
111
129
|
debug.log('mcp', '📦 Loading custom MCP servers...');
|
|
@@ -157,7 +175,13 @@ export class ClaudeCodeEngine implements AIEngine {
|
|
|
157
175
|
});
|
|
158
176
|
});
|
|
159
177
|
}
|
|
160
|
-
//
|
|
178
|
+
// Enforce the resolved permission policy: deny blocks the tool, an
|
|
179
|
+
// allowlist (when set) blocks anything not on it. Everything else is
|
|
180
|
+
// auto-allowed as before.
|
|
181
|
+
if (!isToolAllowed(permissions, _toolName)) {
|
|
182
|
+
debug.log('permissions', `⛔ Blocked tool "${_toolName}" (Clopen permission policy)`);
|
|
183
|
+
return { behavior: 'deny' as const, message: `Blocked by Clopen permission policy: ${_toolName}` };
|
|
184
|
+
}
|
|
161
185
|
return { behavior: 'allow' as const, updatedInput: input };
|
|
162
186
|
},
|
|
163
187
|
...(modelId && { model: modelId }),
|
|
@@ -28,7 +28,9 @@ 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 { artifactFilter } from '$backend/profiles';
|
|
31
32
|
import { syncSkills } from '$backend/skills';
|
|
33
|
+
import { syncEngineArtifacts, buildArtifactsPromptContext } from '$backend/engine/artifact-sync';
|
|
32
34
|
import { CODEX_MODELS } from './models';
|
|
33
35
|
import { debug } from '$shared/utils/logger';
|
|
34
36
|
import { handleStreamError, buildTurnError } from './error-handler';
|
|
@@ -62,6 +64,13 @@ export class CodexEngine implements AIEngine {
|
|
|
62
64
|
private activeController: AbortController | null = null;
|
|
63
65
|
/** Account ID currently baked into `this.codex`. Same trade-off as Copilot. */
|
|
64
66
|
private currentAccountId: number | null = null;
|
|
67
|
+
/**
|
|
68
|
+
* Profile connector-filter signature baked into `this.codex`. Codex takes its
|
|
69
|
+
* MCP set at construction, so scoping connectors to a Profile means rebuilding
|
|
70
|
+
* the client when the filter changes (same trade-off as an account switch).
|
|
71
|
+
* `'*'` = unfiltered (no profile constraint). `null` = not initialized.
|
|
72
|
+
*/
|
|
73
|
+
private currentMcpFilterKey: string | null = null;
|
|
65
74
|
|
|
66
75
|
get isInitialized(): boolean {
|
|
67
76
|
return this._isInitialized;
|
|
@@ -71,8 +80,9 @@ export class CodexEngine implements AIEngine {
|
|
|
71
80
|
return this.activeController !== null;
|
|
72
81
|
}
|
|
73
82
|
|
|
74
|
-
async initialize(accountId?: number): Promise<void> {
|
|
75
|
-
|
|
83
|
+
async initialize(accountId?: number, mcpProfileFilter?: Set<string>): Promise<void> {
|
|
84
|
+
const mcpKey = mcpProfileFilter ? [...mcpProfileFilter].sort().join(',') : '*';
|
|
85
|
+
if (this._isInitialized && (accountId == null || accountId === this.currentAccountId) && mcpKey === this.currentMcpFilterKey) {
|
|
76
86
|
return;
|
|
77
87
|
}
|
|
78
88
|
|
|
@@ -94,7 +104,7 @@ export class CodexEngine implements AIEngine {
|
|
|
94
104
|
applyAccountAuth(account);
|
|
95
105
|
|
|
96
106
|
const codexBinary = resolveBinary('codex');
|
|
97
|
-
const mcpConfig = getCodexMcpConfig();
|
|
107
|
+
const mcpConfig = getCodexMcpConfig(mcpProfileFilter);
|
|
98
108
|
|
|
99
109
|
// Codex SDK takes config at construction. We pass `show_raw_agent_reasoning`
|
|
100
110
|
// (so the SDK forwards reasoning text events) and forward the Clopen MCP
|
|
@@ -119,14 +129,16 @@ export class CodexEngine implements AIEngine {
|
|
|
119
129
|
},
|
|
120
130
|
});
|
|
121
131
|
this.currentAccountId = account.id;
|
|
132
|
+
this.currentMcpFilterKey = mcpKey;
|
|
122
133
|
this._isInitialized = true;
|
|
123
|
-
debug.log('engine', `Codex engine initialized (account ${account.id}, mode=${credential.kind})`);
|
|
134
|
+
debug.log('engine', `Codex engine initialized (account ${account.id}, mode=${credential.kind}, mcpFilter=${mcpKey})`);
|
|
124
135
|
}
|
|
125
136
|
|
|
126
137
|
async dispose(): Promise<void> {
|
|
127
138
|
await this.cancel();
|
|
128
139
|
this.codex = null;
|
|
129
140
|
this.currentAccountId = null;
|
|
141
|
+
this.currentMcpFilterKey = null;
|
|
130
142
|
this._isInitialized = false;
|
|
131
143
|
debug.log('engine', 'Codex engine disposed');
|
|
132
144
|
}
|
|
@@ -139,18 +151,28 @@ export class CodexEngine implements AIEngine {
|
|
|
139
151
|
async *streamQuery(options: EngineQueryOptions): AsyncGenerator<EngineOutput, void, unknown> {
|
|
140
152
|
const { projectPath, prompt, resume, modelId, abortController, accountId } = options;
|
|
141
153
|
|
|
154
|
+
// Active Profile for this stream — scopes the materialized artifact set AND
|
|
155
|
+
// (below) the MCP connector set baked into the Codex client.
|
|
156
|
+
const profileId = options.mcpContext?.profileId;
|
|
142
157
|
// Refresh the synthetic skills preamble in CODEX_HOME before the turn.
|
|
143
|
-
await syncSkills('codex');
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
//
|
|
147
|
-
// re-creating the
|
|
148
|
-
|
|
149
|
-
|
|
158
|
+
await syncSkills('codex', profileId);
|
|
159
|
+
await syncEngineArtifacts('codex', profileId);
|
|
160
|
+
|
|
161
|
+
// Per-stream account/profile override — the SDK bakes both the apiKey and the
|
|
162
|
+
// MCP set at construction, so a change in either requires re-creating the
|
|
163
|
+
// client. The connector filter narrows MCP to the Profile's set (like Claude/
|
|
164
|
+
// Qwen/Copilot do per stream); `undefined` = unfiltered → no change for the
|
|
165
|
+
// common no-profile path.
|
|
166
|
+
const mcpProfileFilter = artifactFilter(profileId, 'mcp') ?? undefined;
|
|
167
|
+
const mcpKey = mcpProfileFilter ? [...mcpProfileFilter].sort().join(',') : '*';
|
|
168
|
+
const accountChanged = this._isInitialized && accountId != null && accountId !== this.currentAccountId;
|
|
169
|
+
const mcpChanged = this._isInitialized && mcpKey !== this.currentMcpFilterKey;
|
|
170
|
+
if (accountChanged || mcpChanged) {
|
|
171
|
+
debug.log('engine', `Codex re-initialising (accountChanged=${accountChanged}, mcpChanged=${mcpChanged})`);
|
|
150
172
|
await this.dispose();
|
|
151
173
|
}
|
|
152
174
|
if (!this._isInitialized || !this.codex) {
|
|
153
|
-
await this.initialize(accountId);
|
|
175
|
+
await this.initialize(accountId, mcpProfileFilter);
|
|
154
176
|
}
|
|
155
177
|
if (!this.codex) {
|
|
156
178
|
throw new Error('Codex client unavailable.');
|
|
@@ -207,7 +229,11 @@ export class CodexEngine implements AIEngine {
|
|
|
207
229
|
|
|
208
230
|
this.activeThread = thread;
|
|
209
231
|
|
|
210
|
-
|
|
232
|
+
// Prompt-scoped engine: advertise the profile-scoped Skills/Commands/
|
|
233
|
+
// Subagents PER-SESSION via the prompt (not the shared global AGENTS.md /
|
|
234
|
+
// persistent client) so the active Profile scopes them correctly.
|
|
235
|
+
const artifactsContext = buildArtifactsPromptContext(profileId);
|
|
236
|
+
const input = await buildCodexInput(prompt, artifactsContext || undefined);
|
|
211
237
|
const { events } = await thread.runStreamed(input, {
|
|
212
238
|
signal: this.activeController.signal,
|
|
213
239
|
});
|
|
@@ -357,9 +383,15 @@ export class CodexEngine implements AIEngine {
|
|
|
357
383
|
// Helpers
|
|
358
384
|
// ============================================================================
|
|
359
385
|
|
|
360
|
-
async function buildCodexInput(prompt: EngineQueryOptions['prompt']): Promise<CodexInput> {
|
|
386
|
+
async function buildCodexInput(prompt: EngineQueryOptions['prompt'], prefixText?: string): Promise<CodexInput> {
|
|
361
387
|
const items: Array<{ type: 'text'; text: string } | { type: 'local_image'; path: string }> = [];
|
|
362
388
|
|
|
389
|
+
// Optional per-session context (e.g. the profile-scoped skills preamble),
|
|
390
|
+
// prepended so it leads the turn.
|
|
391
|
+
if (prefixText) {
|
|
392
|
+
items.push({ type: 'text', text: prefixText });
|
|
393
|
+
}
|
|
394
|
+
|
|
363
395
|
for (const block of prompt.content) {
|
|
364
396
|
if (block.type === 'text') {
|
|
365
397
|
items.push({ type: 'text', text: block.text });
|
|
@@ -13,6 +13,8 @@ import type {
|
|
|
13
13
|
ResumeSessionConfig,
|
|
14
14
|
SessionEvent,
|
|
15
15
|
ModelInfo,
|
|
16
|
+
PermissionRequest,
|
|
17
|
+
PermissionRequestResult,
|
|
16
18
|
} from '@github/copilot-sdk';
|
|
17
19
|
import type { EngineOutput, EngineModel } from '$shared/types/unified';
|
|
18
20
|
import type { AIEngine, EngineQueryOptions, StructuredGenerationOptions } from '../../types';
|
|
@@ -21,7 +23,10 @@ import { engineQueries } from '$backend/database/queries/engine-queries';
|
|
|
21
23
|
import { resolveOsPath, getEngineUserConfigDir } from '$backend/utils/paths';
|
|
22
24
|
import { debug } from '$shared/utils/logger';
|
|
23
25
|
import { getCopilotMcpConfig } from '../../../mcp';
|
|
26
|
+
import { artifactFilter } from '$backend/profiles';
|
|
24
27
|
import { syncSkills } from '$backend/skills';
|
|
28
|
+
import { syncEngineArtifacts, buildArtifactsPromptContext } from '$backend/engine/artifact-sync';
|
|
29
|
+
import { resolvePermissionsFromDb, isToolAllowed, type ResolvedPermissions } from '$backend/permissions';
|
|
25
30
|
import { handleStreamError, buildSessionError } from './error-handler';
|
|
26
31
|
import { fetchCopilotModels } from './models';
|
|
27
32
|
|
|
@@ -30,6 +35,33 @@ import { fetchCopilotModels } from './models';
|
|
|
30
35
|
// `onUserInputRequest`'s return type is exactly that shape — derive
|
|
31
36
|
// it from the SessionConfig field so we don't drift from the SDK.
|
|
32
37
|
type UserInputResponse = Awaited<ReturnType<NonNullable<SessionConfig['onUserInputRequest']>>>;
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* Map a Copilot permission request to the token the permission policy matches on.
|
|
41
|
+
* MCP / custom tools carry a `toolName`; everything else is matched by its
|
|
42
|
+
* operation `kind` (`shell` / `write` / `read` / `url` / `memory` / …), which is
|
|
43
|
+
* why the Copilot builtin catalog lists kinds rather than tool names.
|
|
44
|
+
*/
|
|
45
|
+
function copilotPermissionToken(request: PermissionRequest): string {
|
|
46
|
+
const named = (request as { toolName?: string }).toolName;
|
|
47
|
+
return named && named.trim() ? named : request.kind;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* Enforce the resolved permission policy for one Copilot request. Returns a
|
|
52
|
+
* reject decision for blocked tools, or null to fall through to auto-approve.
|
|
53
|
+
*/
|
|
54
|
+
function enforceCopilotPermission(
|
|
55
|
+
permissions: ResolvedPermissions,
|
|
56
|
+
request: PermissionRequest
|
|
57
|
+
): PermissionRequestResult | null {
|
|
58
|
+
const token = copilotPermissionToken(request);
|
|
59
|
+
if (!isToolAllowed(permissions, token)) {
|
|
60
|
+
debug.log('permissions', `⛔ Blocked tool "${token}" (Clopen permission policy)`);
|
|
61
|
+
return { kind: 'reject', feedback: `Blocked by Clopen permission policy: ${token}` };
|
|
62
|
+
}
|
|
63
|
+
return null;
|
|
64
|
+
}
|
|
33
65
|
import {
|
|
34
66
|
createStreamConverterState,
|
|
35
67
|
convertSessionStart,
|
|
@@ -194,8 +226,26 @@ export class CopilotEngine implements AIEngine {
|
|
|
194
226
|
|
|
195
227
|
this.activeController = abortController || new AbortController();
|
|
196
228
|
|
|
229
|
+
// Active Profile for this stream — scopes artifacts + connectors.
|
|
230
|
+
const profileId = options.mcpContext?.profileId;
|
|
231
|
+
const mcpProfileFilter = artifactFilter(profileId, 'mcp') ?? undefined;
|
|
232
|
+
|
|
197
233
|
// Mirror enabled skills into Copilot's native skills dir before the turn.
|
|
198
|
-
await syncSkills('copilot');
|
|
234
|
+
await syncSkills('copilot', profileId);
|
|
235
|
+
await syncEngineArtifacts('copilot', profileId);
|
|
236
|
+
|
|
237
|
+
// Copilot's skills dir (`~/.copilot/skills`) is SHARED across sessions and
|
|
238
|
+
// read by a PERSISTENT runtime, and its Commands/Subagents ride a synthetic
|
|
239
|
+
// global block — none can reliably scope to THIS session's Profile. Inject
|
|
240
|
+
// the profile-scoped Skills/Commands/Subagents preamble into the prompt as
|
|
241
|
+
// the authoritative per-session signal (synthetic commands/subagents are
|
|
242
|
+
// stripped from the global file; the native skill mirror still loads the
|
|
243
|
+
// filtered folders).
|
|
244
|
+
const artifactsContext = buildArtifactsPromptContext(profileId);
|
|
245
|
+
|
|
246
|
+
// Resolve the permission policy once per stream; onPermissionRequest below
|
|
247
|
+
// enforces it (Copilot otherwise approves every tool via approveAll).
|
|
248
|
+
const permissions = resolvePermissionsFromDb('copilot', options.mcpContext?.projectId, profileId);
|
|
199
249
|
|
|
200
250
|
const resolvedProjectPath = resolveOsPath(projectPath);
|
|
201
251
|
const state = createStreamConverterState('', modelId);
|
|
@@ -249,10 +299,11 @@ export class CopilotEngine implements AIEngine {
|
|
|
249
299
|
this.activeController.signal.addEventListener('abort', onAbort, { once: true });
|
|
250
300
|
|
|
251
301
|
try {
|
|
252
|
-
const mcpConfig = getCopilotMcpConfig();
|
|
302
|
+
const mcpConfig = getCopilotMcpConfig(mcpProfileFilter);
|
|
253
303
|
|
|
254
304
|
const baseConfig: ResumeSessionConfig = {
|
|
255
|
-
onPermissionRequest:
|
|
305
|
+
onPermissionRequest: (request, invocation) =>
|
|
306
|
+
enforceCopilotPermission(permissions, request) ?? approveAll(request, invocation),
|
|
256
307
|
// Enables the agent's `ask_user` tool. Without this callback the
|
|
257
308
|
// SDK reports `requestUserInput: false` to the server and the
|
|
258
309
|
// tool is not exposed to the model, so the AskUserQuestion
|
|
@@ -345,7 +396,10 @@ export class CopilotEngine implements AIEngine {
|
|
|
345
396
|
state.sessionId = session.sessionId;
|
|
346
397
|
|
|
347
398
|
// Send the prompt — fire-and-forget; events arrive via the queue.
|
|
348
|
-
const
|
|
399
|
+
const promptText = artifactsContext
|
|
400
|
+
? `${artifactsContext}\n\n${extractPromptText(prompt)}`
|
|
401
|
+
: extractPromptText(prompt);
|
|
402
|
+
const sendPromise = session.send({ prompt: promptText }).catch(error => {
|
|
349
403
|
debug.error('engine', 'Copilot session.send error:', error);
|
|
350
404
|
pushEvent({
|
|
351
405
|
type: 'session.error',
|